diff --git a/COPYING b/COPYING
new file mode 100644
index 0000000..f288702
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..d881b4c
--- /dev/null
+++ b/README.md
@@ -0,0 +1,25 @@
+# THUEDC25
+
+Platform for the 25th Tsinghua University Electronic Design Competition
+
+## Install
+
+Releases of this project do not need to be installed. Just download the latest release and run the executable file.
+
+## Usage
+
+1. Launch the host program.
+
+1. Visit .
+
+1. Connect to the host program.
+
+## Contributing
+
+Ask questions by creating an issue.
+
+PRs accepted.
+
+## License
+
+GPL-3.0-only © THUASTA
diff --git a/host/.editorconfig b/host/.editorconfig
new file mode 100644
index 0000000..24390c7
--- /dev/null
+++ b/host/.editorconfig
@@ -0,0 +1,189 @@
+# editorconfig.org
+
+# top-most EditorConfig file
+root = true
+
+# Default settings:
+# A newline ending every file
+# Use 4 spaces as indentation
+[*]
+insert_final_newline = true
+indent_style = space
+indent_size = 4
+trim_trailing_whitespace = true
+
+# Generated code
+[*{_AssemblyInfo.cs,.notsupported.cs,AsmOffsets.cs}]
+generated_code = true
+
+# C# files
+[*.cs]
+# New line preferences
+csharp_new_line_before_open_brace = all
+csharp_new_line_before_else = true
+csharp_new_line_before_catch = true
+csharp_new_line_before_finally = true
+csharp_new_line_before_members_in_object_initializers = true
+csharp_new_line_before_members_in_anonymous_types = true
+csharp_new_line_between_query_expression_clauses = true
+
+# Indentation preferences
+csharp_indent_block_contents = true
+csharp_indent_braces = false
+csharp_indent_case_contents = true
+csharp_indent_case_contents_when_block = true
+csharp_indent_switch_labels = true
+csharp_indent_labels = one_less_than_current
+
+# Modifier preferences
+csharp_preferred_modifier_order = public,private,protected,internal,file,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,required,volatile,async:error
+
+# avoid this. unless absolutely necessary
+dotnet_style_qualification_for_field = false:error
+dotnet_style_qualification_for_property = false:error
+dotnet_style_qualification_for_method = false:error
+dotnet_style_qualification_for_event = false:error
+
+# Types: use keywords instead of BCL types, and permit var only when the type is clear
+csharp_style_var_for_built_in_types = false:error
+csharp_style_var_when_type_is_apparent = false:none
+csharp_style_var_elsewhere = false:error
+dotnet_style_predefined_type_for_locals_parameters_members = true:error
+dotnet_style_predefined_type_for_member_access = true:error
+
+# name all constant fields using PascalCase
+dotnet_naming_rule.constant_fields_should_be_pascal_case.severity = suggestion
+dotnet_naming_rule.constant_fields_should_be_pascal_case.symbols = constant_fields
+dotnet_naming_rule.constant_fields_should_be_pascal_case.style = pascal_case_style
+dotnet_naming_symbols.constant_fields.applicable_kinds = field
+dotnet_naming_symbols.constant_fields.required_modifiers = const
+dotnet_naming_style.pascal_case_style.capitalization = pascal_case
+
+# static fields should have s_ prefix
+dotnet_naming_rule.static_fields_should_have_prefix.severity = suggestion
+dotnet_naming_rule.static_fields_should_have_prefix.symbols = static_fields
+dotnet_naming_rule.static_fields_should_have_prefix.style = static_prefix_style
+dotnet_naming_symbols.static_fields.applicable_kinds = field
+dotnet_naming_symbols.static_fields.required_modifiers = static
+dotnet_naming_symbols.static_fields.applicable_accessibilities = private, internal, private_protected
+dotnet_naming_style.static_prefix_style.required_prefix = s_
+dotnet_naming_style.static_prefix_style.capitalization = camel_case
+
+# internal and private fields should be _camelCase
+dotnet_naming_rule.camel_case_for_private_internal_fields.severity = suggestion
+dotnet_naming_rule.camel_case_for_private_internal_fields.symbols = private_internal_fields
+dotnet_naming_rule.camel_case_for_private_internal_fields.style = camel_case_underscore_style
+dotnet_naming_symbols.private_internal_fields.applicable_kinds = field
+dotnet_naming_symbols.private_internal_fields.applicable_accessibilities = private, internal
+dotnet_naming_style.camel_case_underscore_style.required_prefix = _
+dotnet_naming_style.camel_case_underscore_style.capitalization = camel_case
+
+# Code style defaults
+csharp_using_directive_placement = outside_namespace:error
+dotnet_sort_system_directives_first = true
+csharp_prefer_braces = true:silent
+csharp_preserve_single_line_blocks = true:none
+csharp_preserve_single_line_statements = false:none
+csharp_prefer_static_local_function = true:error
+csharp_prefer_simple_using_statement = false:none
+csharp_style_prefer_switch_expression = true:error
+dotnet_style_readonly_field = true:error
+
+# Expression-level preferences
+dotnet_style_object_initializer = true:error
+dotnet_style_collection_initializer = true:error
+dotnet_style_explicit_tuple_names = true:error
+dotnet_style_coalesce_expression = true:error
+dotnet_style_null_propagation = true:error
+dotnet_style_prefer_is_null_check_over_reference_equality_method = true:error
+dotnet_style_prefer_inferred_tuple_names = true:error
+dotnet_style_prefer_inferred_anonymous_type_member_names = true:error
+dotnet_style_prefer_auto_properties = true:error
+dotnet_style_prefer_conditional_expression_over_assignment = true:silent
+dotnet_style_prefer_conditional_expression_over_return = true:silent
+csharp_prefer_simple_default_expression = true:error
+
+# Expression-bodied members
+csharp_style_expression_bodied_methods = true:silent
+csharp_style_expression_bodied_constructors = true:silent
+csharp_style_expression_bodied_operators = true:silent
+csharp_style_expression_bodied_properties = true:silent
+csharp_style_expression_bodied_indexers = true:silent
+csharp_style_expression_bodied_accessors = true:silent
+csharp_style_expression_bodied_lambdas = true:silent
+csharp_style_expression_bodied_local_functions = true:silent
+
+# Pattern matching
+csharp_style_pattern_matching_over_is_with_cast_check = true:error
+csharp_style_pattern_matching_over_as_with_null_check = true:error
+csharp_style_inlined_variable_declaration = true:error
+
+# Null checking preferences
+csharp_style_throw_expression = true:error
+csharp_style_conditional_delegate_call = true:error
+
+# Other features
+csharp_style_prefer_index_operator = false:none
+csharp_style_prefer_range_operator = false:none
+csharp_style_pattern_local_over_anonymous_function = false:none
+
+# Space preferences
+csharp_space_after_cast = false
+csharp_space_after_colon_in_inheritance_clause = true
+csharp_space_after_comma = true
+csharp_space_after_dot = false
+csharp_space_after_keywords_in_control_flow_statements = true
+csharp_space_after_semicolon_in_for_statement = true
+csharp_space_around_binary_operators = before_and_after
+csharp_space_around_declaration_statements = do_not_ignore
+csharp_space_before_colon_in_inheritance_clause = true
+csharp_space_before_comma = false
+csharp_space_before_dot = false
+csharp_space_before_open_square_brackets = false
+csharp_space_before_semicolon_in_for_statement = false
+csharp_space_between_empty_square_brackets = false
+csharp_space_between_method_call_empty_parameter_list_parentheses = false
+csharp_space_between_method_call_name_and_opening_parenthesis = false
+csharp_space_between_method_call_parameter_list_parentheses = false
+csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
+csharp_space_between_method_declaration_name_and_open_parenthesis = false
+csharp_space_between_method_declaration_parameter_list_parentheses = false
+csharp_space_between_parentheses = false
+csharp_space_between_square_brackets = false
+
+# License header
+file_header_template = Licensed to the .NET Foundation under one or more agreements.\nThe .NET Foundation licenses this file to you under the MIT license.
+
+# C++ Files
+[*.{cpp,h,in}]
+curly_bracket_next_line = true
+indent_brace_style = Allman
+
+# Xml project files
+[*.{csproj,vbproj,vcxproj,vcxproj.filters,proj,nativeproj,locproj}]
+indent_size = 2
+
+[*.{csproj,vbproj,proj,nativeproj,locproj}]
+charset = utf-8
+
+# Xml build files
+[*.builds]
+indent_size = 2
+
+# Xml files
+[*.{xml,stylecop,resx,ruleset}]
+indent_size = 2
+
+# Xml config files
+[*.{props,targets,config,nuspec}]
+indent_size = 2
+
+# YAML config files
+[*.{yml,yaml}]
+indent_size = 2
+
+# Shell scripts
+[*.sh]
+end_of_line = lf
+[*.{cmd,bat}]
+end_of_line = crlf
diff --git a/host/.gitattributes b/host/.gitattributes
new file mode 100644
index 0000000..f64d595
--- /dev/null
+++ b/host/.gitattributes
@@ -0,0 +1,12 @@
+## https://github.com/alexkaratarakis/gitattributes/blob/master/CSharp.gitattributes
+# Auto detect text files and perform LF normalization
+* text=auto
+
+*.cs text diff=csharp
+*.cshtml text diff=html
+*.csx text diff=csharp
+*.sln text eol=crlf
+*.csproj text eol=crlf
+
+
+## Repository specific attributes
diff --git a/host/.github/ISSUE_TEMPLATE/bug_report.yml b/host/.github/ISSUE_TEMPLATE/bug_report.yml
new file mode 100644
index 0000000..e0aaadc
--- /dev/null
+++ b/host/.github/ISSUE_TEMPLATE/bug_report.yml
@@ -0,0 +1,45 @@
+name: Bug Report
+description: Create a report to help us improve
+title: "[Bug]: "
+labels: ["bug"]
+body:
+ - type: textarea
+ attributes:
+ label: Describe the bug
+ description: A clear and concise description of what the bug is.
+ validations:
+ required: true
+
+ - type: textarea
+ attributes:
+ label: To Reproduce
+ description: Steps to reproduce the behavior.
+ validations:
+ required: true
+
+ - type: textarea
+ attributes:
+ label: Expected behavior
+ description: A clear and concise description of what you expected to happen.
+ validations:
+ required: true
+
+ - type: textarea
+ attributes:
+ label: Screenshots
+ description: If applicable, add screenshots to help explain your problem.
+
+ - type: input
+ attributes:
+ label: Platform
+ description: The platform you are using. (e.g. Windows 10, macOS 10.15, Ubuntu 20.04)
+
+ - type: input
+ attributes:
+ label: Version
+ description: The version of the application you are using. (e.g. 1.0.0)
+
+ - type: textarea
+ attributes:
+ label: Additional context
+ description: Add any other context about the problem here.
diff --git a/host/.github/ISSUE_TEMPLATE/feature_request.yml b/host/.github/ISSUE_TEMPLATE/feature_request.yml
new file mode 100644
index 0000000..b0f4b33
--- /dev/null
+++ b/host/.github/ISSUE_TEMPLATE/feature_request.yml
@@ -0,0 +1,28 @@
+name: Feature request
+description: Suggest an idea for this project
+title: "[Feature]: "
+labels: ["enhancement"]
+body:
+ - type: textarea
+ attributes:
+ label: Is your feature request related to a problem? Please describe.
+ description: A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
+ validations:
+ required: true
+
+ - type: textarea
+ attributes:
+ label: Describe the solution you'd like
+ description: A clear and concise description of what you want to happen.
+ validations:
+ required: true
+
+ - type: textarea
+ attributes:
+ label: Describe alternatives you've considered
+ description: A clear and concise description of any alternative solutions or features you've considered.
+
+ - type: textarea
+ attributes:
+ label: Additional context
+ description: Add any other context or screenshots about the feature request here.
diff --git a/host/.github/pull_request_template.md b/host/.github/pull_request_template.md
new file mode 100644
index 0000000..7036b42
--- /dev/null
+++ b/host/.github/pull_request_template.md
@@ -0,0 +1,18 @@
+## What does this PR do?
+
+
+
+## Which issues does this PR resolve?
+
+
+
+## Checklist before merging
+
+Thank you for your contribution to the repository.
+Before submitting this PR, please make sure:
+
+- [ ] Your code builds clean without any errors or warnings
+- [ ] Your code follows the code style of [Common C# code conventions](https://learn.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/coding-conventions)
+- [ ] You have tested all functions
+- [ ] You have not used code without license
+- [ ] You have added statement for third-party code
diff --git a/host/.github/workflows/build.yml b/host/.github/workflows/build.yml
new file mode 100644
index 0000000..f33e230
--- /dev/null
+++ b/host/.github/workflows/build.yml
@@ -0,0 +1,92 @@
+on:
+ push:
+ pull_request:
+ workflow_dispatch:
+
+jobs:
+ build:
+ strategy:
+ matrix:
+ runtime:
+ - linux-arm
+ - linux-arm64
+ - ubuntu-x64
+ - win-arm64
+ - win-x64
+ - win-x86
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-dotnet@v3
+ with:
+ dotnet-version: 6.0.x
+
+ - run: |
+ dotnet publish src/EdcHost/EdcHost.csproj -c Release -o bin \
+ --sc false -r ${{ matrix.runtime }} -p:DebugType=none \
+ -p:PublishSingleFile=true
+
+ - uses: actions/upload-artifact@v3
+ with:
+ name: edchost-${{ matrix.runtime }}-${{ github.sha }}
+ path: bin
+
+ check-style:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-dotnet@v3
+ with:
+ dotnet-version: 6.0.x
+
+ - run: dotnet format --verify-no-changes src/EdcHost
+
+ - run: dotnet format --verify-no-changes src/EdcHost.Tests
+
+ deploy-documentation:
+ if: github.ref == 'refs/heads/main' && github.event_name == 'push'
+ needs: generate-documentation
+ permissions:
+ id-token: write
+ pages: write
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/deploy-pages@v2
+
+ generate-documentation:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - run: |
+ mkdir -p site/api/
+
+ - uses: docker://asyncapi/github-action-for-generator:2.1.12
+ with:
+ filepath: docs/api/asyncapi.yaml
+ template: '@asyncapi/html-template@0.28.4'
+ output: site/api/
+
+ - uses: actions/upload-pages-artifact@v2
+ with:
+ path: site/
+
+ test:
+ strategy:
+ matrix:
+ runs-on:
+ - ubuntu-latest
+ - macos-latest
+ - windows-latest
+ runs-on: ${{ matrix.runs-on }}
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-dotnet@v3
+ with:
+ dotnet-version: 6.0.x
+
+ - run: |
+ dotnet test src/EdcHost.Tests/EdcHost.Tests.csproj
diff --git a/host/.github/workflows/release.yml b/host/.github/workflows/release.yml
new file mode 100644
index 0000000..a12c4e9
--- /dev/null
+++ b/host/.github/workflows/release.yml
@@ -0,0 +1,93 @@
+on:
+ release:
+ types:
+ - published
+
+jobs:
+ build:
+ strategy:
+ matrix:
+ runtime:
+ - linux-arm
+ - linux-arm64
+ - ubuntu-x64
+ - win-arm64
+ - win-x64
+ - win-x86
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/setup-dotnet@v3
+ with:
+ dotnet-version: 6.0.x
+
+ - run: |
+ dotnet publish src/EdcHost/EdcHost.csproj -c Release -o bin \
+ --sc false -r ${{ matrix.runtime }} -p:DebugType=none \
+ -p:PublishSingleFile=true
+
+ - run: |
+ cp CHANGELOG.md LICENSE README.md bin
+
+ - uses: actions/upload-artifact@v3
+ with:
+ name: edchost-${{ matrix.runtime }}-${{ github.sha }}
+ path: bin
+
+ upload-to-release:
+ needs:
+ - build
+ permissions:
+ contents: write
+ runs-on: ubuntu-latest
+ strategy:
+ matrix:
+ runtime:
+ - linux-arm
+ - linux-arm64
+ - ubuntu-x64
+ - win-arm64
+ - win-x64
+ - win-x86
+ steps:
+ - uses: actions/checkout@v4
+
+ - uses: actions/download-artifact@v3
+ with:
+ name: edchost-${{ matrix.runtime }}-${{ github.sha }}
+ path: bin
+
+ - run: |
+ cp CHANGELOG.md LICENSE README.md bin/
+
+ - name: Pack artifact (Windows)
+ if: startsWith(matrix.runtime, 'win')
+ run: |
+ cd bin
+ zip -r ../edchost-${{ matrix.runtime }}.zip *
+ cd ..
+
+ - name: Pack artifact (Others)
+ if: startsWith(matrix.runtime, 'win') == false
+ run: |
+ cd bin
+ chmod +x EdcHost
+ tar -czvf ../edchost-${{ matrix.runtime }}.tar.gz *
+ cd ..
+
+ - name: Upload artifact to release (Windows)
+ if: startsWith(matrix.runtime, 'win')
+ uses: softprops/action-gh-release@v1
+ with:
+ append_body: true
+ files: |
+ edchost-${{ matrix.runtime }}.zip
+
+ - name: Upload artifact to release (Others)
+ if: startsWith(matrix.runtime, 'win') == false
+ uses: softprops/action-gh-release@v1
+ with:
+ append_body: true
+ files: |
+ edchost-${{ matrix.runtime }}.tar.gz
diff --git a/host/.gitignore b/host/.gitignore
new file mode 100644
index 0000000..267715f
--- /dev/null
+++ b/host/.gitignore
@@ -0,0 +1,44 @@
+## https://github.com/github/gitignore/blob/main/community/DotNet/core.gitignore
+*.swp
+*.*~
+project.lock.json
+.DS_Store
+*.pyc
+nupkg/
+
+# Visual Studio Code
+.vscode
+
+# Rider
+.idea
+
+# User-specific files
+*.suo
+*.user
+*.userosscache
+*.sln.docstates
+
+# Build results
+[Dd]ebug/
+[Dd]ebugPublic/
+[Rr]elease/
+[Rr]eleases/
+x64/
+x86/
+build/
+bld/
+[Bb]in/
+[Oo]bj/
+[Oo]ut/
+msbuild.log
+msbuild.err
+msbuild.wrn
+
+# Visual Studio 2015
+.vs/
+
+
+## Repository specific ignores
+/site/
+
+.fake
\ No newline at end of file
diff --git a/host/CHANGELOG.md b/host/CHANGELOG.md
new file mode 100644
index 0000000..1c248bb
--- /dev/null
+++ b/host/CHANGELOG.md
@@ -0,0 +1,88 @@
+# Changelog
+
+All notable changes to this project will be documented in this file.
+
+The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
+and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+
+## [Unreleased]
+
+## [0.4.0] - 2023-12-16
+
+### Added
+
+- Dynamic map reloading when resetting the game.
+
+### Fixed
+
+- Failed to close serial ports.
+
+## [0.3.5] - 2023-12-15
+
+### Fixed
+
+- The x,y of the map is incorrect
+
+## [0.3.4] - 2023-12-15
+
+### Fixed
+
+- Do not enqueue player event if game is not running
+
+## [0.3.3] - 2023-12-08
+
+### Fixed
+
+- Wrong position when a player is dead
+
+## [0.3.2] - 2023-12-08
+
+### Fixed
+
+- Wrong position when a player is dead
+
+## [0.3.1] - 2023-12-08
+
+### Fixed
+
+- Abnormal behavior when trading.
+- Wrong ore accumulation mechanism.
+- Uncaught exceptions.
+
+## [0.3.0] - 2023-12-06
+
+### Changed
+
+- Adapt to the new API.
+
+## [0.2.0] - 2023-11-23
+
+### Changed
+
+- Change mine positions and player spawn points to integer tuples.
+- Performance improvements.
+
+### Fixed
+
+- Crash on errors in message publishing.
+- Mistakes in README.
+- Masks cannot be shown in the GUI.
+- Failed to open a camera that has been opened before.
+- Failed to open a serial port that has been opened before.
+- Default configuration values that should not exist.
+- Reversed camera calibration parameters.
+
+## [0.1.0] - 2023-11-21
+
+Initial release.
+
+[unreleased]: https://github.com/THUASTA/EDCHost/compare/v0.4.0...HEAD
+[0.4.0]: https://github.com/THUASTA/EDCHost/compare/v0.3.5...v0.4.0
+[0.3.5]: https://github.com/THUASTA/EDCHost/compare/v0.3.4...v0.3.5
+[0.3.4]: https://github.com/THUASTA/EDCHost/compare/v0.3.3...v0.3.4
+[0.3.3]: https://github.com/THUASTA/EDCHost/compare/v0.3.2...v0.3.3
+[0.3.2]: https://github.com/THUASTA/EDCHost/compare/v0.3.1...v0.3.2
+[0.3.1]: https://github.com/THUASTA/EDCHost/compare/v0.3.0...v0.3.1
+[0.3.0]: https://github.com/THUASTA/EDCHost/compare/v0.2.0...v0.3.0
+[0.2.0]: https://github.com/THUASTA/EDCHost/compare/v0.1.0...v0.2.0
+[0.1.0]: https://github.com/THUASTA/EDCHost/releases/tag/v0.1.0
diff --git a/host/EDCHost.sln b/host/EDCHost.sln
new file mode 100644
index 0000000..7d0225d
--- /dev/null
+++ b/host/EDCHost.sln
@@ -0,0 +1,37 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 17
+VisualStudioVersion = 17.5.002.0
+MinimumVisualStudioVersion = 10.0.40219.1
+Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{2213BFDE-9726-4449-9CCC-5A6C1A9405DC}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EdcHost", "src\EdcHost\EdcHost.csproj", "{B729E817-FA6A-4B2E-BE3D-FEED4182B586}"
+EndProject
+Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EdcHost.Tests", "src\EdcHost.Tests\EdcHost.Tests.csproj", "{AD90F2D8-BB61-41B8-8C9C-A756EF257FD2}"
+EndProject
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ Release|Any CPU = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(ProjectConfigurationPlatforms) = postSolution
+ {B729E817-FA6A-4B2E-BE3D-FEED4182B586}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {B729E817-FA6A-4B2E-BE3D-FEED4182B586}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {B729E817-FA6A-4B2E-BE3D-FEED4182B586}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {B729E817-FA6A-4B2E-BE3D-FEED4182B586}.Release|Any CPU.Build.0 = Release|Any CPU
+ {AD90F2D8-BB61-41B8-8C9C-A756EF257FD2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
+ {AD90F2D8-BB61-41B8-8C9C-A756EF257FD2}.Debug|Any CPU.Build.0 = Debug|Any CPU
+ {AD90F2D8-BB61-41B8-8C9C-A756EF257FD2}.Release|Any CPU.ActiveCfg = Release|Any CPU
+ {AD90F2D8-BB61-41B8-8C9C-A756EF257FD2}.Release|Any CPU.Build.0 = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+ GlobalSection(NestedProjects) = preSolution
+ {B729E817-FA6A-4B2E-BE3D-FEED4182B586} = {2213BFDE-9726-4449-9CCC-5A6C1A9405DC}
+ {AD90F2D8-BB61-41B8-8C9C-A756EF257FD2} = {2213BFDE-9726-4449-9CCC-5A6C1A9405DC}
+ EndGlobalSection
+ GlobalSection(ExtensibilityGlobals) = postSolution
+ SolutionGuid = {36266B2F-0790-4D6C-A715-3E2446240964}
+ EndGlobalSection
+EndGlobal
diff --git a/host/README.md b/host/README.md
new file mode 100644
index 0000000..d5afe89
--- /dev/null
+++ b/host/README.md
@@ -0,0 +1,66 @@
+# EDCHost
+
+The official host program for Electronic Design Competition
+
+## Install
+
+Download the latest release from [here](https://github.com/THUASTA/EDCHost/releases) and unzip it to an empty folder.
+
+## Usage
+
+Run `EdcHost.exe` to launch the program.
+
+See API references at [API documentation](https://thuasta.github.io/EDCHost/api).
+
+### Configuration
+
+When first running the app, a `config.json` file will be created under current work directory. You can edit the configurations inside it.
+
+Here is an example:
+
+```json
+{
+ "loggingLevel": "Information",
+ "serverPort": 8080,
+ "game": {
+ "diamondMines": [
+ {
+ "Item1": 1,
+ "Item2": 3
+ },
+ {
+ "Item1": 4,
+ "Item2": 4
+ }
+ ],
+ "goldMines": [
+ {
+ "Item1": 2,
+ "Item2": 1
+ },
+ {
+ "Item1": 4,
+ "Item2": 7
+ }
+ ],
+ "ironMines": [
+ {
+ "Item1": 0,
+ "Item2": 1
+ },
+ {
+ "Item1": 7,
+ "Item2": 6
+ }
+ ]
+ }
+}
+```
+
+## Contributing
+
+If you have any suggestions or improvements, please submit [an issue](https://github.com/THUASTA/EDCHost/issues/new) or a pull request.
+
+## License
+
+[GPL-3.0-only](LICENSE) © THUASTA
diff --git a/host/config.json b/host/config.json
new file mode 100644
index 0000000..99b5fe8
--- /dev/null
+++ b/host/config.json
@@ -0,0 +1,9 @@
+{
+ "loggingLevel": "Information",
+ "serverPort": 8080,
+ "game": {
+ "diamondMines": [],
+ "goldMines": [],
+ "ironMines": []
+ }
+}
\ No newline at end of file
diff --git a/host/docs/api/asyncapi.yaml b/host/docs/api/asyncapi.yaml
new file mode 100644
index 0000000..e9ba2e7
--- /dev/null
+++ b/host/docs/api/asyncapi.yaml
@@ -0,0 +1,501 @@
+asyncapi: "2.6.0"
+info:
+ title: Viewer API
+ version: ""
+channels:
+ /competition/control:
+ subscribe:
+ message:
+ oneOf:
+ - $ref: "#/components/messages/Error"
+ - $ref: "#/components/messages/HostConfigurationFromServer"
+ publish:
+ message:
+ oneOf:
+ - $ref: "#/components/messages/CompetitionControlCommand"
+ - $ref: "#/components/messages/HostConfigurationFromClient"
+ /competition/updates:
+ subscribe:
+ message:
+ oneOf:
+ - $ref: "#/components/messages/CompetitionUpdate"
+ - $ref: "#/components/messages/Error"
+components:
+ messages:
+ CompetitionControlCommand:
+ payload:
+ type: object
+ additionalProperties: false
+ required:
+ - messageType
+ - token
+ - command
+ properties:
+ messageType:
+ type: string
+ const: COMPETITION_CONTROL_COMMAND
+ token:
+ type: string
+ command:
+ type: string
+ enum:
+ - START
+ - END
+ - RESET
+ - GET_HOST_CONFIGURATION
+ CompetitionUpdate:
+ payload:
+ type: object
+ additionalProperties: false
+ properties:
+ messageType:
+ type: string
+ const: COMPETITION_UPDATE
+ cameras:
+ type: array
+ items:
+ type: object
+ additionalProperties: false
+ required:
+ - cameraId
+ - frameData
+ - height
+ - width
+ properties:
+ cameraId:
+ type: integer
+ frameData:
+ type: string
+ format: binary
+ height:
+ type: integer
+ width:
+ type: integer
+ chunks:
+ type: array
+ items:
+ type: object
+ additionalProperties: false
+ required:
+ - chunkId
+ - height
+ - position
+ properties:
+ chunkId:
+ type: integer
+ height:
+ type: integer
+ position:
+ $ref: "#/components/schemas/PositionInt"
+ events:
+ type: array
+ items:
+ oneOf:
+ - $ref: "#/components/schemas/PlayerAttackEvent"
+ - $ref: "#/components/schemas/PlayerDigEvent"
+ - $ref: "#/components/schemas/PlayerPickUpEvent"
+ - $ref: "#/components/schemas/PlayerPlaceBlockEvent"
+ - $ref: "#/components/schemas/PlayerTryAttackEvent"
+ - $ref: "#/components/schemas/PlayerTryUseEvent"
+ info:
+ type: object
+ additionalProperties: false
+ required:
+ - elapsedTicks
+ - stage
+ properties:
+ elapsedTicks:
+ type: integer
+ stage:
+ type: integer
+ enum:
+ - READY
+ - RUNNING
+ - BATTLING
+ - FINISHED
+ - ENDED
+ mines:
+ type: array
+ items:
+ type: object
+ additionalProperties: false
+ required:
+ - mineId
+ - accumulatedOreCount
+ - oreType
+ - position
+ properties:
+ mineId:
+ type: string
+ accumulatedOreCount:
+ type: integer
+ oreType:
+ type: integer
+ enum:
+ - IRON_ORE
+ - GOLD_ORE
+ - DIAMOND_ORE
+ position:
+ $ref: "#/components/schemas/PositionInt"
+ players:
+ type: array
+ additionalProperties: false
+ required:
+ - playerId
+ - attributes
+ - health
+ - homePosition
+ - inventory
+ - position
+ properties:
+ playerId:
+ type: integer
+ attributes:
+ type: object
+ additionalProperties: false
+ required:
+ - agility
+ - maxHealth
+ - strength
+ properties:
+ agility:
+ type: integer
+ maxHealth:
+ type: integer
+ strength:
+ type: integer
+ health:
+ type: integer
+ homePosition:
+ $ref: "#/components/schemas/Position"
+ inventory:
+ type: object
+ additionalProperties: false
+ required:
+ - emerald
+ - wool
+ properties:
+ emerald:
+ type: integer
+ wool:
+ type: integer
+ position:
+ $ref: "#/components/schemas/Position"
+ Error:
+ payload:
+ type: object
+ additionalProperties: false
+ required:
+ - messageType
+ - errorCode
+ - message
+ properties:
+ messageType:
+ type: string
+ const: ERROR
+ errorCode:
+ type: integer
+ message:
+ type: string
+ HostConfigurationFromClient:
+ payload:
+ type: object
+ additionalProperties: false
+ required:
+ - messageType
+ - token
+ - configuration
+ properties:
+ messageType:
+ type: string
+ const: HOST_CONFIGURATION_FROM_CLIENT
+ token:
+ type: string
+ configuration:
+ $ref: "#/components/schemas/HostConfiguration"
+ HostConfigurationFromServer:
+ payload:
+ type: object
+ additionalProperties: false
+ required:
+ - messageType
+ - availableCameras
+ - availableSerialPorts
+ - configuration
+ properties:
+ messageType:
+ type: string
+ const: HOST_CONFIGURATION_FROM_SERVER
+ availableCameras:
+ type: array
+ items:
+ type: integer
+ availableSerialPorts:
+ type: array
+ items:
+ type: string
+ configuration:
+ $ref: "#/components/schemas/HostConfiguration"
+ schemas:
+ PlayerAttackEvent:
+ type: object
+ additionalProperties: false
+ required:
+ - eventType
+ - playerId
+ - targetPlayerId
+ properties:
+ eventType:
+ type: string
+ const: PLAYER_ATTACK
+ playerId:
+ type: integer
+ targetPlayerId:
+ type: integer
+ PlayerDigEvent:
+ type: object
+ additionalProperties: false
+ required:
+ - eventType
+ - playerId
+ - targetChunk
+ properties:
+ eventType:
+ type: string
+ const: PLAYER_DIG
+ playerId:
+ type: integer
+ targetChunk:
+ type: integer
+ PlayerPickUpEvent:
+ type: object
+ additionalProperties: false
+ required:
+ - eventType
+ - playerId
+ - itemType
+ - itemCount
+ - mineId
+ properties:
+ eventType:
+ type: string
+ const: PLAYER_PICK_UP
+ playerId:
+ type: integer
+ itemType:
+ type: string
+ enum:
+ - IRON_INGOT
+ - GOLD_INGOT
+ - DIAMOND
+ itemCount:
+ type: integer
+ mineId:
+ type: string
+ PlayerPlaceBlockEvent:
+ type: object
+ additionalProperties: false
+ required:
+ - eventType
+ - playerId
+ - blockType
+ properties:
+ eventType:
+ type: string
+ const: PLAYER_PLACE_BLOCK
+ playerId:
+ type: integer
+ blockType:
+ type: string
+ enum:
+ - WOOL
+ PlayerTryAttackEvent:
+ type: object
+ additionalProperties: false
+ required:
+ - eventType
+ - playerId
+ - targetChunk
+ properties:
+ eventType:
+ type: string
+ const: PLAYER_TRY_ATTACK
+ playerId:
+ type: integer
+ targetChunk:
+ type: integer
+ PlayerTryUseEvent:
+ type: object
+ additionalProperties: false
+ required:
+ - eventType
+ - playerId
+ - targetChunk
+ properties:
+ eventType:
+ type: string
+ const: PLAYER_TRY_USE
+ playerId:
+ type: integer
+ targetChunk:
+ type: integer
+ Position:
+ type: object
+ additionalProperties: false
+ required:
+ - x
+ - y
+ properties:
+ x:
+ type: number
+ y:
+ type: number
+ PositionInt:
+ type: object
+ additionalProperties: false
+ required:
+ - x
+ - y
+ properties:
+ x:
+ type: integer
+ y:
+ type: integer
+ HostConfiguration:
+ type: object
+ additionalProperties: false
+ required:
+ - cameras
+ - players
+ - serialPorts
+ properties:
+ cameras:
+ type: array
+ items:
+ type: object
+ additionalProperties: false
+ required:
+ - cameraId
+ properties:
+ cameraId:
+ type: integer
+ calibration:
+ type: object
+ additionalProperties: false
+ required:
+ - topLeft
+ - topRight
+ - bottomLeft
+ - bottomRight
+ properties:
+ topLeft:
+ $ref: "#/components/schemas/Position"
+ topRight:
+ $ref: "#/components/schemas/Position"
+ bottomLeft:
+ $ref: "#/components/schemas/Position"
+ bottomRight:
+ $ref: "#/components/schemas/Position"
+ properties:
+ type: object
+ additionalProperties: false
+ properties:
+ frameWidth:
+ type: number
+ frameHeight:
+ type: number
+ fps:
+ type: number
+ brightness:
+ type: number
+ contrast:
+ type: number
+ saturation:
+ type: number
+ hue:
+ type: number
+ gain:
+ type: number
+ exposure:
+ type: number
+ monocrome:
+ type: number
+ sharpness:
+ type: number
+ autoExposure:
+ type: number
+ gamma:
+ type: number
+ temperature:
+ type: number
+ whiteBalanceRedV:
+ type: number
+ zoom:
+ type: number
+ focus:
+ type: number
+ isoSpeed:
+ type: number
+ iris:
+ type: number
+ autofocus:
+ type: number
+ autoWb:
+ type: number
+ wbTemperature:
+ type: number
+ recognition:
+ type: object
+ additionalProperties: false
+ required:
+ - hueCenter
+ - hueRange
+ - saturationCenter
+ - saturationRange
+ - valueCenter
+ - valueRange
+ - minArea
+ - showMask
+ properties:
+ hueCenter:
+ type: number
+ hueRange:
+ type: number
+ saturationCenter:
+ type: number
+ saturationRange:
+ type: number
+ valueCenter:
+ type: number
+ valueRange:
+ type: number
+ minArea:
+ type: number
+ showMask:
+ type: boolean
+ players:
+ type: array
+ items:
+ type: object
+ additionalProperties: false
+ required:
+ - playerId
+ properties:
+ playerId:
+ type: integer
+ camera:
+ type: integer
+ serialPort:
+ type: string
+ serialPorts:
+ type: array
+ items:
+ type: object
+ additionalProperties: false
+ required:
+ - portName
+ properties:
+ portName:
+ type: string
+ baudRate:
+ type: integer
diff --git a/host/docs/build.md b/host/docs/build.md
new file mode 100644
index 0000000..38f8c17
--- /dev/null
+++ b/host/docs/build.md
@@ -0,0 +1,19 @@
+# Build Guide
+
+## Build EDCHost
+
+Run the following command to build the program:
+
+```shell
+dotnet publish src/EdcHost/ -o bin -p:PublishSingleFile=true -r win-x64 --sc false
+```
+
+Checkout artifacts in `bin/` directory.
+
+## Build API Reference
+
+The API are defined following AsyncAPI specifications. To build the API references, AsyncAPI CLI tool is required.
+
+```shell
+ag docs/api/asyncapi.yaml @asyncapi/html-template -o site/api/
+```
diff --git a/host/docs/serial_port_protocols.md b/host/docs/serial_port_protocols.md
new file mode 100644
index 0000000..a4135d9
--- /dev/null
+++ b/host/docs/serial_port_protocols.md
@@ -0,0 +1,84 @@
+# Serial Port Protocols
+
+## Table of Contents
+
+In a packet, the first 5 bytes are the header and the later bytes are the data.
+
+| Byte | Description |
+| -------- | ---------------------------------------------------- |
+| 0 | Always 0x55 |
+| 1 | Always 0xAA |
+| 2 to 3 | Short. The number of bytes of the data (N) |
+| 4 | Byte. The checksum of the data |
+| 5 to N+4 | The data of the packet. N is the length of the data. |
+
+* [Operations](#operations)
+ * [PUB main](#pub-main-operation)
+ * [SUB main](#sub-main-operation)
+
+## Operations
+
+### PUB `main` Operation
+
+#### Message ``
+
+##### Payload
+
+| Name | Type | Description | Value | Constraints | Notes |
+| ---------- | ------- | ---------------------------------------------------------------------- | ----------------------- | --------------- | ----------------------------------------- |
+| (root) | object | - | - | - | **additional properties are NOT allowed** |
+| actionType | integer | The action type. 0: ATTACK 1: PLACE_BLOCK 2: TRADE | allowed (`0`, `1`, `2`) | format (`int8`) | - |
+| param | integer | The parameter. Chunk id for ATTACK and PLACE_BLOCK. Item id for TRADE. | - | format (`int8`) | - |
+
+The ID of the top-left chunk is 0 and the ID of the bottom-right chunk is 63. The chunk ID increases first from left to right and then from top to down. For example, chunk (0, 0) has ID 0, and chunk (1, 0) has ID 1.
+
+The item IDs are defined as belows:
+
+| Item ID | Item |
+|---|---|
+| 0 | AgilityBoost |
+| 1 | HealthBoost |
+| 2 | StrengthBoost |
+| 3 | Wool |
+| 4 | PotionOfHealing |
+
+### SUB `main` Operation
+
+#### Message ``
+
+##### Payload
+
+| Name | Type | Description | Value | Constraints | Notes |
+| ---------------------------- | -------------- | ---------------------------------------------------------- | ----- | ---------------- | ----------------------------------------- |
+| (root) | object | - | - | - | **additional properties are NOT allowed** |
+| gameStage | integer | The game stage 0: READY 1: RUNNING 2: BATTLING 3: FINISHED | - | format (`int8`) | - |
+| elapsedTicks | integer | The elapsed ticks. | - | format (`int32`) | - |
+| informationOfChunks | array | - | - | 64 items | - |
+| informationOfChunks (single item) | integer | The information of chunks. | - | format (`int8`) | - |
+| hasBed | boolean | Whether the player has bed. | - | - | - |
+| hasBedOpponent | boolean | Whether the opponent has bed. | - | - | - |
+| positionX | number | The x coordinate. | - | format (`float`) | - |
+| positionY | number | The y coordinate. | - | format (`float`) | - |
+| positionOpponentX | number | The x coordinate of the opponent. | - | format (`float`) | - |
+| positionOpponentY | number | The y coordinate of the opponent. | - | format (`float`) | - |
+| agility | integer | The agility point. | - | format (`int8`) | - |
+| health | integer | The health point. | - | format (`int8`) | - |
+| maxHealth | integer | The max health point. | - | format (`int8`) | - |
+| strength | integer | The strength point. | - | format (`int8`) | - |
+| emeraldCount | integer | The emerald count. | - | format (`int8`) | - |
+| woolCount | integer | The wool count. | - | format (`int8`) | - |
+
+InfomationOfChunk is defined as below:
+
+```c
+informationOfChunk = heightOfChunk + (oreKindOfChunk << 4)
+```
+
+The ore kinds are defined as belows:
+
+| ID | OreKind |
+|---|---|
+| 0 | IronIngot |
+| 1 | GoldIngot |
+| 2 | Diamond |
+| 3 | None |
diff --git a/host/src/EdcHost.Tests/EdcHost.Tests.csproj b/host/src/EdcHost.Tests/EdcHost.Tests.csproj
new file mode 100644
index 0000000..6bf1b3c
--- /dev/null
+++ b/host/src/EdcHost.Tests/EdcHost.Tests.csproj
@@ -0,0 +1,29 @@
+
+
+
+ net6.0
+ enable
+ enable
+
+ false
+ true
+
+
+
+
+
+
+ runtime; build; native; contentfiles; analyzers; buildtransitive
+ all
+
+
+ runtime; build; native; contentfiles; analyzers; buildtransitive
+ all
+
+
+
+
+
+
+
+
diff --git a/host/src/EdcHost.Tests/IntegrationTests/GameTests.OreAccumulate.cs b/host/src/EdcHost.Tests/IntegrationTests/GameTests.OreAccumulate.cs
new file mode 100644
index 0000000..3c1abde
--- /dev/null
+++ b/host/src/EdcHost.Tests/IntegrationTests/GameTests.OreAccumulate.cs
@@ -0,0 +1,138 @@
+using EdcHost.Games;
+using Xunit;
+
+namespace EdcHost.Tests.IntegrationTests;
+
+public partial class GameTests
+{
+ const int WoolCount = 8;
+ const int MaxHeight = 8;
+ const int MaximumItemCount = 128;
+ public class MockPosition : IPosition
+ {
+ public int X { get; set; }
+ public int Y { get; set; }
+ }
+
+ [Fact]
+ public void OreAccumulationTests()
+ {
+ Tuple iron1 = Tuple.Create(0, 0);
+ Tuple iron2 = Tuple.Create(7, 7);
+ Tuple gold1 = Tuple.Create(3, 3);
+ Tuple gold2 = Tuple.Create(4, 4);
+ Tuple diamond1 = Tuple.Create(5, 5);
+ List>? iron = new();
+ List>? gold = new();
+ List>? diamond = new();
+ iron.Add(iron1);
+ iron.Add(iron2);
+ gold.Add(gold1);
+ gold.Add(gold2);
+ diamond.Add(diamond1);
+ var game = IGame.Create(diamond, gold, iron);
+ game.Start();
+
+ //Act1 Increase the height of bed to max
+ Assert.StrictEqual(0, game.Players[0].EmeraldCount);
+ IPosition position = new MockPosition { X = 0, Y = 0 };
+ for (int i = 1; i < 8; i++)
+ {
+ game.Players[0].Place(game.Players[0].SpawnPoint.X, game.Players[0].SpawnPoint.Y);
+ game.Tick();
+ Assert.StrictEqual(i + 1, game.GameMap.GetChunkAt(position).Height);
+ Assert.StrictEqual(WoolCount - i, game.Players[0].WoolCount);
+ }
+ game.Players[0].Place(game.Players[0].SpawnPoint.X, game.Players[0].SpawnPoint.Y);
+ game.Tick();
+ Assert.StrictEqual(1, game.Players[0].WoolCount);
+ Assert.StrictEqual(MaxHeight, game.GameMap.GetChunkAt(position).Height);
+
+ //Act2 accumulate iron 7~11
+ for (int i = 0; i < OreAccumulationInterval; i++)
+ {
+ game.Tick();
+ }
+ Assert.StrictEqual(1, game.Players[0].EmeraldCount);
+ for (int i = 0; i < 9 * OreAccumulationInterval; i++)
+ {
+ game.Tick();
+ }
+ Assert.StrictEqual(10, game.Players[0].EmeraldCount);
+
+ //Act3 Trade and Invalid Placement
+ game.Players[0].Place(3, 2);
+ IPosition position0 = new MockPosition { X = 3, Y = 2 };
+ Assert.StrictEqual(0, game.GameMap.GetChunkAt(position0).Height);
+ Assert.StrictEqual(1, game.Players[0].WoolCount);
+ game.Players[0].Place(-1, 0);
+ Assert.StrictEqual(1, game.Players[0].WoolCount);
+ for (int i = 1; i < 6; i++)
+ {
+ game.Players[0].Trade(IPlayer.CommodityKindType.Wool);
+ game.Tick();
+ Assert.StrictEqual(10 - 2 * i, game.Players[0].EmeraldCount);
+ Assert.StrictEqual(i + 1, game.Players[0].WoolCount);
+ }
+ Assert.False(game.Players[0].Trade(IPlayer.CommodityKindType.Wool));
+
+ //Act4 Valid Placement and Accumulate gold and diamond
+ IPosition position1 = new MockPosition { X = 1, Y = 0 };
+ Assert.StrictEqual(0, game.GameMap.GetChunkAt(position1).Height);
+ game.Players[0].Place(1, 0);
+ game.Tick();
+ Assert.StrictEqual(1, game.GameMap.GetChunkAt(position1).Height);
+ game.Players[0].Move(1.4f, 0.4f);
+ game.Tick();
+ game.Players[0].Place(1, 1);
+ game.Tick();
+ game.Players[0].Move(1.4f, 1.4f);
+ game.Tick();
+ game.Players[0].Place(2, 1);
+ game.Tick();
+ game.Players[0].Move(2.4f, 1.4f);
+ game.Tick();
+ game.Players[0].Place(3, 1);
+ game.Tick();
+ game.Players[0].Move(3.4f, 1.4f);
+ game.Tick();
+ game.Players[0].Place(3, 2);
+ game.Tick();
+ game.Players[0].Move(3.4f, 2.4f);
+ game.Tick();
+ game.Players[0].Place(3, 3);
+ game.Tick();
+ game.Players[0].Move(3.4f, 3.4f);
+ game.Tick();
+ Assert.StrictEqual(0, game.Players[0].WoolCount);
+ Assert.StrictEqual(40, game.Players[0].EmeraldCount);
+ for (int i = 1; i < 21; i++)
+ {
+ game.Players[0].Trade(IPlayer.CommodityKindType.Wool);
+ game.Tick();
+ Assert.StrictEqual(i, game.Players[0].WoolCount);
+ }
+ Assert.StrictEqual(0, game.Players[0].EmeraldCount);
+ game.Players[0].Place(4, 3);
+ game.Tick();
+ game.Players[0].Move(4.4f, 3.4f);
+ game.Tick();
+ game.Players[0].Place(5, 3);
+ game.Tick();
+ game.Players[0].Move(5.4f, 3.4f);
+ game.Tick();
+ game.Players[0].Place(5, 4);
+ game.Tick();
+ game.Players[0].Move(5.4f, 4.4f);
+ game.Tick();
+ game.Players[0].Place(5, 5);
+ game.Tick();
+ game.Players[0].Move(5.4f, 5.4f);
+ game.Tick();
+ Assert.StrictEqual(16, game.Players[0].WoolCount);
+ Assert.StrictEqual(MaximumItemCount, game.Players[0].EmeraldCount);
+
+ game.End();
+ }
+
+}
diff --git a/host/src/EdcHost.Tests/IntegrationTests/GameTests.Trade.cs b/host/src/EdcHost.Tests/IntegrationTests/GameTests.Trade.cs
new file mode 100644
index 0000000..554165d
--- /dev/null
+++ b/host/src/EdcHost.Tests/IntegrationTests/GameTests.Trade.cs
@@ -0,0 +1,92 @@
+using EdcHost.Games;
+using Xunit;
+
+namespace EdcHost.Tests.IntegrationTests;
+
+public partial class GameTests
+{
+ const int MaxHealth = 20;
+ const int OreAccumulationInterval = 200;
+ const int HealthPotionPrice = 4;
+ const int HealthBoostPrice = 32;
+ const int AgilityBoostPrice = 32;
+
+ [Fact]
+ public void TradeTests()
+ {
+ List> diamond = new()
+ {
+ Tuple.Create(1, 0),
+ Tuple.Create(0, 1)
+ };
+ var game = IGame.Create(diamond, null, null);
+ game.Start();
+
+ // Act1 Accumulate diamond, EmeraldCount = 64
+ Assert.StrictEqual(0, game.Players[0].EmeraldCount);
+ game.Players[0].Place(1, 0);
+ game.Tick();
+ game.Players[0].Place(0, 1);
+ game.Tick();
+ game.Players[0].Move(1.4f, 0.4f);
+ for (int i = 0; i < 4 * OreAccumulationInterval; i++)
+ {
+ game.Tick();
+ }
+ game.Tick();
+ Assert.StrictEqual(64, game.Players[0].EmeraldCount);
+
+ // Act2 Trade for health, EmeraldCount = 28
+
+ game.Players[0].Trade(IPlayer.CommodityKindType.HealthPotion);
+ game.Tick();
+ Assert.StrictEqual(MaximumItemCount / 2 - HealthPotionPrice, game.Players[0].EmeraldCount);
+ Assert.StrictEqual(MaxHealth, game.Players[0].Health);
+ Assert.StrictEqual(MaxHealth, game.Players[0].MaxHealth);
+ Assert.True(game.Players[0].Trade(IPlayer.CommodityKindType.HealthBoost));
+ game.Tick();
+ Assert.StrictEqual(MaximumItemCount / 2 - HealthPotionPrice - HealthBoostPrice, game.Players[0].EmeraldCount);
+ Assert.StrictEqual(MaxHealth + 3, game.Players[0].MaxHealth);
+ Assert.StrictEqual(MaxHealth + 3, game.Players[0].Health);
+
+ //Act3 Accumulate diamond, EmeraldCount = 128
+ game.Players[0].Move(0.4f, 0.4f);
+ game.Tick();
+ game.Players[0].Move(0.4f, 1.4f);
+ game.Tick();
+ for (int i = 0; i < 4 * OreAccumulationInterval; i++)
+ {
+ game.Tick();
+ }
+ game.Tick();
+ Assert.StrictEqual(MaximumItemCount - HealthPotionPrice, game.Players[0].EmeraldCount);
+
+ //Act4 Trade for Agility, EmeralCount = 0
+ game.Players[0].Trade(IPlayer.CommodityKindType.AgilityBoost);
+ game.Tick();
+ Assert.StrictEqual(1, game.Players[0].ActionPoints);
+ Assert.StrictEqual(MaximumItemCount - HealthPotionPrice, game.Players[0].EmeraldCount);
+ for (int i = 0; i < 31; i++)
+ {
+ game.Players[0].Trade(IPlayer.CommodityKindType.HealthPotion);
+ game.Tick();
+ }
+ Assert.StrictEqual(0, game.Players[0].EmeraldCount);
+
+ //Act5 Trade for Strength
+ Assert.False(game.Players[0].Trade(IPlayer.CommodityKindType.StrengthBoost));
+ game.Tick();
+ for (int i = 0; i < 4 * OreAccumulationInterval; i++)
+ {
+ game.Tick();
+ }
+ Assert.StrictEqual(MaximumItemCount / 2, game.Players[0].EmeraldCount);
+ Assert.True(game.Players[0].Trade(IPlayer.CommodityKindType.StrengthBoost));
+ game.Tick();
+ Assert.StrictEqual(2, game.Players[0].Strength);
+ Assert.StrictEqual(0, game.Players[0].EmeraldCount);
+
+ game.End();
+
+ }
+}
diff --git a/host/src/EdcHost.Tests/IntegrationTests/GamesTests.AttackDie.cs b/host/src/EdcHost.Tests/IntegrationTests/GamesTests.AttackDie.cs
new file mode 100644
index 0000000..045fde0
--- /dev/null
+++ b/host/src/EdcHost.Tests/IntegrationTests/GamesTests.AttackDie.cs
@@ -0,0 +1,45 @@
+using EdcHost.Games;
+using Xunit;
+
+namespace EdcHost.Tests.IntegrationTests;
+
+public partial class GamesTests
+{
+ const int AttackTickInterval = (int)(8.5 * 20);
+ const int AttackTimes = 20;
+ [Fact]
+ public void Game_AttackDieTests()
+ {
+ var game = IGame.Create();
+ game.Start();
+ game.Players[0].Move(game.Players[1].PlayerPosition.X, game.Players[1].PlayerPosition.Y);
+ game.Tick();
+
+ // Accumulate no ore and attack 20 times
+ for (int i = 1; i <= AttackTimes; i++)
+ {
+ game.Players[0].Attack((int)game.Players[1].PlayerPosition.X, (int)game.Players[1].PlayerPosition.Y);
+ game.Tick();
+ Assert.StrictEqual(game.Players[1].MaxHealth - i * game.Players[0].Strength, game.Players[1].Health);
+ for (int j = 1; j < AttackTickInterval; j++)
+ {
+ game.Players[0].Attack((int)game.Players[1].PlayerPosition.X, (int)game.Players[1].PlayerPosition.Y);
+ game.Tick();
+ Assert.StrictEqual(game.Players[1].MaxHealth - i * game.Players[0].Strength, game.Players[1].Health);
+ }
+ game.Tick();
+ }
+ Assert.False(game.Players[1].IsAlive);
+ Assert.True(game.Players[1].HasBed);
+ Assert.Null(game.Winner);
+
+ // BedDestryed
+ game.Players[0].Attack(game.Players[1].SpawnPoint.X, game.Players[1].SpawnPoint.Y);
+ game.Tick();
+ Assert.False(game.Players[1].IsAlive);
+ Assert.False(game.Players[1].HasBed);
+ Assert.StrictEqual(game.Players[0], game.Winner);
+ Assert.StrictEqual(IGame.Stage.Finished, game.CurrentStage);
+
+ }
+}
diff --git a/host/src/EdcHost.Tests/IntegrationTests/GamesTests.InvalidMove.cs b/host/src/EdcHost.Tests/IntegrationTests/GamesTests.InvalidMove.cs
new file mode 100644
index 0000000..354518c
--- /dev/null
+++ b/host/src/EdcHost.Tests/IntegrationTests/GamesTests.InvalidMove.cs
@@ -0,0 +1,68 @@
+using EdcHost.Games;
+using Xunit;
+
+namespace EdcHost.Tests.IntegrationTests;
+
+public partial class GamesTests
+{
+ const int TicksBeforeRespawn = 300;
+ [Fact]
+ public void Game_InvalidMoveTests()
+ {
+ var game = IGame.Create();
+
+ // Act1 ValidMoveMent
+ game.Start();
+ for (int i = 1; i < 8; i++)
+ {
+ float x0 = game.Players[0].SpawnPoint.X;
+ float y0 = game.Players[0].SpawnPoint.Y;
+ float x1 = game.Players[1].SpawnPoint.X;
+ float y1 = game.Players[1].SpawnPoint.Y;
+ float move = i;
+ game.Players[0].Move(x0 + move, y0 + move);
+ game.Players[1].Move(x1 - move, y1 - move);
+ game.Tick();
+ Assert.StrictEqual(IGame.Stage.Running, game.CurrentStage);
+ Assert.StrictEqual(x0 + move, game.Players[0].PlayerPosition.X);
+ Assert.StrictEqual(y0 + move, game.Players[0].PlayerPosition.Y);
+ Assert.StrictEqual(x1 - move, game.Players[1].PlayerPosition.X);
+ Assert.StrictEqual(y1 - move, game.Players[1].PlayerPosition.Y);
+ Assert.False(game.Players[0].IsAlive);
+ }
+
+ // Act2 InvalidMoveMent and Relive
+ game.Players[1].Move(8f, 8f);
+ game.Tick();
+ Assert.False(game.Players[1].IsAlive);
+ Assert.Null(game.Winner);
+ for (int i = 0; i < TicksBeforeRespawn; i++)
+ {
+ game.Tick();
+ Assert.False(game.Players[1].IsAlive);
+ }
+ game.Players[1].Move(game.Players[1].SpawnPoint.X, game.Players[1].SpawnPoint.Y);
+ game.Players[0].Move(game.Players[0].SpawnPoint.X, game.Players[0].SpawnPoint.Y);
+ game.Tick();
+ Assert.True(game.Players[1].IsAlive);
+ Assert.True(game.Players[0].IsAlive);
+
+ // Act3 InvalidMoveMent and Die
+ game.Players[0].Move(1.4f, 0.4f);
+ game.Tick();
+ Assert.False(game.Players[0].IsAlive);
+ Assert.Null(game.Winner);
+ for (int i = 0; i < TicksBeforeRespawn / 2; i++)
+ {
+ game.Tick();
+ }
+ game.Players[1].Move(game.Players[0].SpawnPoint.X, game.Players[0].SpawnPoint.Y);
+ game.Tick();
+ game.Players[1].Attack(game.Players[0].SpawnPoint.X, game.Players[0].SpawnPoint.Y);
+ game.Tick();
+ Assert.StrictEqual(game.Players[1], game.Winner);
+ Assert.StrictEqual(IGame.Stage.Finished, game.CurrentStage);
+
+ }
+
+}
diff --git a/host/src/EdcHost.Tests/IntegrationTests/GamesTests.Simple.cs b/host/src/EdcHost.Tests/IntegrationTests/GamesTests.Simple.cs
new file mode 100644
index 0000000..7f65067
--- /dev/null
+++ b/host/src/EdcHost.Tests/IntegrationTests/GamesTests.Simple.cs
@@ -0,0 +1,75 @@
+using EdcHost.Games;
+using Xunit;
+
+namespace EdcHost.Tests.IntegrationTests;
+
+public partial class GamesTests
+{
+ [Fact]
+ public void Simple()
+ {
+ const int TicksBeforeBattling = 12000;
+ const int TicksBattling = 2000;
+
+ // Arrange
+ var game = IGame.Create();
+
+ IGame.Stage? stage = game.CurrentStage;
+ int elapsedTicks = game.ElapsedTicks;
+ IPlayer? winner = game.Winner;
+
+ Assert.StrictEqual(IGame.Stage.Ready, stage);
+ Assert.StrictEqual(0, elapsedTicks);
+ Assert.Null(winner);
+
+ // Act 1
+ game.Start();
+
+ stage = game.CurrentStage;
+ elapsedTicks = game.ElapsedTicks;
+ winner = game.Winner;
+
+ Assert.StrictEqual(IGame.Stage.Running, stage);
+ Assert.StrictEqual(0, elapsedTicks);
+ Assert.Null(winner);
+
+ for (int tick = 1; tick <= TicksBeforeBattling; ++tick)
+ {
+ // Act 2~12001
+ game.Tick();
+
+ stage = game.CurrentStage;
+ elapsedTicks = game.ElapsedTicks;
+ winner = game.Winner;
+
+ Assert.StrictEqual(IGame.Stage.Running, stage);
+ Assert.StrictEqual(tick, elapsedTicks);
+ Assert.Null(winner);
+ }
+
+ for (int tick = TicksBeforeBattling + 1; tick <= TicksBeforeBattling + TicksBattling; ++tick)
+ {
+ // Act 12002~12401
+ game.Tick();
+
+ stage = game.CurrentStage;
+ elapsedTicks = game.ElapsedTicks;
+ winner = game.Winner;
+
+ Assert.StrictEqual(IGame.Stage.Battling, stage);
+ Assert.StrictEqual(tick, elapsedTicks);
+ Assert.Null(winner);
+ }
+
+ // Act 12402
+ game.Tick();
+
+ stage = game.CurrentStage;
+ elapsedTicks = game.ElapsedTicks;
+ winner = game.Winner;
+
+ Assert.StrictEqual(IGame.Stage.Finished, stage);
+ Assert.StrictEqual(TicksBeforeBattling + TicksBattling + 1, elapsedTicks);
+ Assert.Null(winner);
+ }
+}
diff --git a/host/src/EdcHost.Tests/IntegrationTests/SlaveServersTests.Concurrency.cs b/host/src/EdcHost.Tests/IntegrationTests/SlaveServersTests.Concurrency.cs
new file mode 100644
index 0000000..e86d91f
--- /dev/null
+++ b/host/src/EdcHost.Tests/IntegrationTests/SlaveServersTests.Concurrency.cs
@@ -0,0 +1,64 @@
+using System.Collections.Concurrent;
+using System.Text;
+
+using EdcHost.SlaveServers;
+
+using Xunit;
+
+namespace EdcHost.Tests.IntegrationTests;
+
+public partial class SlaveServersTests
+{
+ [Theory]
+ [InlineData(new int[] { 1, 1 }, 10000, "COM1", 9600)]
+ [InlineData(new int[] { 255, 255 }, 10000, "COM1", 9600)]
+ [InlineData(new int[] { 0, 255 }, 10000, "COM1", 9600)]
+ [InlineData(new int[] { 16, 1 }, 10000, "COM1", 9600)]
+ [InlineData(new int[] { 170, 32 }, 10000, "COM1", 9600)]
+ public void Concurrency(int[] data, int clientCount, string portName, int baudRate)
+ {
+ SerialPortHubMock serialPortHubMock = new()
+ {
+ SerialPorts = {
+ { portName, new SerialPortWrapperMock(portName) }
+ }
+ };
+ var slaveServer = new SlaveServer(serialPortHubMock);
+ slaveServer.Start();
+ slaveServer.OpenPort(portName, baudRate);
+
+ //data preparation
+ byte[] byteData = new byte[data.Length];
+ for (int i = 0; i < data.Length; i++)
+ {
+ byteData[i] = Convert.ToByte(data[i]);
+ }
+ byte[] header = IPacket.GeneratePacketHeader(byteData);
+ byte[] bytes = new byte[header.Length + byteData.Length];
+ header.CopyTo(bytes, 0);
+ byteData.CopyTo(bytes, header.Length);
+ ConcurrentBag count = new();
+ //do concurrency test
+ var tasks = new List();
+ var serialPortWrapperMock = (SerialPortWrapperMock)serialPortHubMock.Get(portName, baudRate);
+ serialPortWrapperMock.AfterReceive += (sender, args) =>
+ {
+ PacketFromSlave packetReceived = new(args.Bytes);
+ // Assertion
+ Assert.Equal(bytes, args.Bytes);
+ Assert.Equal(packetReceived.ActionType, packetReceived.ActionType);
+ Assert.Equal(packetReceived.Param, packetReceived.Param);
+ count.Add(1);
+ };
+ for (int i = 0; i < clientCount; i++)
+ {
+ tasks.Add(Task.Run(() =>
+ {
+ serialPortWrapperMock.MockReceive(bytes);
+ }));
+ }
+ Task.WhenAll(tasks).Wait();
+ Assert.Equal(clientCount, count.Count);
+ slaveServer.Stop();
+ }
+}
diff --git a/host/src/EdcHost.Tests/IntegrationTests/SlaveServersTests.Malformed.cs b/host/src/EdcHost.Tests/IntegrationTests/SlaveServersTests.Malformed.cs
new file mode 100644
index 0000000..278bd37
--- /dev/null
+++ b/host/src/EdcHost.Tests/IntegrationTests/SlaveServersTests.Malformed.cs
@@ -0,0 +1,25 @@
+using System.Text;
+
+using EdcHost.SlaveServers;
+
+using Xunit;
+
+namespace EdcHost.Tests.IntegrationTests;
+public partial class SlaveServersTests
+{
+ [Theory]
+ [InlineData(new byte[] { 0x55, 0xAA, 0x02, 0x01, 0x00, 0x01, 0x01 })] //length
+ [InlineData(new byte[] { 0x55, 0xAA, 0x02, 0x00, 0x01, 0x01 })] //length
+ [InlineData(new byte[] { 0x55, 0xAA, 0x02, 0x00, 0x01, 0x01, 0x01, 0x01 })] //length
+ [InlineData(new byte[] { 0x55, 0xAA, 0x02, 0x00, 0x01, 0x01, 0x01 })] //checksum
+ [InlineData(new byte[] { 0x55, 0x02, 0x00, 0x00, 0x01, 0x01 })] //head
+ [InlineData(new byte[] { 0xAA, 0x02, 0x00, 0x00, 0x01, 0x01 })] //head
+ [InlineData(new byte[] { 0x53, 0xAA, 0x02, 0x00, 0x00, 0x01, 0x01 })] //head
+ [InlineData(new byte[] { 0x55, 0xAB, 0x02, 0x00, 0x00, 0x01, 0x01 })] //head
+
+ void Malformed(byte[] bytes)
+ {
+ // Assertion
+ Assert.Throws(() => new PacketFromSlave(bytes));
+ }
+}
diff --git a/host/src/EdcHost.Tests/IntegrationTests/SlaveServersTests.Random.cs b/host/src/EdcHost.Tests/IntegrationTests/SlaveServersTests.Random.cs
new file mode 100644
index 0000000..d0359f0
--- /dev/null
+++ b/host/src/EdcHost.Tests/IntegrationTests/SlaveServersTests.Random.cs
@@ -0,0 +1,97 @@
+using System.Text;
+using EdcHost.SlaveServers;
+using Xunit;
+
+namespace EdcHost.Tests.IntegrationTests;
+
+public partial class SlaveServersTests
+{
+ [Theory]
+ [InlineData(2)]
+ [InlineData(3)]
+ [InlineData(5)]
+ [InlineData(7)]
+ [InlineData(11)]
+ [InlineData(13)]
+ [InlineData(17)]
+ [InlineData(19)]
+ [InlineData(23)]
+ [InlineData(29)]
+ [InlineData(31)]
+ [InlineData(37)]
+ [InlineData(41)]
+ [InlineData(43)]
+ [InlineData(47)]
+ [InlineData(53)]
+ [InlineData(59)]
+ [InlineData(61)]
+ [InlineData(67)]
+ [InlineData(71)]
+ [InlineData(73)]
+ [InlineData(79)]
+ [InlineData(83)]
+ [InlineData(89)]
+ [InlineData(97)]
+ [InlineData(101)]
+ [InlineData(103)]
+ [InlineData(107)]
+ [InlineData(109)]
+ [InlineData(113)]
+ [InlineData(127)]
+ [InlineData(131)]
+ [InlineData(137)]
+ [InlineData(139)]
+ [InlineData(149)]
+ [InlineData(151)]
+ [InlineData(157)]
+ [InlineData(163)]
+ [InlineData(167)]
+ [InlineData(173)]
+ [InlineData(179)]
+ [InlineData(181)]
+ [InlineData(191)]
+ [InlineData(193)]
+ [InlineData(197)]
+ [InlineData(199)]
+ public void Random(int randomSeed)
+ {
+ const int MaxLength = 100000;
+ const int SlaveToHostBytesCount = 7;
+ const int SlaveToHostDataBytesCount = 2;
+
+ // Arrange
+ Random random = new(randomSeed);
+ string portName = Encoding.ASCII.GetString(Utils.GenerateRandomBytes(random, random.Next(0, MaxLength)));
+ SerialPortWrapperMock serialPortWrapperMock = new(portName);
+ SerialPortHubMock serialPortHubMock = new()
+ {
+ SerialPorts = {
+ { portName, serialPortWrapperMock }
+ }
+ };
+ ISlaveServer slaveServer = new SlaveServer(serialPortHubMock);
+
+ // Act
+ slaveServer.Start();
+ slaveServer.OpenPort(portName, 0);
+
+ Assert.True(serialPortWrapperMock.IsOpen);
+
+ // Act: random bytes
+ serialPortWrapperMock.MockReceive(Utils.GenerateRandomBytes(random, random.Next(0, MaxLength)));
+
+ // Act: random body
+ serialPortWrapperMock.MockReceive(MakePacket(Utils.GenerateRandomBytes(random, random.Next(0, MaxLength))));
+
+ // Act: random value
+ byte[] readBufferBytes = new byte[SlaveToHostBytesCount];
+ readBufferBytes[5] = (byte)random.Next(0, 255);
+ readBufferBytes[6] = (byte)random.Next(0, 255);
+ // Headers should be generated after data bytes are set.
+ readBufferBytes[0] = 0x55;
+ readBufferBytes[1] = 0xAA;
+ BitConverter.GetBytes((short)SlaveToHostDataBytesCount).CopyTo(readBufferBytes, 2);
+ readBufferBytes[4] = CalculateChecksum(readBufferBytes.ToArray()[5..SlaveToHostBytesCount]);
+ serialPortWrapperMock.MockReceive(readBufferBytes);
+ }
+}
diff --git a/host/src/EdcHost.Tests/IntegrationTests/SlaveServersTests.Reception.cs b/host/src/EdcHost.Tests/IntegrationTests/SlaveServersTests.Reception.cs
new file mode 100644
index 0000000..f80e6e0
--- /dev/null
+++ b/host/src/EdcHost.Tests/IntegrationTests/SlaveServersTests.Reception.cs
@@ -0,0 +1,44 @@
+using System.Text;
+
+using EdcHost.SlaveServers;
+
+using Xunit;
+
+namespace EdcHost.Tests.IntegrationTests;
+public partial class SlaveServersTests
+{
+ [Theory]
+ [InlineData(new byte[] { 0x01, 0x01 }, "COM1", 9600)]
+ [InlineData(new byte[] { 0xFF, 0xFF }, "COM1", 9600)]
+ [InlineData(new byte[] { 0x00, 0xFF }, "COM1", 9600)]
+ [InlineData(new byte[] { 0x10, 0x01 }, "COM1", 9600)]
+ [InlineData(new byte[] { 0xAA, 0x20 }, "COM1", 9600)]
+ public void Reception(byte[] packetData, string portName, int baudRate)
+ {
+ SerialPortHubMock serialPortHubMock = new()
+ {
+ SerialPorts = {
+ { portName, new SerialPortWrapperMock(portName) }
+ }
+ };
+ var slaveServer = new SlaveServer(serialPortHubMock);
+ slaveServer.Start();
+
+ byte[] bytes = MakePacket(packetData);
+
+ PacketFromSlave packet = new(bytes);
+
+ var serialPortWrapperMock = (SerialPortWrapperMock)serialPortHubMock.Get(portName, baudRate);
+ serialPortWrapperMock.AfterReceive += (sender, args) =>
+ {
+ PacketFromSlave packetReceived = new(args.Bytes);
+ // Assertion
+ Assert.Equal(bytes, args.Bytes);
+ Assert.Equal(packetReceived.ActionType, packet.ActionType);
+ Assert.Equal(packetReceived.Param, packet.Param);
+
+ slaveServer.Stop();
+ };
+ serialPortWrapperMock.MockReceive(bytes);
+ }
+}
diff --git a/host/src/EdcHost.Tests/IntegrationTests/SlaveServersTests.Simple.cs b/host/src/EdcHost.Tests/IntegrationTests/SlaveServersTests.Simple.cs
new file mode 100644
index 0000000..848d427
--- /dev/null
+++ b/host/src/EdcHost.Tests/IntegrationTests/SlaveServersTests.Simple.cs
@@ -0,0 +1,165 @@
+using EdcHost.SlaveServers;
+using Xunit;
+
+namespace EdcHost.Tests.IntegrationTests;
+
+public partial class SlaveServersTests
+{
+ [Fact]
+ public void Simple()
+ {
+ const int HostToSlaveBytesCount = 98;
+ const int HostToSlaveDataBytesCount = 93;
+ const int SlaveToHostBytesCount = 7;
+ const int SlaveToHostDataBytesCount = 2;
+ const int ChunkCount = 64;
+ const string PortName = "COM1";
+
+ // Arrange
+ SerialPortWrapperMock serialPortWrapperMock = new(PortName);
+ SerialPortHubMock serialPortHubMock = new()
+ {
+ SerialPorts = {
+ { PortName, serialPortWrapperMock }
+ }
+ };
+ ISlaveServer slaveServer = new SlaveServer(serialPortHubMock);
+
+ // Act
+ slaveServer.Start();
+
+ Assert.Single(serialPortHubMock.SerialPorts);
+ Assert.False(serialPortWrapperMock.IsOpen);
+ Assert.Empty(serialPortWrapperMock.WriteBuffer);
+
+ // Act
+ slaveServer.OpenPort(PortName, 0);
+
+ Assert.Single(serialPortHubMock.SerialPorts);
+ Assert.True(serialPortWrapperMock.IsOpen);
+ Assert.Empty(serialPortWrapperMock.WriteBuffer);
+
+ // Act
+ slaveServer.Publish(
+ PortName, 0, 0, Enumerable.Repeat(0, ChunkCount).ToList(), false, false,
+ 0.0, 0.0, 0.0, 0.0, 0, 0, 0, 0, 0, 0, Enumerable.Repeat(0, ChunkCount).ToList()
+ );
+
+ Assert.Single(serialPortHubMock.SerialPorts);
+ Assert.True(serialPortWrapperMock.IsOpen);
+ Assert.Equal(HostToSlaveBytesCount, serialPortWrapperMock.WriteBuffer.Count);
+
+ List writeBuffer = serialPortWrapperMock.WriteBuffer;
+ byte checksum = CalculateChecksum(writeBuffer.ToArray()[5..HostToSlaveBytesCount]);
+
+ Assert.Equal((byte)0x55, writeBuffer[0]);
+ Assert.Equal((byte)0xAA, writeBuffer[1]);
+ Assert.Equal(HostToSlaveDataBytesCount,
+ BitConverter.ToInt16(writeBuffer.ToArray(), 2));
+ Assert.Equal(checksum, writeBuffer[4]);
+ Assert.Equal((byte)0x00, writeBuffer[5]);
+ Assert.Equal(0, BitConverter.ToInt32(writeBuffer.ToArray(), 6));
+ for (int i = 0; i < 64; ++i)
+ {
+ Assert.Equal((byte)0x00, writeBuffer[10 + i]);
+ }
+ Assert.Equal((byte)0x00, writeBuffer[74]);
+ Assert.Equal((byte)0x00, writeBuffer[75]);
+ Assert.Equal(0.0f, BitConverter.ToSingle(writeBuffer.ToArray(), 76));
+ Assert.Equal(0.0f, BitConverter.ToSingle(writeBuffer.ToArray(), 80));
+ Assert.Equal(0.0f, BitConverter.ToSingle(writeBuffer.ToArray(), 84));
+ Assert.Equal(0.0f, BitConverter.ToSingle(writeBuffer.ToArray(), 88));
+ Assert.Equal((byte)0x00, writeBuffer[92]);
+ Assert.Equal((byte)0x00, writeBuffer[93]);
+ Assert.Equal((byte)0x00, writeBuffer[94]);
+ Assert.Equal((byte)0x00, writeBuffer[95]);
+ Assert.Equal((byte)0x00, writeBuffer[96]);
+ Assert.Equal((byte)0x00, writeBuffer[97]);
+
+ // Act
+ bool isPlayerTryAttackEventRaised = false;
+ slaveServer.PlayerTryAttackEvent += (sender, e) =>
+ {
+ Assert.Equal(PortName, e.PortName);
+ Assert.Equal(0, e.TargetChunkId);
+ isPlayerTryAttackEventRaised = true;
+ };
+
+ byte[] readBufferBytes = new byte[SlaveToHostBytesCount];
+ readBufferBytes[5] = (byte)0x00;
+ readBufferBytes[6] = (byte)0x00;
+ // Headers should be generated after data bytes are set.
+ readBufferBytes[0] = (byte)0x55;
+ readBufferBytes[1] = (byte)0xAA;
+ BitConverter.GetBytes((short)SlaveToHostDataBytesCount).CopyTo(readBufferBytes, 2);
+ readBufferBytes[4] = CalculateChecksum(readBufferBytes.ToArray()[5..SlaveToHostBytesCount]);
+ serialPortWrapperMock.MockReceive(readBufferBytes);
+
+ Assert.Single(serialPortHubMock.SerialPorts);
+ Assert.True(serialPortWrapperMock.IsOpen);
+ Assert.Equal(HostToSlaveBytesCount, serialPortWrapperMock.WriteBuffer.Count);
+ Assert.True(isPlayerTryAttackEventRaised);
+
+ // Act
+ bool isPlayerTryPlaceBlockEventRaised = false;
+ slaveServer.PlayerTryPlaceBlockEvent += (sender, e) =>
+ {
+ Assert.Equal(PortName, e.PortName);
+ Assert.Equal(0, e.TargetChunkId);
+ isPlayerTryPlaceBlockEventRaised = true;
+ };
+
+ readBufferBytes = new byte[SlaveToHostBytesCount];
+ readBufferBytes[5] = (byte)0x01;
+ readBufferBytes[6] = (byte)0x00;
+ // Headers should be generated after data bytes are set.
+ readBufferBytes[0] = (byte)0x55;
+ readBufferBytes[1] = (byte)0xAA;
+ BitConverter.GetBytes((short)SlaveToHostDataBytesCount).CopyTo(readBufferBytes, 2);
+ readBufferBytes[4] = CalculateChecksum(readBufferBytes.ToArray()[5..SlaveToHostBytesCount]);
+ serialPortWrapperMock.MockReceive(readBufferBytes);
+
+ Assert.Single(serialPortHubMock.SerialPorts);
+ Assert.True(serialPortWrapperMock.IsOpen);
+ Assert.Equal(HostToSlaveBytesCount, serialPortWrapperMock.WriteBuffer.Count);
+ Assert.True(isPlayerTryPlaceBlockEventRaised);
+
+ // Act
+ bool isPlayerTryTradeEventRaised = false;
+ slaveServer.PlayerTryTradeEvent += (sender, e) =>
+ {
+ Assert.Equal(PortName, e.PortName);
+ Assert.Equal(0, e.Item);
+ isPlayerTryTradeEventRaised = true;
+ };
+
+ readBufferBytes = new byte[SlaveToHostBytesCount];
+ readBufferBytes[5] = (byte)0x02;
+ readBufferBytes[6] = (byte)0x00;
+ // Headers should be generated after data bytes are set.
+ readBufferBytes[0] = (byte)0x55;
+ readBufferBytes[1] = (byte)0xAA;
+ BitConverter.GetBytes((short)SlaveToHostDataBytesCount).CopyTo(readBufferBytes, 2);
+ readBufferBytes[4] = CalculateChecksum(readBufferBytes.ToArray()[5..SlaveToHostBytesCount]);
+ serialPortWrapperMock.MockReceive(readBufferBytes);
+
+ Assert.Single(serialPortHubMock.SerialPorts);
+ Assert.True(serialPortWrapperMock.IsOpen);
+ Assert.Equal(HostToSlaveBytesCount, serialPortWrapperMock.WriteBuffer.Count);
+ Assert.True(isPlayerTryTradeEventRaised);
+
+ // Act
+ slaveServer.ClosePort(PortName);
+
+ Assert.Single(serialPortHubMock.SerialPorts);
+ Assert.False(serialPortWrapperMock.IsOpen);
+ Assert.Equal(HostToSlaveBytesCount, serialPortWrapperMock.WriteBuffer.Count);
+
+ // Act
+ slaveServer.Stop();
+
+ Assert.Single(serialPortHubMock.SerialPorts);
+ Assert.False(serialPortWrapperMock.IsOpen);
+ Assert.Equal(HostToSlaveBytesCount, serialPortWrapperMock.WriteBuffer.Count);
+ }
+}
diff --git a/host/src/EdcHost.Tests/IntegrationTests/SlaveServersTests.Transmission.cs b/host/src/EdcHost.Tests/IntegrationTests/SlaveServersTests.Transmission.cs
new file mode 100644
index 0000000..04aa790
--- /dev/null
+++ b/host/src/EdcHost.Tests/IntegrationTests/SlaveServersTests.Transmission.cs
@@ -0,0 +1,84 @@
+using System.Text;
+
+using EdcHost.SlaveServers;
+
+using Xunit;
+
+namespace EdcHost.Tests.IntegrationTests;
+public partial class SlaveServersTests
+{
+ [Theory]
+ [InlineData("COM1", 9600)]
+ public void Transmission(string portName, int baudRate)
+ {
+ SerialPortHubMock serialPortHubMock = new()
+ {
+ SerialPorts = {
+ { portName, new SerialPortWrapperMock(portName) }
+ }
+ };
+ var slaveServer = new SlaveServer(serialPortHubMock);
+
+ slaveServer.Start();
+ slaveServer.OpenPort(portName, baudRate);
+
+ var serialPort = (SerialPortWrapperMock)serialPortHubMock.Get(portName, baudRate);
+
+ int gameStage = 1;
+ int elapsedTime = 100;
+ List heightOfChunks = Enumerable.Repeat(0, 64).ToList();
+ for (int i = 0; i < heightOfChunks.Count; i++)
+ {
+ heightOfChunks[i] = i % 8;
+ }
+ heightOfChunks[0] = 8;
+
+ bool hasBed = true;
+ bool hasBedOpponent = true;
+ double positionX = 1.0;
+ double positionY = 1.0;
+ double positionOpponentX = 1.0;
+ double positionOpponentY = 1.0;
+ int agility = 1;
+ int health = 2;
+ int maxHealth = 3;
+ int strength = 4;
+ int emeraldCount = 5;
+ int woolCount = 6;
+ List owningOreKindOfChunks = Enumerable.Repeat(0, 64).ToList();
+ for (int i = 0; i < owningOreKindOfChunks.Count; i++)
+ {
+ owningOreKindOfChunks[i] = i % 4;
+ }
+ owningOreKindOfChunks[0] = 3;
+
+ PacketFromHost packet = new(
+ gameStage, elapsedTime,
+ heightOfChunks,
+ hasBed, hasBedOpponent,
+ (float)positionX, (float)positionY,
+ (float)positionOpponentX, (float)positionOpponentY,
+ agility, health, maxHealth, strength,
+ emeraldCount, woolCount,
+ owningOreKindOfChunks
+ );
+
+ byte[] bytes = packet.ToBytes();
+
+ slaveServer.Publish(
+ portName,
+ gameStage, elapsedTime,
+ heightOfChunks,
+ hasBed, hasBedOpponent,
+ positionX, positionY, positionOpponentX, positionOpponentY,
+ agility, health, maxHealth, strength,
+ emeraldCount, woolCount,
+ owningOreKindOfChunks
+ );
+
+ byte[] bytesToSend = serialPort.WriteBuffer.ToArray();
+
+ //Assertion
+ Assert.Equal(bytes, bytesToSend);
+ }
+}
diff --git a/host/src/EdcHost.Tests/IntegrationTests/SlaveServersTests.Utils.cs b/host/src/EdcHost.Tests/IntegrationTests/SlaveServersTests.Utils.cs
new file mode 100644
index 0000000..855b344
--- /dev/null
+++ b/host/src/EdcHost.Tests/IntegrationTests/SlaveServersTests.Utils.cs
@@ -0,0 +1,100 @@
+using EdcHost.SlaveServers;
+
+namespace EdcHost.Tests.IntegrationTests;
+
+public partial class SlaveServersTests
+{
+ class SerialPortHubMock : ISerialPortHub
+ {
+ public Dictionary SerialPorts = new();
+
+ public List PortNames => SerialPorts.Keys.ToList();
+
+ public ISerialPortWrapper Get(string portName, int baudRate)
+ {
+ if (!SerialPorts.ContainsKey(portName))
+ {
+ throw new ArgumentException($"port name does not exist: {portName}");
+ }
+
+ return SerialPorts[portName];
+ }
+ }
+
+ class SerialPortWrapperMock : ISerialPortWrapper
+ {
+ public bool IsOpen = false;
+ public List WriteBuffer = new();
+ public void MockReceive(byte[] bytes)
+ {
+ AfterReceive?.Invoke(this, new ISerialPortWrapper.AfterReceiveEventArgs(PortName, bytes));
+ }
+
+ public event EventHandler? AfterReceive;
+
+ public string PortName { get; }
+
+ public int BaudRate => 115200;
+
+ public SerialPortWrapperMock(string portName)
+ {
+ PortName = portName;
+ }
+
+ public void Close()
+ {
+ IsOpen = false;
+ }
+ public void Dispose()
+ {
+ }
+ public void Open()
+ {
+ if (IsOpen)
+ {
+ throw new InvalidOperationException();
+ }
+
+ IsOpen = true;
+ }
+ public void Send(byte[] bytes)
+ {
+ if (!IsOpen)
+ {
+ throw new InvalidOperationException();
+ }
+
+ WriteBuffer.Clear();
+ WriteBuffer.AddRange(bytes);
+ }
+ }
+
+ static byte CalculateChecksum(byte[] bytes)
+ {
+ byte checksum = 0x00;
+ foreach (byte byte_item in bytes)
+ {
+ checksum ^= byte_item;
+ }
+ return checksum;
+ }
+
+ static byte[] MakePacketHeader(byte[] data)
+ {
+ byte[] header = new byte[5];
+ header[0] = 0x55;
+ header[1] = 0xAA;
+ BitConverter.GetBytes((short)data.Length).CopyTo(header, 2);
+ header[4] = CalculateChecksum(data);
+ return header;
+ }
+
+ static byte[] MakePacket(byte[] data)
+ {
+ byte[] header = MakePacketHeader(data);
+ byte[] packet = new byte[header.Length + data.Length];
+ header.CopyTo(packet, 0);
+ data.CopyTo(packet, header.Length);
+ return packet;
+ }
+}
diff --git a/host/src/EdcHost.Tests/IntegrationTests/Utils.cs b/host/src/EdcHost.Tests/IntegrationTests/Utils.cs
new file mode 100644
index 0000000..052d4e0
--- /dev/null
+++ b/host/src/EdcHost.Tests/IntegrationTests/Utils.cs
@@ -0,0 +1,11 @@
+namespace EdcHost.Tests.IntegrationTests;
+
+public partial class Utils
+{
+ public static byte[] GenerateRandomBytes(Random random, int count)
+ {
+ byte[] bytes = new byte[count];
+ random.NextBytes(bytes);
+ return bytes;
+ }
+}
diff --git a/host/src/EdcHost.Tests/IntegrationTests/ViewerServersTests.Concurrency.cs b/host/src/EdcHost.Tests/IntegrationTests/ViewerServersTests.Concurrency.cs
new file mode 100644
index 0000000..fb9af57
--- /dev/null
+++ b/host/src/EdcHost.Tests/IntegrationTests/ViewerServersTests.Concurrency.cs
@@ -0,0 +1,41 @@
+using EdcHost.ViewerServers;
+
+using Fleck;
+
+using Xunit;
+
+namespace EdcHost.Tests.IntegrationTests;
+
+public partial class ViewerServersTests
+{
+ [Theory]
+ [InlineData(500, 8080)]
+ public void Concurrency(int clientCount, int port)
+ {
+ WebSocketServerHubMock wsServerHubMock = new()
+ {
+ Servers = {
+ { port, new WebSocketServerMock(port) }
+ }
+ };
+ var viewerServer = new ViewerServer(port, wsServerHubMock);
+ viewerServer.Start();
+ //do concurrency test
+ var tasks = new List();
+ for (int i = 0; i < clientCount; i++)
+ {
+ tasks.Add(Task.Run(() =>
+ {
+ var wsServerMock = (WebSocketServerMock)wsServerHubMock.Get(port);
+ var wsConnectionMock = new WebSocketConnectionMock();
+ wsServerMock.AddConnection(wsConnectionMock);
+ }));
+ }
+ Task.WhenAll(tasks).Wait();
+ var wsServerMock = (WebSocketServerMock)wsServerHubMock.Get(port);
+
+ //Assertion
+ Assert.Equal(clientCount, wsServerMock.Connections.Count);
+ viewerServer.Stop();
+ }
+}
diff --git a/host/src/EdcHost.Tests/IntegrationTests/ViewerServersTests.Malformed.cs b/host/src/EdcHost.Tests/IntegrationTests/ViewerServersTests.Malformed.cs
new file mode 100644
index 0000000..567bf1d
--- /dev/null
+++ b/host/src/EdcHost.Tests/IntegrationTests/ViewerServersTests.Malformed.cs
@@ -0,0 +1,47 @@
+using System.Text;
+
+using EdcHost.ViewerServers;
+
+using Fleck;
+
+using Xunit;
+
+namespace EdcHost.Tests.IntegrationTests;
+
+public partial class ViewerServersTests
+{
+ [Theory]
+ [InlineData("", 8080)]
+ [InlineData("{}", 8080)]
+ [InlineData("{messageType: \"COMPETITION_CONTROL_COMMAND\", token: \"\", command:\"\"", 8080)]
+ [InlineData("{messageType: \"COMPETITION_CONTROL_COMMAND\"}, token: \"\", command:\"\"", 8080)]
+ [InlineData("{messageType: \"COMPETITION_CONTROL_COMMAND\", token \"\", command:\"\"}", 8080)]
+ [InlineData("{messageType: \"COMPETITION_CONTROL_COMMAND\", token: \"", 8080)]
+ [InlineData("{messageType: \"COMPETITION_CONTROL_COMMAND\", token: \"\", command: \"", 8080)]
+ [InlineData("{messageType: \"COMPETITION_CONTROL_COMMAND\", token: \"\", command: \"}", 8080)]
+ [InlineData("{messageType: \"COMPETITION_CONTROL_COMMAND\" token: \"\", command: \"\"}", 8080)]
+ [InlineData("{messageType \"COMPETITION_CONTROL_COMMAND\", token: \"\", command: \"\"}", 8080)]
+ [InlineData("{messageType: \"COMPETITION_CONTROL_COMMAND\", token: command: \"\"}", 8080)]
+ [InlineData("{messageType: 114514, token: \"\", command: \"\"}", 8080)]
+ [InlineData("{messageType: \"COMPETITION_CONTROL_COMMAND\", token: 114514, command: \"\"}", 8080)]
+ [InlineData("{messageType: \"COMPETITION_CONTROL_COMMAND\", token: \"\", command: 114514}", 8080)]
+ void Malformed(string message, int port)
+ {
+ // Arrange
+ WebSocketServerHubMock wsServerHubMock = new()
+ {
+ Servers = {
+ { port, new WebSocketServerMock(port) }
+ }
+ };
+ ViewerServer viewerServer = new(port, wsServerHubMock);
+ viewerServer.Start();
+
+ WebSocketServerMock wsServerMock = (WebSocketServerMock)wsServerHubMock.Get(port);
+ WebSocketConnectionMock wsConnectionMock = new();
+ wsServerMock.AddConnection(wsConnectionMock);
+
+ // Act
+ wsConnectionMock.OnMessage?.Invoke(message);
+ }
+}
diff --git a/host/src/EdcHost.Tests/IntegrationTests/ViewerServersTests.Random.cs b/host/src/EdcHost.Tests/IntegrationTests/ViewerServersTests.Random.cs
new file mode 100644
index 0000000..26723b8
--- /dev/null
+++ b/host/src/EdcHost.Tests/IntegrationTests/ViewerServersTests.Random.cs
@@ -0,0 +1,193 @@
+using System.Text;
+using EdcHost.ViewerServers;
+using Xunit;
+
+namespace EdcHost.Tests.IntegrationTests;
+
+public partial class ViewerServersTests
+{
+ [Theory]
+ [InlineData(2)]
+ [InlineData(3)]
+ [InlineData(5)]
+ [InlineData(7)]
+ [InlineData(11)]
+ [InlineData(13)]
+ [InlineData(17)]
+ [InlineData(19)]
+ [InlineData(23)]
+ [InlineData(29)]
+ [InlineData(31)]
+ [InlineData(37)]
+ [InlineData(41)]
+ [InlineData(43)]
+ [InlineData(47)]
+ [InlineData(53)]
+ [InlineData(59)]
+ [InlineData(61)]
+ [InlineData(67)]
+ [InlineData(71)]
+ [InlineData(73)]
+ [InlineData(79)]
+ [InlineData(83)]
+ [InlineData(89)]
+ [InlineData(97)]
+ [InlineData(101)]
+ [InlineData(103)]
+ [InlineData(107)]
+ [InlineData(109)]
+ [InlineData(113)]
+ [InlineData(127)]
+ [InlineData(131)]
+ [InlineData(137)]
+ [InlineData(139)]
+ [InlineData(149)]
+ [InlineData(151)]
+ [InlineData(157)]
+ [InlineData(163)]
+ [InlineData(167)]
+ [InlineData(173)]
+ [InlineData(179)]
+ [InlineData(181)]
+ [InlineData(191)]
+ [InlineData(193)]
+ [InlineData(197)]
+ [InlineData(199)]
+ public void Random(int randomSeed)
+ {
+ const int MinPort = 1;
+ const int MaxPort = 65534;
+ const int MaxLength = 100000;
+ // const int MaxSize = 100;
+
+ // Arrange
+ Random random = new(randomSeed);
+ int port = random.Next(MinPort, MaxPort);
+ List wsConnMockList = new()
+ {
+ new() {
+
+ }
+ };
+ WebSocketServerMock wsServerMock = new(port);
+ WebSocketServerHubMock wsServerHubMock = new()
+ {
+ Servers = {
+ { port, wsServerMock }
+ }
+ };
+
+ IViewerServer server = new ViewerServer(port, wsServerHubMock);
+
+ // Act
+ server.Start();
+ foreach (WebSocketConnectionMock wsConnMock in wsConnMockList)
+ {
+ wsServerMock.AddConnection(wsConnMock);
+ }
+
+ Assert.True(wsServerMock.IsStarted);
+
+ // Act
+ foreach (WebSocketConnectionMock wsConnMock in wsConnMockList)
+ {
+ wsConnMock.OnOpen();
+ }
+
+ // Act
+ foreach (WebSocketConnectionMock wsConnMock in wsConnMockList)
+ {
+ string message = Encoding.ASCII.GetString(Utils.GenerateRandomBytes(random, random.Next(0, MaxLength)));
+ wsConnMock.OnMessage(message);
+ wsConnMock.OnBinary(Encoding.ASCII.GetBytes(message));
+ }
+
+ // Act: random value - message
+ foreach (WebSocketConnectionMock wsConnMock in wsConnMockList)
+ {
+ Message message = new()
+ {
+ MessageType = Encoding.ASCII.GetString(Utils.GenerateRandomBytes(random, random.Next(0, MaxLength))),
+ };
+ wsConnMock.OnMessage(message.Json);
+ wsConnMock.OnBinary(Encoding.ASCII.GetBytes(message.Json));
+ }
+
+ // Act: random value - competition control command
+ foreach (WebSocketConnectionMock wsConnMock in wsConnMockList)
+ {
+ CompetitionControlCommandMessage message = new()
+ {
+ Token = Encoding.ASCII.GetString(Utils.GenerateRandomBytes(random, random.Next(0, MaxLength))),
+ Command = Encoding.ASCII.GetString(Utils.GenerateRandomBytes(random, random.Next(0, MaxLength))),
+ };
+ wsConnMock.OnMessage(message.Json);
+ wsConnMock.OnBinary(Encoding.ASCII.GetBytes(message.Json));
+ }
+
+ // // Act: random value - host configuration from client
+ // foreach (WebSocketConnectionMock wsConnMock in wsConnMockList)
+ // {
+ // HostConfigurationFromClientMessage message = new()
+ // {
+ // Token = Encoding.ASCII.GetString(Utils.GenerateRandomBytes(random, random.Next(0, MaxLength))),
+ // Players = Enumerable.Range(0, random.Next(0, MaxSize)).Select(_ => new HostConfigurationFromClientMessage.PlayerType()
+ // {
+ // PlayerId = random.Next(),
+ // Camera = random.Next() % 2 == 0 ? null : new()
+ // {
+ // CameraId = random.Next(),
+ // Calibration = random.Next() % 2 == 0 ? null : new()
+ // {
+ // TopLeft = new()
+ // {
+ // X = random.NextSingle(),
+ // Y = random.NextSingle(),
+ // },
+ // TopRight = new()
+ // {
+ // X = random.NextSingle(),
+ // Y = random.NextSingle(),
+ // },
+ // BottomLeft = new()
+ // {
+ // X = random.NextSingle(),
+ // Y = random.NextSingle(),
+ // },
+ // BottomRight = new()
+ // {
+ // X = random.NextSingle(),
+ // Y = random.NextSingle(),
+ // },
+ // },
+ // Recognition = new()
+ // {
+ // HueCenter = random.NextSingle(),
+ // HueRange = random.NextSingle(),
+ // SaturationCenter = random.NextSingle(),
+ // SaturationRange = random.NextSingle(),
+ // ValueCenter = random.NextSingle(),
+ // ValueRange = random.NextSingle(),
+ // MinArea = random.NextSingle(),
+ // ShowMask = random.Next() % 2 == 0,
+ // }
+ // },
+ // SerialPort = random.Next() % 2 == 0 ? null : new()
+ // {
+ // PortName = Encoding.ASCII.GetString(Utils.GenerateRandomBytes(random, random.Next(0, MaxLength))),
+ // BaudRate = random.Next(),
+ // }
+ // }).ToList(),
+ // };
+
+ // wsConnMock.OnMessage(message.Json);
+ // wsConnMock.OnBinary(Encoding.ASCII.GetBytes(message.Json));
+ // }
+
+ // // Act
+ // foreach (WebSocketConnectionMock wsConnMock in wsConnMockList)
+ // {
+ // wsConnMock.OnClose();
+ // }
+ }
+}
diff --git a/host/src/EdcHost.Tests/IntegrationTests/ViewerServersTests.Utils.cs b/host/src/EdcHost.Tests/IntegrationTests/ViewerServersTests.Utils.cs
new file mode 100644
index 0000000..9ead10e
--- /dev/null
+++ b/host/src/EdcHost.Tests/IntegrationTests/ViewerServersTests.Utils.cs
@@ -0,0 +1,120 @@
+using System.Collections.Concurrent;
+using System.Text;
+using EdcHost.ViewerServers;
+using Fleck;
+
+namespace EdcHost.Tests.IntegrationTests;
+
+public partial class ViewerServersTests
+{
+ class WebSocketServerHubMock : IWebSocketServerHub
+ {
+ public Dictionary Servers { get; init; } = new();
+
+ public IWebSocketServer Get(int port)
+ {
+ if (!Servers.ContainsKey(port))
+ {
+ throw new ArgumentException($"no server on port {port}");
+ }
+
+ return Servers[port];
+ }
+ }
+
+ class WebSocketServerMock : IWebSocketServer
+ {
+ public readonly ConcurrentBag Connections = new();
+ readonly List> _configs = new();
+ readonly int _port;
+
+ public bool IsDisposed { get; set; } = false;
+ public bool IsStarted { get; set; } = false;
+
+ public WebSocketServerMock(int port)
+ {
+ _port = port;
+ }
+
+ public void Start(Action config)
+ {
+ _configs.Add(config);
+ IsStarted = true;
+ }
+
+ public void Dispose()
+ {
+ IsDisposed = true;
+ }
+
+ public void AddConnection(IWebSocketConnection connection)
+ {
+ Connections.Add(connection);
+ foreach (Action config in _configs)
+ {
+ config(connection);
+ }
+ }
+ }
+
+ class WebSocketConnectionMock : IWebSocketConnection
+ {
+ public readonly List SendBuffer = new();
+
+ public Action OnOpen { get; set; } = () => { };
+ public Action OnClose { get; set; } = () => { };
+ public Action OnMessage { get; set; } = (message) => { };
+ public Action OnBinary { get; set; } = (message) => { };
+ public Action OnPing { get; set; } = (message) => { };
+ public Action OnPong { get; set; } = (message) => { };
+ public Action OnError { get; set; } = (exception) => { };
+ public IWebSocketConnectionInfo ConnectionInfo { get; set; } = new WebSocketConnectionInfoMock();
+ public bool IsAvailable { get; set; } = true;
+ public Task Send(string message)
+ {
+ SendBuffer.Clear();
+ SendBuffer.AddRange(Encoding.UTF8.GetBytes(message));
+ return Task.CompletedTask;
+ }
+ public Task Send(byte[] message)
+ {
+ SendBuffer.Clear();
+ SendBuffer.AddRange(message);
+ return Task.CompletedTask;
+ }
+ public Task SendPing(byte[] message)
+ {
+ SendBuffer.Clear();
+ SendBuffer.AddRange(message);
+ return Task.CompletedTask;
+ }
+ public Task SendPong(byte[] message)
+ {
+ SendBuffer.Clear();
+ SendBuffer.AddRange(message);
+ return Task.CompletedTask;
+ }
+ public void Close()
+ {
+ IsAvailable = false;
+ }
+ public void Close(int code)
+ {
+ IsAvailable = false;
+ }
+ }
+
+ class WebSocketConnectionInfoMock : IWebSocketConnectionInfo
+ {
+ public string SubProtocol { get; set; } = "";
+ public string Origin { get; set; } = "";
+ public string Host { get; set; } = "";
+ public string Path { get; set; } = "";
+ public string ClientIpAddress { get; set; } = "";
+ public int ClientPort { get; set; } = 0;
+ public IDictionary Cookies { get; set; } = new Dictionary();
+ public IDictionary Headers { get; set; } = new Dictionary();
+ public Guid Id { get; set; } = Guid.Empty;
+ public string NegotiatedSubProtocol { get; set; } = "";
+ }
+}
diff --git a/host/src/EdcHost.Tests/SystemTests/WebSocketConnection.py b/host/src/EdcHost.Tests/SystemTests/WebSocketConnection.py
new file mode 100644
index 0000000..ca81f87
--- /dev/null
+++ b/host/src/EdcHost.Tests/SystemTests/WebSocketConnection.py
@@ -0,0 +1,119 @@
+import asyncio
+import websocket
+import json
+import time
+
+async def send_websocket_message():
+ # ws server uri
+ uri = "ws://127.0.0.1:8080"
+
+ # Message to send
+ messages = {
+ "start": {
+ "messageType": "COMPETITION_CONTROL_COMMAND",
+ "token": "string",
+ "command": "START"
+ },
+ "end": {
+ "messageType": "COMPETITION_CONTROL_COMMAND",
+ "token": "string",
+ "command": "END"
+ },
+ "reset": {
+ "messageType": "COMPETITION_CONTROL_COMMAND",
+ "token": "string",
+ "command": "RESET"
+ },
+ "config": {
+ "messageType": "COMPETITION_CONTROL_COMMAND",
+ "token": "string",
+ "command": "GET_HOST_CONFIGURATION"
+ }
+ }
+
+ # Bad message to send
+ bad_messages = {
+ "empty": {
+
+ },
+ "key_missing": {
+ "messageType": "COMPETITION_CONTROL_COMMAND",
+ "token": "string"
+ },
+ "wrong_key": {
+ "asdgkladf": "COMPETITION_CONTROL_COMMAND",
+ "token": "string",
+ "command": "START"
+ },
+ "wrong_key_num": {
+ "messageType": "COMPETITION_CONTROL_COMMAND",
+ "token": "string",
+ "command": "START",
+ "sdfasdlf": 111
+ },
+ "wrong_value_type": {
+ "messageType": "COMPETITION_CONTROL_COMMAND",
+ "token": "string",
+ "command": 0
+ },
+ "wrong_command": {
+ "messageType": "COMPETITION_CONTROL_COMMAND",
+ "token": "string",
+ "command": "sdklfadsnkfl"
+ },
+ "not_match": {
+ "messageType": "HOST_CONFIGURATION_FROM_CLIENT",
+ "token": "string",
+ "command": "START"
+ }
+ }
+
+ async def send(ws: websocket.WebSocket, message: str):
+ # Send json
+ async def sendtask():
+ ws.send(json.dumps(message))
+ await sendtask()
+
+ # Wait for response
+ response = ws.recv()
+
+ print(f"Sent message: {json.dumps(message)}")
+ print(f"Received response: {response}")
+
+ time.sleep(3)
+ return
+
+ ws = websocket.WebSocket()
+ ws.connect(uri)
+
+ if ws.connected == True:
+ # Send messages
+ await send(ws, messages["start"])
+ await send(ws, messages["end"])
+ await send(ws, messages["reset"])
+ await send(ws, messages["start"])
+ await send(ws, messages["config"])
+
+ # Send "START" command again
+ await send(ws, messages["start"])
+
+ #Send bad messages
+ await send(ws, bad_messages["empty"])
+ await send(ws, bad_messages["key_missing"])
+ await send(ws, bad_messages["wrong_command"])
+ await send(ws, bad_messages["wrong_key"])
+ await send(ws, bad_messages["wrong_key_num"])
+ await send(ws, bad_messages["wrong_value_type"])
+ await send(ws, bad_messages["not_match"])
+
+ time.sleep(2)
+
+ # Close ws connection
+ ws.close()
+
+def main():
+ asyncio.get_event_loop().run_until_complete(send_websocket_message())
+ print("Done")
+
+if __name__ == "__main__":
+ main()
diff --git a/host/src/EdcHost.Tests/UnitTests/Games/ChunkTests.cs b/host/src/EdcHost.Tests/UnitTests/Games/ChunkTests.cs
new file mode 100644
index 0000000..aa6cc31
--- /dev/null
+++ b/host/src/EdcHost.Tests/UnitTests/Games/ChunkTests.cs
@@ -0,0 +1,168 @@
+using EdcHost.Games;
+using Xunit;
+
+namespace EdcHost.Tests.UnitTests.Games;
+
+public class ChunkTests
+{
+ public class MockPosition : IPosition
+ {
+ public int X { get; set; }
+ public int Y { get; set; }
+ }
+
+ [Theory]
+ [InlineData(0)]
+ [InlineData(1)]
+ [InlineData(2)]
+ [InlineData(3)]
+ [InlineData(7)]
+ public void CanPlaceBlock_LessThanMaxHeight_ReturnsTrue(int height)
+ {
+ IChunk chunk = IChunk.Create(height, new MockPosition { X = 0, Y = 0 });
+
+ bool actual = chunk.CanPlaceBlock;
+
+ Assert.True(actual);
+ }
+
+ [Fact]
+ public void CanPlaceBlock_EqualToMaxHeight_ReturnsFalse()
+ {
+ int MaxHeight = 8;
+ IChunk chunk = IChunk.Create(MaxHeight, new MockPosition { X = 0, Y = 0 });
+
+ bool actual = chunk.CanPlaceBlock;
+
+ Assert.False(actual);
+ }
+
+ [Theory]
+ [InlineData(1)]
+ [InlineData(2)]
+ [InlineData(3)]
+ [InlineData(7)]
+ [InlineData(8)]
+ public void CanRemoveBlock_MoreThanZero_ReturnsTrue(int height)
+ {
+ IChunk chunk = IChunk.Create(height, new MockPosition { X = 0, Y = 0 });
+
+ bool actual = chunk.CanRemoveBlock;
+
+ Assert.True(actual);
+ }
+
+ [Fact]
+ public void CanRemoveBlock_Zero_ReturnsFalse()
+ {
+ IChunk chunk = IChunk.Create(0, new MockPosition { X = 0, Y = 0 });
+
+ bool actual = chunk.CanRemoveBlock;
+
+ Assert.False(actual);
+ }
+
+ [Theory]
+ [InlineData(0, 0)]
+ [InlineData(1, 1)]
+ [InlineData(2, 2)]
+ [InlineData(3, 3)]
+ [InlineData(7, 7)]
+ [InlineData(8, 8)]
+ public void Height_DoNothing_ReturnsConstructorValue(int height, int expectedHeight)
+ {
+ IChunk chunk = IChunk.Create(height, new MockPosition { X = 0, Y = 0 });
+
+ int actual = chunk.Height;
+
+ Assert.Equal(expectedHeight, actual);
+ }
+
+ [Theory]
+ [InlineData(1)]
+ [InlineData(2)]
+ [InlineData(3)]
+ [InlineData(7)]
+ [InlineData(8)]
+ public void IsVoid_MoreThanZero_ReturnsFalse(int height)
+ {
+ IChunk chunk = IChunk.Create(height, new MockPosition { X = 0, Y = 0 });
+
+ bool actual = chunk.IsVoid;
+
+ Assert.False(actual);
+ }
+
+ [Fact]
+ public void IsVoid_Zero_ReturnsTrue()
+ {
+ IChunk chunk = IChunk.Create(0, new MockPosition { X = 0, Y = 0 });
+
+ bool actual = chunk.IsVoid;
+
+ Assert.True(actual);
+ }
+
+ [Theory]
+ [InlineData(0, 0)]
+ [InlineData(1, 1)]
+ [InlineData(-1, -1)]
+ [InlineData(int.MinValue, int.MinValue)]
+ [InlineData(int.MaxValue, int.MaxValue)]
+ public void Position_DoNothing_ReturnsConstructorValue(int x, int y)
+ {
+ IPosition expected = IPosition.Create(x, y);
+ IChunk chunk = IChunk.Create(0, expected);
+
+ IPosition actual = chunk.Position;
+
+ Assert.Equal(expected, actual);
+ }
+
+ [Theory]
+ [InlineData(0)]
+ [InlineData(1)]
+ [InlineData(2)]
+ [InlineData(3)]
+ [InlineData(7)]
+ public void PlaceBlock_LessThanMaxHeight_IncrementsHeight(int height)
+ {
+ IChunk chunk = IChunk.Create(height, new MockPosition { X = 0, Y = 0 });
+
+ chunk.PlaceBlock();
+
+ Assert.Equal(height + 1, chunk.Height);
+ }
+
+ [Fact]
+ public void PlaceBlock_EqualToMaxHeight_ThrowsInvalidOperationException()
+ {
+ int MaxHeight = 8;
+ IChunk chunk = IChunk.Create(MaxHeight, new MockPosition { X = 0, Y = 0 });
+
+ Assert.Throws(() => chunk.PlaceBlock());
+ }
+
+ [Theory]
+ [InlineData(1)]
+ [InlineData(2)]
+ [InlineData(3)]
+ [InlineData(7)]
+ [InlineData(8)]
+ public void RemoveBlock_MoreThanZero_DecrementsHeight(int height)
+ {
+ IChunk chunk = IChunk.Create(height, new MockPosition { X = 0, Y = 0 });
+
+ chunk.RemoveBlock();
+
+ Assert.Equal(height - 1, chunk.Height);
+ }
+
+ [Fact]
+ public void RemoveBlock_Zero_ThrowsInvalidOperationException()
+ {
+ IChunk chunk = IChunk.Create(0, new MockPosition { X = 0, Y = 0 });
+
+ Assert.Throws(() => chunk.RemoveBlock());
+ }
+}
diff --git a/host/src/EdcHost.Tests/UnitTests/Games/GameTests.cs b/host/src/EdcHost.Tests/UnitTests/Games/GameTests.cs
new file mode 100644
index 0000000..1615e13
--- /dev/null
+++ b/host/src/EdcHost.Tests/UnitTests/Games/GameTests.cs
@@ -0,0 +1,61 @@
+using EdcHost.Games;
+using Xunit;
+
+namespace EdcHost.Tests.UnitTests.Games;
+
+public class GameTest
+{
+ [Fact]
+ public void Game_DoNothing_PublicMembersCorrectlyInitialized()
+ {
+ IGame game = IGame.Create();
+ Assert.Equal(IGame.Stage.Ready, game.CurrentStage);
+ Assert.Null(game.Winner);
+ Assert.Equal(0, game.ElapsedTicks);
+ Assert.Equal(0, game.GameMap.Chunks[0].Position.X);
+ Assert.Equal(0, game.GameMap.Chunks[0].Position.Y);
+ Assert.Equal(1, game.GameMap.Chunks[0].Height);
+ Assert.Equal(7, game.GameMap.Chunks[63].Position.X);
+ Assert.Equal(7, game.GameMap.Chunks[63].Position.Y);
+ Assert.Equal(1, game.GameMap.Chunks[63].Height);
+ }
+
+ [Fact]
+ public void Start_StartedYet_ThrowsCorrectException()
+ {
+ var game = IGame.Create();
+ game.Start();
+ Assert.Throws(game.Start);
+ }
+
+ [Fact]
+ public void Start_DoNothing_ReturnsCorrectValue()
+ {
+ var game = IGame.Create();
+ game.Start();
+ Assert.Equal(0, game.Players[0].PlayerId);
+ Assert.Equal(0, game.Players[0].SpawnPoint.X);
+ Assert.Equal(0.5f, game.Players[0].PlayerPosition.Y);
+ Assert.Equal(1, game.Players[1].PlayerId);
+ Assert.Equal(7, game.Players[1].SpawnPoint.X);
+ Assert.Equal(7.5f, game.Players[1].PlayerPosition.Y);
+ Assert.Equal(IGame.Stage.Running, game.CurrentStage);
+ Assert.Equal(0, game.ElapsedTicks);
+ Assert.True(game.Players[0].IsAlive);
+ Assert.True(game.Players[1].IsAlive);
+ Assert.Null(game.Winner);
+ }
+
+ [Fact]
+ public void Start_AfterGameStartEvent_IsRaised()
+ {
+ bool eventReceived = false;
+ var game = IGame.Create();
+ game.AfterGameStartEvent += (sender, args) =>
+ {
+ eventReceived = true;
+ };
+ game.Start();
+ Assert.True(eventReceived);
+ }
+}
diff --git a/host/src/EdcHost.Tests/UnitTests/Games/MapTests.cs b/host/src/EdcHost.Tests/UnitTests/Games/MapTests.cs
new file mode 100644
index 0000000..c63408c
--- /dev/null
+++ b/host/src/EdcHost.Tests/UnitTests/Games/MapTests.cs
@@ -0,0 +1,60 @@
+using EdcHost.Games;
+using Xunit;
+
+namespace EdcHost.Tests.UnitTests.Games;
+public class IMapTests
+{
+ public class MockPosition : IPosition
+ {
+ public int X { get; set; }
+ public int Y { get; set; }
+ }
+
+ public static IPosition point1 = new MockPosition { X = 1, Y = 1 };
+ public static IPosition point2 = new MockPosition { X = 2, Y = 2 };
+ public static IPosition point3 = new MockPosition { X = 3, Y = 3 };
+ public static IPosition point4 = new MockPosition { X = 4, Y = 4 };
+
+ public IPosition[] spawnPoints = new IPosition[] { point1, point2, point3, point4 };
+
+ [Fact]
+ public void IMap_CorrectyInitialized()
+ {
+ IMap map = IMap.Create(spawnPoints);
+ Assert.NotNull(map.Chunks);
+ Assert.Equal(64, map.Chunks.Count);
+ for (int i = 0; i < 64; i++)
+ {
+ Assert.Equal(i % 8, map.Chunks[i].Position.X);
+ Assert.Equal(i / 8, map.Chunks[i].Position.Y);
+ }
+ Assert.Equal(0, map.Chunks[0].Height);
+ Assert.Equal(0, map.Chunks[20].Height);
+ Assert.Equal(1, map.Chunks[9].Height);
+ Assert.Equal(1, map.Chunks[18].Height);
+ Assert.Equal(1, map.Chunks[27].Height);
+ Assert.Equal(1, map.Chunks[36].Height);
+ }
+
+ [Fact]
+ public void GetChunkAt_DoNothing_ReturnsCorrectChunkPosition()
+ {
+ IMap map = IMap.Create(spawnPoints);
+ MockPosition positionMock = new() { X = 2, Y = 3 };
+ IChunk expectedChunk = map.Chunks[26];
+ IChunk actualChunk = map.GetChunkAt(positionMock);
+ Assert.Equal(expectedChunk, actualChunk);
+ }
+
+ [Theory]
+ [InlineData(-1, 3)]
+ [InlineData(2, -1)]
+ [InlineData(8, 3)]
+ [InlineData(2, 8)]
+ public void GetChunkAt_ThrowsRightException(int x, int y)
+ {
+ IMap map = IMap.Create(spawnPoints);
+ MockPosition positionMock = new() { X = x, Y = y };
+ Assert.Throws(() => map.GetChunkAt(positionMock));
+ }
+}
diff --git a/host/src/EdcHost.Tests/UnitTests/Games/MineTests.cs b/host/src/EdcHost.Tests/UnitTests/Games/MineTests.cs
new file mode 100644
index 0000000..728d76b
--- /dev/null
+++ b/host/src/EdcHost.Tests/UnitTests/Games/MineTests.cs
@@ -0,0 +1,79 @@
+using EdcHost.Games;
+using Xunit;
+
+namespace EdcHost.Tests.UnitTests.Games;
+
+public interface Iint
+{
+ int GetCurrentint();
+}
+
+public class IMineTest
+{
+ public class MockPosition : IPosition
+ {
+ public int X { get; set; }
+ public int Y { get; set; }
+ }
+
+ [Fact]
+ public void IntAccumulatedOreCount_NotGenerate_ReturnsCorrectValue()
+ {
+ IMine mine = IMine.Create(IMine.OreKindType.Diamond, new MockPosition { X = 0, Y = 0 }, 0);
+ Assert.Equal(0, mine.AccumulatedOreCount);
+ }
+
+ [Theory]
+ [InlineData(IMine.OreKindType.IronIngot, IMine.OreKindType.IronIngot)]
+ [InlineData(IMine.OreKindType.GoldIngot, IMine.OreKindType.GoldIngot)]
+ [InlineData(IMine.OreKindType.Diamond, IMine.OreKindType.Diamond)]
+ public void OreKind_ReturnsCorrectValue(IMine.OreKindType oreKindType, IMine.OreKindType expectedOreKind)
+ {
+ IMine mine = IMine.Create(oreKindType, new MockPosition { X = 0, Y = 0 }, 0);
+ Assert.Equal(expectedOreKind, mine.OreKind);
+ }
+
+ [Theory]
+ [InlineData(3, 3)]
+ [InlineData(4, 4)]
+ [InlineData(30, 30)]
+ [InlineData(100, 100)]
+ [InlineData(200, 200)]
+ public void GenerateOre_AccumulatedOreCountAdd_ReturnsCorrectValue(int generate, int expectedValue)
+ {
+ IMine mine = IMine.Create(IMine.OreKindType.Diamond, new MockPosition { X = 0, Y = 0 }, 0);
+ for (int i = 0; i < generate; i++)
+ {
+ mine.GenerateOre(0);
+ }
+ Assert.Equal(expectedValue, mine.AccumulatedOreCount);
+ }
+
+ [Fact]
+ public void PickUpOre_CountLessThanAccumulatedOreCount_ReturnsCorrctValue()
+ {
+ IMine mine = IMine.Create(IMine.OreKindType.Diamond, new MockPosition { X = 0, Y = 0 }, 0);
+ for (int i = 0; i < 200; i++)
+ {
+ mine.GenerateOre(0);
+ }
+ int count = 64;
+ int expectedValue = 136;
+ mine.PickUpOre(count);
+ Assert.Equal(expectedValue, mine.AccumulatedOreCount);
+ }
+
+ [Fact]
+ public void PickUpOre_CountMoreThanAccumulatedOreCount_ReturnsCorrctValue()
+ {
+ IMine mine = IMine.Create(IMine.OreKindType.Diamond, new MockPosition { X = 0, Y = 0 }, 0);
+ for (int i = 0; i < 30; i++)
+ {
+ mine.GenerateOre(0);
+ }
+ int count = 60;
+ InvalidOperationException ex = Assert.Throws(() => { mine.PickUpOre(count); });
+ Assert.Equal("No enough ore.", ex.Message);
+ }
+
+}
diff --git a/host/src/EdcHost.Tests/UnitTests/Games/PlayerTests.cs b/host/src/EdcHost.Tests/UnitTests/Games/PlayerTests.cs
new file mode 100644
index 0000000..52ae804
--- /dev/null
+++ b/host/src/EdcHost.Tests/UnitTests/Games/PlayerTests.cs
@@ -0,0 +1,399 @@
+using EdcHost.Games;
+using Xunit;
+
+namespace EdcHost.Tests.UnitTests.Games;
+
+public class PlayerTests
+{
+ const int Expected_MaxHealth = 20;
+ const int Expected_Strength = 1;
+ const int Expected_Initial_ActionPoints = 0;
+ const int Expected_Initial_WoolCount = 8;
+
+ [Fact]
+ public void Player_Initialization_DefaultConstructor()
+ {
+ // Arrange & Act
+ IPlayer player = IPlayer.Create();
+
+ // Assert
+ Assert.Equal(1, player.PlayerId);
+ Assert.Equal(0, player.EmeraldCount);
+ Assert.True(player.IsAlive);
+ Assert.True(player.HasBed);
+ Assert.NotNull(player.SpawnPoint);
+ Assert.NotNull(player.PlayerPosition);
+ Assert.Equal(Expected_Initial_WoolCount, player.WoolCount);
+ Assert.Equal(Expected_MaxHealth, player.Health);
+ Assert.Equal(Expected_MaxHealth, player.MaxHealth);
+ Assert.Equal(Expected_Strength, player.Strength);
+ Assert.Equal(Expected_Initial_ActionPoints, player.ActionPoints);
+ }
+
+ [Theory]
+ [InlineData(1)]
+ [InlineData(2)]
+ [InlineData(3)]
+ [InlineData(4)]
+ [InlineData(5)]
+ [InlineData(6)]
+ [InlineData(7)]
+ [InlineData(8)]
+ [InlineData(int.MaxValue)]
+ public void IdX_DoNothing_ReturnsConstructorValue(int X)
+ {
+ IPlayer player = IPlayer.Create(X, 0, 0, 0, 0);
+ Assert.Equal(X, player.PlayerId);
+ Assert.Equal(0, player.EmeraldCount);
+ Assert.True(player.IsAlive);
+ Assert.True(player.HasBed);
+ Assert.Equal(0, player.SpawnPoint.X);
+ Assert.Equal(0, player.SpawnPoint.Y);
+ Assert.Equal(0, player.PlayerPosition.X);
+ Assert.Equal(0, player.PlayerPosition.Y);
+ Assert.Equal(Expected_Initial_WoolCount, player.WoolCount);
+ Assert.Equal(Expected_MaxHealth, player.Health);
+ Assert.Equal(Expected_MaxHealth, player.MaxHealth);
+ Assert.Equal(Expected_Strength, player.Strength);
+ Assert.Equal(Expected_Initial_ActionPoints, player.ActionPoints);
+ }
+ [Theory]
+ [InlineData(0, 0)]
+ [InlineData(1, 1)]
+ [InlineData(-1, -0.5f)]
+ [InlineData(int.MaxValue, int.MaxValue)]
+ [InlineData(int.MinValue, int.MinValue)]
+ [InlineData(int.MaxValue, int.MinValue)]
+ public void SpawnPoint_DoNothing_ReturnsConstructorValue(int X, int Y)
+ {
+ IPlayer player = IPlayer.Create(1, X, Y, 0, 0);
+ Assert.Equal(X, player.SpawnPoint.X);
+ Assert.Equal(Y, player.SpawnPoint.Y);
+ }
+
+ [Theory]
+ [InlineData(0, 0)]
+ [InlineData(0.5f, 0.5f)]
+ [InlineData(-0.5f, -0.5f)]
+ [InlineData(0.5f, -0.5f)]
+ [InlineData(1.0f / 3, 1.0f / 3)]
+ [InlineData(float.MaxValue, float.MaxValue)]
+ [InlineData(float.MinValue, float.MinValue)]
+ [InlineData(float.MaxValue, float.MinValue)]
+ public void PlayerPosition_DoNothing_ReturnsConstructorValue(float X, float Y)
+ {
+ IPlayer player = IPlayer.Create(1, 0, 0, X, Y);
+ Assert.Equal(X, player.PlayerPosition.X);
+ Assert.Equal(Y, player.PlayerPosition.Y);
+ }
+
+ [Theory]
+ [InlineData(1)]
+ [InlineData(0)]
+ [InlineData(int.MaxValue)]
+ public void EmeraldAdd_IncreaseBy(int x)
+ {
+ IPlayer player = IPlayer.Create();
+ player.EmeraldAdd(x);
+ Assert.Equal(x, player.EmeraldCount);
+ }
+
+ [Theory]
+ [InlineData(0, 0)]
+ [InlineData(0.5f, 0.5f)]
+ [InlineData(-0.5f, -0.5f)]
+ [InlineData(0.5f, -0.5f)]
+ [InlineData(1.0f / 3, 1.0f / 3)]
+ [InlineData(float.MaxValue, float.MaxValue)]
+ [InlineData(float.MinValue, float.MinValue)]
+ [InlineData(float.MaxValue, float.MinValue)]
+ public void Move_ToNewPosition_ReturnsNewCoordinate(float newX, float newY)
+ {
+ IPlayer player = IPlayer.Create();
+ player.OnMove += (this_x, args) =>
+ {
+ Assert.Equal(0, args.PositionBeforeMovement.X);
+ Assert.Equal(0, args.PositionBeforeMovement.Y);
+ Assert.Equal(newX, args.Position.X);
+ Assert.Equal(newY, args.Position.Y);
+ Assert.Equal(player, args.Player);
+ Assert.Equal(player, this_x);
+ };
+ player.Move(newX, newY);
+ Assert.Equal(newX, player.PlayerPosition.X);
+ Assert.Equal(newY, player.PlayerPosition.Y);
+ }
+
+ [Theory]
+ [InlineData(0, 0)]
+ [InlineData(1, 1)]
+ [InlineData(-1, -1)]
+ [InlineData(int.MaxValue, int.MaxValue)]
+ [InlineData(int.MinValue, int.MinValue)]
+ [InlineData(int.MaxValue, int.MinValue)]
+ public void Attack_TestPosition_CheckEvent(int newX, int newY)
+ {
+ IPlayer player = IPlayer.Create();
+ bool event_triggered = false;
+ player.OnAttack += (this_x, args) =>
+ {
+ Assert.Equal(Expected_Strength, args.Strength);
+ Assert.Equal(newX, args.Position.X);
+ Assert.Equal(newY, args.Position.Y);
+ Assert.Equal(player, args.Player);
+ Assert.Equal(player, this_x);
+ event_triggered = true;
+ };
+ player.Attack(newX, newY);
+ Assert.True(event_triggered);
+ }
+ //TODO: wait for implementation of WoolCount adding.
+
+ [Theory]
+ [InlineData(0, 0)]
+ [InlineData(1, 1)]
+ [InlineData(-1, -1)]
+ [InlineData(int.MaxValue, int.MaxValue)]
+ [InlineData(int.MinValue, int.MinValue)]
+ [InlineData(int.MaxValue, int.MinValue)]
+ public void Place_TestPosition_HasWool_EventTriggered(int newX, int newY)
+ {
+ IPlayer player = IPlayer.Create();
+ player.EmeraldAdd(1);
+ player.Trade(IPlayer.CommodityKindType.Wool);
+ bool event_triggered = false;
+ player.OnPlace += (this_x, args) =>
+ {
+ Assert.Equal(newX, args.Position.X);
+ Assert.Equal(newY, args.Position.Y);
+ Assert.Equal(player, args.Player);
+ Assert.Equal(player, this_x);
+ event_triggered = true;
+ };
+ player.Place(newX, newY);
+ Assert.True(event_triggered);
+ }
+ [Fact]
+ public void Place_NoWool_EventNotTriggered()
+ {
+ IPlayer player = IPlayer.Create();
+ bool event_triggered = false;
+ player.OnPlace += (this_x, args) =>
+ {
+ event_triggered = true;
+ };
+ for (int i = 1; i <= Expected_Initial_WoolCount; i++)
+ {
+ player.DecreaseWoolCount();
+ Assert.Equal(Expected_Initial_WoolCount - i, player.WoolCount);
+ }
+ player.Place(0, 0);
+ Assert.False(event_triggered);
+ }
+ [Theory]
+ [InlineData(1)]
+ [InlineData(19)]
+ public void Hurt_LessthanHealth_CheckNewHealth(int EnemyStrength)
+ {
+ IPlayer player = IPlayer.Create();
+ bool event_triggered = false;
+ player.OnDie += (this_x, args) =>
+ {
+ event_triggered = true;
+ };
+ player.Hurt(EnemyStrength);
+ Assert.Equal(Expected_MaxHealth - EnemyStrength, player.Health);
+ Assert.False(event_triggered);
+ Assert.True(player.IsAlive);
+ }
+ [Theory]
+ [InlineData(20)]
+ [InlineData(int.MaxValue)]
+ public void Hurt_CoversHealth_PlayerDie(int EnemyStrength)
+ {
+ IPlayer player = IPlayer.Create();
+ bool event_triggered = false;
+ player.OnDie += (this_x, args) =>
+ {
+ Assert.Equal(player, this_x);
+ Assert.Equal(player, args.Player);
+ event_triggered = true;
+ };
+ player.Hurt(EnemyStrength);
+ Assert.Equal(0, player.Health);
+ Assert.True(event_triggered);
+ Assert.False(player.IsAlive);
+ }
+ [Fact]
+ public void KillandSpawn_HasBed_Alive()
+ {
+ IPlayer player = IPlayer.Create();
+ player.Hurt(100);
+ Assert.Equal(0, player.Health);
+ Assert.False(player.IsAlive);
+ player.Spawn(player.MaxHealth);
+ Assert.Equal(Expected_MaxHealth, player.Health);
+ Assert.True(player.IsAlive);
+ }
+ [Fact]
+ public void KillandSpawn_BedDestroyed_NothingHappens()
+ {
+ IPlayer player = IPlayer.Create();
+ player.DestroyBed();
+ player.Hurt(100);
+ Assert.Equal(0, player.Health);
+ Assert.False(player.IsAlive);
+ player.Spawn(player.MaxHealth);
+ Assert.Equal(0, player.Health);
+ Assert.False(player.IsAlive);
+ }
+ [Fact]
+ public void DecreaseWoolCount_DecreaseByOne()
+ {
+ IPlayer player = IPlayer.Create();
+ player.EmeraldAdd(2);
+ player.Trade(IPlayer.CommodityKindType.Wool);
+ Assert.Equal(Expected_Initial_WoolCount + 1, player.WoolCount);
+ player.DecreaseWoolCount();
+ Assert.Equal(Expected_Initial_WoolCount, player.WoolCount);
+ }
+ [Fact]
+ public void PerformActionPosition_Attack_CheckEvent()
+ {
+ IPlayer player = IPlayer.Create();
+ bool event_triggered = false;
+ player.OnAttack += (this_x, args) =>
+ {
+ event_triggered = true;
+ };
+ player.PerformActionPosition(IPlayer.ActionKindType.Attack, 0, 0);
+ Assert.True(event_triggered);
+ }
+ [Fact]
+ public void PerformActionPosition_Place_CheckEvent()
+ {
+ IPlayer player = IPlayer.Create();
+ bool event_triggered = false;
+ player.OnPlace += (this_x, args) =>
+ {
+ event_triggered = true;
+ };
+ while (player.WoolCount > 0)
+ {
+ player.DecreaseWoolCount();
+ }
+ player.PerformActionPosition(IPlayer.ActionKindType.PlaceBlock, 0, 0);
+ Assert.False(event_triggered);
+
+ player.EmeraldAdd(2);
+ player.Trade(IPlayer.CommodityKindType.Wool);
+ player.PerformActionPosition(IPlayer.ActionKindType.PlaceBlock, 0, 0);
+ Assert.True(event_triggered);
+ }
+ //TODO: TEST Trade
+ [Fact]
+ public void Trade_AgilityBoost_CommodityKindType()
+ {
+ // Arrange
+ IPlayer player = IPlayer.Create();
+ player.EmeraldAdd(64);
+
+ // Act
+ bool result = player.Trade(IPlayer.CommodityKindType.AgilityBoost);
+
+ // Assert
+ Assert.True(result);
+ Assert.Equal(32, player.EmeraldCount);
+ Assert.Equal(1, player.ActionPoints);
+
+ // Act
+ result = player.Trade(IPlayer.CommodityKindType.AgilityBoost);
+
+ // Assert
+ Assert.True(result);
+ Assert.Equal(0, player.EmeraldCount);
+ Assert.Equal(2, player.ActionPoints);
+
+ // Act
+ result = player.Trade(IPlayer.CommodityKindType.AgilityBoost);
+
+ // Assert
+ Assert.False(result);
+ Assert.Equal(0, player.EmeraldCount);
+ Assert.Equal(2, player.ActionPoints);
+ }
+
+ [Fact]
+ public void Trade_HealthBoost_CommodityKindType()
+ {
+ // Arrange
+ IPlayer player = IPlayer.Create();
+ player.EmeraldAdd(64);
+
+ // Act
+ bool result = player.Trade(IPlayer.CommodityKindType.HealthBoost);
+
+ // Assert
+ Assert.True(result);
+ Assert.Equal(32, player.EmeraldCount);
+ Assert.Equal(23, player.MaxHealth);
+
+ // Act
+ result = player.Trade(IPlayer.CommodityKindType.HealthBoost);
+
+ // Assert
+ Assert.True(result);
+ Assert.Equal(0, player.EmeraldCount);
+ Assert.Equal(26, player.MaxHealth);
+
+ // Act
+ result = player.Trade(IPlayer.CommodityKindType.HealthBoost);
+
+ // Assert
+ Assert.False(result);
+ Assert.Equal(0, player.EmeraldCount);
+ Assert.Equal(26, player.MaxHealth);
+ }
+
+ [Fact]
+ public void Trade_HealthPotion_CommodityKindType()
+ {
+ // Arrange
+ IPlayer player = IPlayer.Create();
+ player.EmeraldAdd(5);
+ player.Hurt(10);
+
+ // Act
+ bool result = player.Trade(IPlayer.CommodityKindType.HealthPotion);
+
+ // Assert
+ Assert.True(result);
+ Assert.Equal(1, player.EmeraldCount);
+ Assert.Equal(11, player.Health);
+
+ // Act
+ result = player.Trade(IPlayer.CommodityKindType.HealthPotion);
+
+ // Assert
+ Assert.False(result);
+ Assert.Equal(1, player.EmeraldCount);
+ Assert.Equal(11, player.Health);
+ }
+
+ [Fact]
+ public void Trade_UnknownCommodityKindType()
+ {
+ // Arrange
+ IPlayer player = IPlayer.Create();
+ player.EmeraldAdd(10);
+
+ // Act
+
+ // Assert
+ Assert.Throws(
+ () => player.Trade((IPlayer.CommodityKindType)99)
+ ); // Unknown commodity kind
+ Assert.Equal(10, player.EmeraldCount); // Emerald count remains unchanged
+ }
+ //
+}
diff --git a/host/src/EdcHost.Tests/UnitTests/Games/PositionTests.cs b/host/src/EdcHost.Tests/UnitTests/Games/PositionTests.cs
new file mode 100644
index 0000000..da49bba
--- /dev/null
+++ b/host/src/EdcHost.Tests/UnitTests/Games/PositionTests.cs
@@ -0,0 +1,152 @@
+using EdcHost.Games;
+using Xunit;
+
+namespace EdcHost.Tests.UnitTests.Games;
+
+public class PositionTests
+{
+ [Theory]
+ [InlineData(0, 0)]
+ [InlineData(1, 1)]
+ [InlineData(-1, -1)]
+ [InlineData(int.MinValue, int.MinValue)]
+ [InlineData(int.MaxValue, int.MaxValue)]
+ public void IntX_DoNothing_ReturnsConstructorValue(int x, int expectedX)
+ {
+ IPosition position = IPosition.Create(x, 0);
+
+ int actualX = position.X;
+
+ Assert.Equal(expectedX, actualX);
+ }
+
+ [Theory]
+ [InlineData(0, 0)]
+ [InlineData(1, 1)]
+ [InlineData(-1, -1)]
+ [InlineData(int.MinValue, int.MinValue)]
+ [InlineData(int.MaxValue, int.MaxValue)]
+ public void IntX_SingleNumber_ReturnsSameNumber(int x, int expectedX)
+ {
+#pragma warning disable IDE0017
+ IPosition position = IPosition.Create(0, 0);
+
+ position.X = x;
+ int actualX = position.X;
+
+ Assert.Equal(expectedX, actualX);
+ }
+
+ [Theory]
+ [InlineData(0, 0)]
+ [InlineData(1, 1)]
+ [InlineData(-1, -1)]
+ [InlineData(int.MinValue, int.MinValue)]
+ [InlineData(int.MaxValue, int.MaxValue)]
+ public void IntY_DoNothing_ReturnsConstructorValue(int y, int expectedY)
+ {
+ IPosition position = IPosition.Create(0, y);
+
+ int actualY = position.Y;
+
+ Assert.Equal(expectedY, actualY);
+ }
+
+ [Theory]
+ [InlineData(0, 0)]
+ [InlineData(1, 1)]
+ [InlineData(-1, -1)]
+ [InlineData(int.MinValue, int.MinValue)]
+ [InlineData(int.MaxValue, int.MaxValue)]
+ public void IntY_SingleNumber_ReturnsSameNumber(int y, int expectedY)
+ {
+#pragma warning disable IDE0017
+ IPosition position = IPosition.Create(0, 0);
+
+ position.Y = y;
+ int actualY = position.Y;
+
+ Assert.Equal(expectedY, actualY);
+ }
+
+ [Theory]
+ [InlineData(0.0, 0.0)]
+ [InlineData(0.1, 0.1)]
+ [InlineData(-0.1, -0.1)]
+ [InlineData(float.MinValue, float.MinValue)]
+ [InlineData(float.MaxValue, float.MaxValue)]
+ [InlineData(float.PositiveInfinity, float.PositiveInfinity)]
+ [InlineData(float.NegativeInfinity, float.NegativeInfinity)]
+ [InlineData(float.NaN, float.NaN)]
+ [InlineData(float.Epsilon, float.Epsilon)]
+ public void FloatX_DoNothing_ReturnsConstructorValue(float x, float expectedX)
+ {
+ IPosition position = IPosition.Create(x, 0);
+
+ float actualX = position.X;
+
+ Assert.Equal(expectedX, actualX);
+ }
+
+ [Theory]
+ [InlineData(0.0, 0.0)]
+ [InlineData(0.1, 0.1)]
+ [InlineData(-0.1, -0.1)]
+ [InlineData(float.MinValue, float.MinValue)]
+ [InlineData(float.MaxValue, float.MaxValue)]
+ [InlineData(float.PositiveInfinity, float.PositiveInfinity)]
+ [InlineData(float.NegativeInfinity, float.NegativeInfinity)]
+ [InlineData(float.NaN, float.NaN)]
+ [InlineData(float.Epsilon, float.Epsilon)]
+ public void FloatX_SingleNumber_ReturnsSameNumber(float x, float expectedX)
+ {
+#pragma warning disable IDE0017
+ IPosition position = IPosition.Create(0, 0);
+
+ position.X = x;
+ float actualX = position.X;
+
+ Assert.Equal(expectedX, actualX);
+ }
+
+ [Theory]
+ [InlineData(0.0, 0.0)]
+ [InlineData(0.1, 0.1)]
+ [InlineData(-0.1, -0.1)]
+ [InlineData(float.MinValue, float.MinValue)]
+ [InlineData(float.MaxValue, float.MaxValue)]
+ [InlineData(float.PositiveInfinity, float.PositiveInfinity)]
+ [InlineData(float.NegativeInfinity, float.NegativeInfinity)]
+ [InlineData(float.NaN, float.NaN)]
+ [InlineData(float.Epsilon, float.Epsilon)]
+ public void FloatY_DoNothing_ReturnsConstructorValue(float y, float expectedY)
+ {
+ IPosition position = IPosition.Create(0, y);
+
+ float actualY = position.Y;
+
+ Assert.Equal(expectedY, actualY);
+ }
+
+ [Theory]
+ [InlineData(0.0, 0.0)]
+ [InlineData(0.1, 0.1)]
+ [InlineData(-0.1, -0.1)]
+ [InlineData(float.MinValue, float.MinValue)]
+ [InlineData(float.MaxValue, float.MaxValue)]
+ [InlineData(float.PositiveInfinity, float.PositiveInfinity)]
+ [InlineData(float.NegativeInfinity, float.NegativeInfinity)]
+ [InlineData(float.NaN, float.NaN)]
+ [InlineData(float.Epsilon, float.Epsilon)]
+ public void FloatY_SingleNumber_ReturnsSameNumber(float y, float expectedY)
+ {
+#pragma warning disable IDE0017
+ IPosition position = IPosition.Create(0, 0);
+
+ position.Y = y;
+ float actualY = position.Y;
+
+ Assert.Equal(expectedY, actualY);
+ }
+}
+
diff --git a/host/src/EdcHost.Tests/UnitTests/SlaveServers/IPacketTests.cs b/host/src/EdcHost.Tests/UnitTests/SlaveServers/IPacketTests.cs
new file mode 100644
index 0000000..374f8cf
--- /dev/null
+++ b/host/src/EdcHost.Tests/UnitTests/SlaveServers/IPacketTests.cs
@@ -0,0 +1,25 @@
+using EdcHost.SlaveServers;
+using Xunit;
+
+namespace EdcHost.Tests.UnitTests.SlaveServers;
+public class IPacketTests
+{
+ [Fact]
+ public void CalculateChecksum_ReturnCorrectValue()
+ {
+ byte[] bytes = new byte[] { 0x01, 0x02, 0x03, 0x04 };
+ byte checksum = IPacket.CalculateChecksum(bytes);
+ Assert.Equal(0x04, checksum);
+ }
+
+ [Fact]
+ public void GetPacketData_ReturnCorrectValue()
+ {
+ byte[] data = new byte[] { 0x01, 0x02, 0x03, 0x04 };
+ byte[] header = IPacket.GeneratePacketHeader(data);
+ Assert.Equal(0x55, header[0]);
+ Assert.Equal(0xAA, header[1]);
+ Assert.Equal(data.Length, BitConverter.ToInt16(header, 2));
+ }
+
+}
diff --git a/host/src/EdcHost.Tests/UnitTests/SlaveServers/PacketFromHostTests.cs b/host/src/EdcHost.Tests/UnitTests/SlaveServers/PacketFromHostTests.cs
new file mode 100644
index 0000000..b0f9dea
--- /dev/null
+++ b/host/src/EdcHost.Tests/UnitTests/SlaveServers/PacketFromHostTests.cs
@@ -0,0 +1,103 @@
+using EdcHost.SlaveServers;
+using Xunit;
+
+namespace EdcHost.Tests.UnitTests.SlaveServers;
+
+public class PacketFromHostTests
+{
+ [Fact]
+ public void PacketFromHost_CorrectlyInitialized()
+ {
+ int exp_gameStage = 0;
+ int exp_elapsedTime = 12000;
+ List exp_heightOfChunks = Enumerable.Repeat(0, 64).ToList();
+ bool exp_hasBed = true;
+ bool exp_hasBedOpponent = true;
+ float exp_positionX = 0.4f;
+ float exp_positionY = 0.4f;
+ float exp_positionOpponentX = 7.4f;
+ float exp_positionOpponentY = 7.4f;
+ int exp_agility = 0;
+ int exp_health = 8;
+ int exp_MaxHealth = 8;
+ int exp_strength = 4;
+ int exp_emeraldCount = 64;
+ int exp_woolcount = 64;
+ List exp_owningOreKindOfChunks = Enumerable.Repeat(0, 64).ToList();
+ List exp_informationOfChunks = Enumerable.Repeat(0, 64).ToList();
+ PacketFromHost packetFromHost = new(
+ exp_gameStage, exp_elapsedTime, exp_heightOfChunks, exp_hasBed, exp_hasBedOpponent,
+ exp_positionX, exp_positionY, exp_positionOpponentX, exp_positionOpponentY, exp_agility,
+ exp_health, exp_MaxHealth, exp_strength, exp_emeraldCount, exp_woolcount,
+ exp_owningOreKindOfChunks);
+ Assert.Equal(exp_gameStage, packetFromHost.GameStage);
+ Assert.Equal(exp_elapsedTime, packetFromHost.ElapsedTime);
+ Assert.Equal(exp_informationOfChunks, packetFromHost.InformationOfChunks);
+ Assert.Equal(exp_hasBed, packetFromHost.HasBed);
+ Assert.Equal(exp_hasBedOpponent, packetFromHost.HasBedOpponent);
+ Assert.Equal(exp_positionX, packetFromHost.PositionX);
+ Assert.Equal(exp_positionY, packetFromHost.PositionY);
+ Assert.Equal(exp_positionOpponentX, packetFromHost.PositionOpponentX);
+ Assert.Equal(exp_positionOpponentY, packetFromHost.PositionOpponentY);
+ Assert.Equal(exp_agility, packetFromHost.Agility);
+ Assert.Equal(exp_health, packetFromHost.Health);
+ Assert.Equal(exp_MaxHealth, packetFromHost.MaxHealth);
+ Assert.Equal(exp_strength, packetFromHost.Strength);
+ Assert.Equal(exp_strength, packetFromHost.Strength);
+ Assert.Equal(exp_emeraldCount, packetFromHost.EmeraldCount);
+ Assert.Equal(exp_woolcount, packetFromHost.WoolCount);
+ }
+
+ [Fact]
+ public void ToBytes_CorrectlyCoverted()
+ {
+ int exp_gameStage = 0;
+ int exp_elapsedTime = 12000;
+ // len=64 content all zero
+ List exp_heightOfChunks = Enumerable.Repeat(0, 64).ToList();
+ bool exp_hasBed = true;
+ bool exp_hasBedOpponent = true;
+ float exp_positionX = 0.4f;
+ float exp_positionY = 0.4f;
+ float exp_positionOpponentX = 7.4f;
+ float exp_positionOpponentY = 7.4f;
+ int exp_agility = 0;
+ int exp_health = 8;
+ int exp_MaxHealth = 8;
+ int exp_strength = 4;
+ int exp_emeraldCount = 64;
+ int exp_woolcount = 64;
+ List exp_owningOreKindOfChunks = Enumerable.Repeat(0, 64).ToList();
+ List exp_informationOfChunks = Enumerable.Repeat(0, 64).ToList();
+ PacketFromHost exp_Packet = new(
+ exp_gameStage, exp_elapsedTime,
+ exp_heightOfChunks, exp_hasBed, exp_hasBedOpponent,
+ exp_positionX, exp_positionY, exp_positionOpponentX, exp_positionOpponentY,
+ exp_agility, exp_health, exp_MaxHealth, exp_strength, exp_emeraldCount, exp_woolcount,
+ exp_owningOreKindOfChunks
+ );
+ byte[] data = exp_Packet.ToBytes();
+ PacketFromHost actualPacket = new(data);
+ Assert.Equal(exp_Packet.GameStage, actualPacket.GameStage);
+ Assert.Equal(exp_Packet.ElapsedTime, actualPacket.ElapsedTime);
+ Assert.Equal(exp_Packet.InformationOfChunks.Count, actualPacket.InformationOfChunks.Count);
+ for (int i = 0; i < exp_Packet.InformationOfChunks.Count; i++)
+ {
+ Assert.Equal(exp_Packet.InformationOfChunks[i], actualPacket.InformationOfChunks[i]);
+ }
+
+ Assert.Equal(exp_Packet.HasBed, actualPacket.HasBed);
+ Assert.Equal(exp_Packet.HasBedOpponent, actualPacket.HasBedOpponent);
+ Assert.Equal(exp_Packet.PositionX, actualPacket.PositionX);
+ Assert.Equal(exp_Packet.PositionY, actualPacket.PositionY);
+ Assert.Equal(exp_Packet.PositionOpponentX, actualPacket.PositionOpponentX);
+ Assert.Equal(exp_Packet.PositionOpponentY, actualPacket.PositionOpponentY);
+ Assert.Equal(exp_Packet.Agility, actualPacket.Agility);
+ Assert.Equal(exp_Packet.Health, actualPacket.Health);
+ Assert.Equal(exp_Packet.MaxHealth, actualPacket.MaxHealth);
+ Assert.Equal(exp_Packet.Strength, actualPacket.Strength);
+ Assert.Equal(exp_Packet.EmeraldCount, actualPacket.EmeraldCount);
+ Assert.Equal(exp_Packet.WoolCount, actualPacket.WoolCount);
+ }
+
+}
diff --git a/host/src/EdcHost.Tests/UnitTests/SlaveServers/PacketFromSlaveTests.cs b/host/src/EdcHost.Tests/UnitTests/SlaveServers/PacketFromSlaveTests.cs
new file mode 100644
index 0000000..8bd7fd7
--- /dev/null
+++ b/host/src/EdcHost.Tests/UnitTests/SlaveServers/PacketFromSlaveTests.cs
@@ -0,0 +1,73 @@
+using EdcHost.SlaveServers;
+using Xunit;
+
+namespace EdcHost.Tests.UnitTests.SlaveServers;
+
+public class PacketFromSlaverTests
+{
+ [Fact]
+ public void PacketFromSlave_ValidByteArray_ParsesDataCorrectly()
+ {
+ byte[] bytes = new byte[] { 0x55, 0xAA, 0x02, 0x00, 0x07, 0x03, 0x04 };
+ var packet = new PacketFromSlave(bytes);
+ Assert.Equal(3, packet.ActionType);
+ Assert.Equal(4, packet.Param);
+ }
+
+ [Fact]
+ public void PacketFromSlave_InvalidHeader_ThrowsException()
+ {
+ byte[] bytes1 = new byte[] { 0x55, 0xAB, 0x00, 0x02, 0x01, 0x03, 0x04 };
+ byte[] bytes2 = new byte[] { 0x50, 0xAA, 0x00, 0x02, 0x01, 0x03, 0x04 };
+ Assert.Throws(() => new PacketFromSlave(bytes1));
+ Assert.Throws(() => new PacketFromSlave(bytes2));
+ }
+
+ [Fact]
+ public void PacketFromSlave_InvalidDataLength_ThrowsException()
+ {
+ byte[] bytes = new byte[] { 0x55, 0xAA, 0x00 };
+ Assert.Throws(() => new PacketFromSlave(bytes));
+ }
+
+ [Fact]
+ public void PacketFromSlave_InvalidChecksum_ThrowsException()
+ {
+ byte[] bytes = new byte[] { 0x55, 0xAA, 0x00, 0x02, 0x01, 0x03, 0x05 };
+ Assert.Throws(() => new PacketFromSlave(bytes));
+ }
+
+ [Theory]
+ [InlineData(0, 0)]
+ [InlineData(1, 1)]
+ [InlineData(2, 2)]
+ [InlineData(8, 8)]
+ public void PacketFromSlave_CorrectlyInitilized(int exp_actionType, int exp_param)
+ {
+ PacketFromSlave packet = new(exp_actionType, exp_param);
+ Assert.Equal(exp_actionType, packet.ActionType);
+ Assert.Equal(exp_param, packet.Param);
+ }
+
+ [Fact]
+ public void ToBytes_ReturnsCorrectByteArray()
+ {
+ int exp_actionType = 1;
+ int exp_param = 2;
+ PacketFromSlave packet = new(exp_actionType, exp_param);
+ byte[] result = packet.ToBytes();
+ byte[] expectedBytes = new byte[]
+ {
+ 0x55, 0xAA, // Header
+ 0x02, 0x00, // Data length (2 bytes)
+ 0x03, // Checksum
+ 0x01, // ActionType
+ 0x02 // Param
+ };
+ Assert.Equal(expectedBytes, result);
+ }
+
+
+
+
+}
diff --git a/host/src/EdcHost.Tests/UnitTests/SlaveServers/SlaveServerTests.cs b/host/src/EdcHost.Tests/UnitTests/SlaveServers/SlaveServerTests.cs
new file mode 100644
index 0000000..00590e5
--- /dev/null
+++ b/host/src/EdcHost.Tests/UnitTests/SlaveServers/SlaveServerTests.cs
@@ -0,0 +1,22 @@
+using EdcHost.SlaveServers;
+using Xunit;
+
+namespace EdcHost.Tests.UnitTests.SlaveServers;
+
+public class SlaveServerTests
+{
+ // [Fact]
+ // public void SlaveServer_WrongPlayerNum_ThrowsCorrectException()
+ // {
+ // string[] portNameList1 = new string[] { "COM1" };
+ // string[] portNameList2 = new string[] { "COM1", "COM2" };
+ // string[] portNameList3 = new string[] { "COM1", "COM2", "COM3" };
+ // int[] baudRateList1 = new int[] { 9600 };
+ // int[] baudRateList2 = new int[] { 9600, 9600 };
+ // int[] baudRateList3 = new int[] { 9600, 9600, 9600 };
+ // Assert.Throws(() => new SlaveServer(portNameList2, baudRateList1));
+ // Assert.Throws(() => new SlaveServer(portNameList2, baudRateList3));
+ // Assert.Throws(() => new SlaveServer(portNameList1, baudRateList2));
+ // Assert.Throws(() => new SlaveServer(portNameList3, baudRateList2));
+ // }
+}
diff --git a/host/src/EdcHost/CameraServers/Camera.cs b/host/src/EdcHost/CameraServers/Camera.cs
new file mode 100644
index 0000000..cc61c1f
--- /dev/null
+++ b/host/src/EdcHost/CameraServers/Camera.cs
@@ -0,0 +1,137 @@
+using System.Diagnostics;
+using Emgu.CV;
+using Emgu.CV.CvEnum;
+using Emgu.CV.Structure;
+
+namespace EdcHost.CameraServers;
+
+public class Camera : ICamera
+{
+ public int CameraIndex { get; private set; }
+ public int Height => _capture.Height;
+ public bool IsOpened => _capture.IsOpened;
+ public byte[]? JpegData { get; private set; }
+ public ILocator Locator { get; set; }
+ public Tuple? TargetLocation { get; private set; }
+ public Tuple? TargetLocationNotCalibrated { get; private set; }
+ public int Width => _capture.Width;
+
+ VideoCapture _capture;
+ Task? _task = null;
+ CancellationTokenSource? _taskCancellationTokenSource = null;
+
+ public Camera(int cameraIndex, ILocator locator)
+ {
+ CameraIndex = cameraIndex;
+
+ _capture = new(cameraIndex);
+ Locator = locator;
+
+ _taskCancellationTokenSource = new();
+ _task = Task.Run(TaskFunc);
+ }
+
+ public void Close()
+ {
+ if (!_capture.IsOpened)
+ {
+ throw new InvalidOperationException($"camera {CameraIndex} is not open");
+ }
+
+ Debug.Assert(_task is not null);
+ Debug.Assert(_taskCancellationTokenSource is not null);
+
+ _capture.Dispose();
+
+ _taskCancellationTokenSource.Cancel();
+ _task.Wait();
+ _taskCancellationTokenSource.Dispose();
+ _task.Dispose();
+
+ _task = null;
+ _taskCancellationTokenSource = null;
+ }
+
+ public void Dispose()
+ {
+ _capture.Dispose();
+ _task?.Dispose();
+
+ GC.SuppressFinalize(this);
+ }
+
+ public void Open()
+ {
+ if (_capture.IsOpened)
+ {
+ throw new InvalidOperationException($"camera {CameraIndex} is already open");
+ }
+
+ Debug.Assert(_task is null);
+ Debug.Assert(_taskCancellationTokenSource is null);
+
+ _capture = new(CameraIndex);
+
+ _taskCancellationTokenSource = new();
+ _task = Task.Run(TaskFunc);
+ }
+
+ public double GetProperty(CapProp property)
+ {
+ return _capture.Get(property);
+ }
+
+ public void SetProperty(CapProp property, double value)
+ {
+ _capture.Set(property, value);
+ }
+
+ void TaskFunc()
+ {
+ Debug.Assert(JpegData is null);
+ Debug.Assert(TargetLocation is null);
+ Debug.Assert(TargetLocationNotCalibrated is null);
+
+ while (!_taskCancellationTokenSource?.Token.IsCancellationRequested ?? false)
+ {
+ Mat frame = _capture.QueryFrame();
+
+ if (frame is null)
+ {
+ continue;
+ }
+
+ ILocator.RecognitionResult? recognitionResult = Locator.Locate(frame);
+
+ if (Locator.Mask is null)
+ {
+ var image = frame.ToImage();
+ JpegData = image.ToJpegData();
+ image.Dispose();
+ }
+ else
+ {
+ var image = Locator.Mask.ToImage();
+ JpegData = image.ToJpegData();
+ image.Dispose();
+ }
+
+ if (recognitionResult is null)
+ {
+ TargetLocation = null;
+ TargetLocationNotCalibrated = null;
+ }
+ else
+ {
+ TargetLocation = recognitionResult.CalibratedLocation;
+ TargetLocationNotCalibrated = recognitionResult.Location;
+ }
+
+ frame.Dispose();
+ }
+
+ JpegData = null;
+ TargetLocation = null;
+ TargetLocationNotCalibrated = null;
+ }
+}
diff --git a/host/src/EdcHost/CameraServers/CameraFactory.cs b/host/src/EdcHost/CameraServers/CameraFactory.cs
new file mode 100644
index 0000000..66767c0
--- /dev/null
+++ b/host/src/EdcHost/CameraServers/CameraFactory.cs
@@ -0,0 +1,62 @@
+using Emgu.CV;
+
+namespace EdcHost.CameraServers;
+
+public class CameraFactory : ICameraFactory
+{
+ public List CameraIndexes { get; } = new();
+
+ public CameraFactory()
+ {
+ Scan();
+ }
+
+ public ICamera Create(int cameraIndex, ILocator locator)
+ {
+ if (!CameraIndexes.Contains(cameraIndex))
+ {
+ throw new ArgumentException($"Camera index {cameraIndex} is not available");
+ }
+
+ return new Camera(cameraIndex, locator);
+ }
+
+ static bool IsCameraAvailable(int cameraIndex)
+ {
+ using VideoCapture capture = new(cameraIndex);
+
+ if (!capture.IsOpened)
+ {
+ return false;
+ }
+
+ using Mat frame = capture.QueryFrame();
+
+ if (frame?.IsEmpty ?? true)
+ {
+ return false;
+ }
+
+ return true;
+ }
+
+ public void Scan()
+ {
+ List cameraIndexes = new();
+ int index = 0;
+ while (true)
+ {
+ if (IsCameraAvailable(index))
+ {
+ cameraIndexes.Add(index);
+ ++index;
+ continue;
+ }
+
+ break;
+ }
+
+ CameraIndexes.Clear();
+ CameraIndexes.AddRange(cameraIndexes);
+ }
+}
diff --git a/host/src/EdcHost/CameraServers/CameraServer.cs b/host/src/EdcHost/CameraServers/CameraServer.cs
new file mode 100644
index 0000000..0ca7f16
--- /dev/null
+++ b/host/src/EdcHost/CameraServers/CameraServer.cs
@@ -0,0 +1,111 @@
+using System.Diagnostics;
+using Serilog;
+
+namespace EdcHost.CameraServers;
+
+public class CameraServer : ICameraServer
+{
+ readonly ICameraFactory _cameraFactory;
+ readonly List _cameras = new();
+ readonly ILogger _logger = Log.Logger.ForContext("Component", "CameraServers");
+
+ public List AvailableCameraIndexes => _cameraFactory.CameraIndexes;
+ public List OpenCameraIndexes => _cameras.Select(x => x.CameraIndex).ToList();
+ bool _isRunning = false;
+
+ public CameraServer(ICameraFactory cameraFactory)
+ {
+ _cameraFactory = cameraFactory;
+ }
+
+ public void CloseCamera(int cameraIndex)
+ {
+ if (_isRunning is false)
+ {
+ throw new InvalidOperationException("not running");
+ }
+
+ ICamera? camera = _cameras.Find(x => x.CameraIndex == cameraIndex) ??
+ throw new ArgumentException($"camera index does not exist: {cameraIndex}");
+
+ camera.Close();
+ camera.Dispose();
+ _cameras.Remove(camera);
+
+ _logger.Information("Camera {cameraIndex} opened.", cameraIndex);
+ }
+
+ public ICamera? GetCamera(int cameraIndex)
+ {
+ if (_isRunning is false)
+ {
+ throw new InvalidOperationException("not running");
+ }
+
+ ICamera? camera = _cameras.Find(x => x.CameraIndex == cameraIndex);
+
+ return camera;
+ }
+
+ public ICamera OpenCamera(int cameraIndex, ILocator locator)
+ {
+ if (_isRunning is false)
+ {
+ throw new InvalidOperationException("not running");
+ }
+
+ if (_cameras.Any(x => x.CameraIndex == cameraIndex))
+ {
+ ICamera? camera = _cameras.Find(x => x.CameraIndex == cameraIndex);
+ Debug.Assert(camera is not null);
+ return camera;
+ }
+ else
+ {
+ ICamera camera = _cameraFactory.Create(cameraIndex, locator);
+ _cameras.Add(camera);
+
+ _logger.Information("Camera {cameraIndex} opened.", cameraIndex);
+
+ return camera;
+ }
+ }
+
+ public void Start()
+ {
+ if (_isRunning is true)
+ {
+ throw new InvalidOperationException("already running");
+ }
+
+ _logger.Information("Starting...");
+
+ _isRunning = true;
+
+ _logger.Information("Started.");
+ }
+
+ public void Stop()
+ {
+ if (_isRunning is false)
+ {
+ throw new InvalidOperationException("not running");
+ }
+
+ _logger.Information("Stopping...");
+
+ _isRunning = false;
+
+ _logger.Information("Stopped.");
+ }
+
+ public void Dispose()
+ {
+ foreach (ICamera camera in _cameras)
+ {
+ camera.Dispose();
+ }
+
+ GC.SuppressFinalize(this);
+ }
+}
diff --git a/host/src/EdcHost/CameraServers/ICamera.cs b/host/src/EdcHost/CameraServers/ICamera.cs
new file mode 100644
index 0000000..68d0959
--- /dev/null
+++ b/host/src/EdcHost/CameraServers/ICamera.cs
@@ -0,0 +1,20 @@
+using Emgu.CV.CvEnum;
+
+namespace EdcHost.CameraServers;
+
+public interface ICamera : IDisposable
+{
+ int CameraIndex { get; }
+ int Height { get; }
+ bool IsOpened { get; }
+ byte[]? JpegData { get; }
+ ILocator Locator { get; set; }
+ int Width { get; }
+ Tuple? TargetLocation { get; }
+ Tuple? TargetLocationNotCalibrated { get; }
+
+ void Close();
+ void Open();
+ double GetProperty(CapProp property);
+ void SetProperty(CapProp property, double value);
+}
diff --git a/host/src/EdcHost/CameraServers/ICameraFactory.cs b/host/src/EdcHost/CameraServers/ICameraFactory.cs
new file mode 100644
index 0000000..0dd4902
--- /dev/null
+++ b/host/src/EdcHost/CameraServers/ICameraFactory.cs
@@ -0,0 +1,10 @@
+namespace EdcHost.CameraServers;
+
+public interface ICameraFactory
+{
+ List CameraIndexes { get; }
+
+ ICamera Create(int cameraIndex, ILocator locator);
+
+ void Scan();
+}
diff --git a/host/src/EdcHost/CameraServers/ICameraServer.cs b/host/src/EdcHost/CameraServers/ICameraServer.cs
new file mode 100644
index 0000000..c26e2ba
--- /dev/null
+++ b/host/src/EdcHost/CameraServers/ICameraServer.cs
@@ -0,0 +1,23 @@
+namespace EdcHost.CameraServers;
+
+public interface ICameraServer : IDisposable
+{
+ static ICameraServer Create()
+ {
+ return new CameraServer(new CameraFactory());
+ }
+
+ List AvailableCameraIndexes { get; }
+
+ List OpenCameraIndexes { get; }
+
+ void CloseCamera(int cameraIndex);
+
+ ICamera? GetCamera(int cameraIndex);
+
+ ICamera OpenCamera(int cameraIndex, ILocator locator);
+
+ void Start();
+
+ void Stop();
+}
diff --git a/host/src/EdcHost/CameraServers/ILocator.cs b/host/src/EdcHost/CameraServers/ILocator.cs
new file mode 100644
index 0000000..1584455
--- /dev/null
+++ b/host/src/EdcHost/CameraServers/ILocator.cs
@@ -0,0 +1,26 @@
+using Emgu.CV;
+
+namespace EdcHost.CameraServers;
+
+public interface ILocator
+{
+ record RecognitionResult
+ {
+ public Tuple CalibratedLocation { get; init; } = null!;
+ public Tuple Location { get; init; } = null!;
+ }
+
+ Mat? Mask { get; }
+
+ RecognitionOptions Options { get; set; }
+
+ ///
+ /// Locates the target in the given frame.
+ ///
+ /// The frame to locate the target in.
+ ///
+ /// The location of the target in the frame, or null if the target could
+ /// not be located.
+ ///
+ RecognitionResult? Locate(Mat frame);
+}
diff --git a/host/src/EdcHost/CameraServers/Locator.cs b/host/src/EdcHost/CameraServers/Locator.cs
new file mode 100644
index 0000000..931b7d9
--- /dev/null
+++ b/host/src/EdcHost/CameraServers/Locator.cs
@@ -0,0 +1,163 @@
+using System.Diagnostics;
+using System.Drawing;
+using Emgu.CV;
+using Emgu.CV.CvEnum;
+using Emgu.CV.Structure;
+using Emgu.CV.Util;
+
+namespace EdcHost.CameraServers;
+
+public class Locator : ILocator
+{
+ public Mat? Mask { get; private set; } = null;
+
+ public RecognitionOptions Options { get; set; }
+
+ public Locator(RecognitionOptions? options = null)
+ {
+ Options = options ?? new RecognitionOptions();
+ }
+
+ public ILocator.RecognitionResult? Locate(Mat originalFrame)
+ {
+ using Mat mask = GetMask(originalFrame);
+
+ // Show mask if requested.
+ if (Options.ShowMask)
+ {
+ Mask?.Dispose();
+ Mask = mask.Clone();
+ }
+ else
+ {
+ Mask?.Dispose();
+ Mask = null;
+ }
+
+ Tuple? location = GetLocation(mask);
+
+ if (location is null)
+ {
+ return null;
+ }
+
+ Tuple calibratedLocation = GetCalibratedLocation(location);
+
+ return new ILocator.RecognitionResult
+ {
+ CalibratedLocation = calibratedLocation,
+ Location = location,
+ };
+ }
+
+ Tuple GetCalibratedLocation(Tuple pixelLocation)
+ {
+ using Mat transform = CvInvoke.GetPerspectiveTransform(
+ src: new PointF[] {
+ new(Options.TopLeftX, Options.TopLeftY),
+ new(Options.TopRightX, Options.TopRightY),
+ new(Options.BottomRightX, Options.BottomRightY),
+ new(Options.BottomLeftX, Options.BottomLeftY),
+ },
+ dest: new PointF[] {
+ new(0, 0),
+ new(1, 0),
+ new(1, 1),
+ new(0, 1),
+ }
+ );
+
+ PointF[] transformed = CvInvoke.PerspectiveTransform(
+ src: new PointF[] { new(pixelLocation.Item1, pixelLocation.Item2) },
+ mat: transform
+ );
+
+ Debug.Assert(transformed.Length == 1);
+
+ return new Tuple(
+ transformed[0].X,
+ transformed[0].Y
+ );
+ }
+
+ Mat GetMask(Mat frame)
+ {
+ Mat mask = frame.Clone();
+
+ // Convert to HSV color space.
+ CvInvoke.CvtColor(
+ src: mask,
+ dst: mask,
+ code: ColorConversion.Bgr2Hsv
+ );
+
+ // Binarize the image.
+ CvInvoke.InRange(
+ src: mask,
+ lower: new ScalarArray(new MCvScalar(
+ Options.HueCenter - Options.HueRange / 2,
+ Options.SaturationCenter - Options.SaturationRange / 2,
+ Options.ValueCenter - Options.ValueRange / 2
+ )),
+ upper: new ScalarArray(new MCvScalar(
+ Options.HueCenter + Options.HueRange / 2,
+ Options.SaturationCenter + Options.SaturationRange / 2,
+ Options.ValueCenter + Options.ValueRange / 2
+ )),
+ dst: mask
+ );
+
+ return mask;
+ }
+
+ Tuple? GetLocation(Mat mask)
+ {
+ // Find contours.
+ using VectorOfVectorOfPoint contours = new();
+ CvInvoke.FindContours(
+ image: mask,
+ contours: contours,
+ hierarchy: null,
+ mode: RetrType.List,
+ method: ChainApproxMethod.ChainApproxSimple
+ );
+
+ // Find the largest contour.
+ int? largestContourIndex = null;
+ double largestContourArea = 0;
+ for (int i = 0; i < contours.Size; i++)
+ {
+ double area = CvInvoke.ContourArea(contours[i]);
+ if (area > largestContourArea)
+ {
+ largestContourIndex = i;
+ largestContourArea = area;
+ }
+ }
+
+ // Return null if no contours were found.
+ if (largestContourIndex is null)
+ {
+ return null;
+ }
+
+ // Return null if no area is large enough.
+ if (largestContourArea / (mask.Height * mask.Width) < Options.MinArea)
+ {
+ return null;
+ }
+
+ // Find the center of the largest contour.
+ using VectorOfPoint largestContour = contours[largestContourIndex.Value];
+ using Moments moments = CvInvoke.Moments(largestContour);
+ float centerX = (float)(moments.M10 / moments.M00);
+ float centerY = (float)(moments.M01 / moments.M00);
+
+ Tuple location = new(
+ centerX,
+ centerY
+ );
+
+ return location;
+ }
+}
diff --git a/host/src/EdcHost/CameraServers/RecognitionOptions.cs b/host/src/EdcHost/CameraServers/RecognitionOptions.cs
new file mode 100644
index 0000000..b571dd5
--- /dev/null
+++ b/host/src/EdcHost/CameraServers/RecognitionOptions.cs
@@ -0,0 +1,22 @@
+namespace EdcHost.CameraServers;
+
+public record RecognitionOptions
+{
+ public bool Calibrate = false;
+ public float TopLeftX;
+ public float TopLeftY;
+ public float TopRightX;
+ public float TopRightY;
+ public float BottomLeftX;
+ public float BottomLeftY;
+ public float BottomRightX;
+ public float BottomRightY;
+ public float HueCenter;
+ public float HueRange;
+ public float SaturationCenter;
+ public float SaturationRange;
+ public float ValueCenter;
+ public float ValueRange;
+ public float MinArea;
+ public bool ShowMask;
+}
diff --git a/host/src/EdcHost/Config.cs b/host/src/EdcHost/Config.cs
new file mode 100644
index 0000000..8607391
--- /dev/null
+++ b/host/src/EdcHost/Config.cs
@@ -0,0 +1,27 @@
+using System.Text.Json.Serialization;
+
+namespace EdcHost;
+
+public record Config
+{
+ public record GameType
+ {
+ [JsonPropertyName("diamondMines")]
+ public List> DiamondMines { get; init; } = new();
+
+ [JsonPropertyName("goldMines")]
+ public List> GoldMines { get; init; } = new();
+
+ [JsonPropertyName("ironMines")]
+ public List> IronMines { get; init; } = new();
+ }
+
+ [JsonPropertyName("loggingLevel")]
+ public string LoggingLevel { get; init; } = "Information";
+
+ [JsonPropertyName("serverPort")]
+ public int ServerPort { get; init; } = 8080;
+
+ [JsonPropertyName("game")]
+ public GameType Game { get; init; } = new();
+}
diff --git a/host/src/EdcHost/EdcHost.GameEventHandlers.cs b/host/src/EdcHost/EdcHost.GameEventHandlers.cs
new file mode 100644
index 0000000..4e9b6f4
--- /dev/null
+++ b/host/src/EdcHost/EdcHost.GameEventHandlers.cs
@@ -0,0 +1,33 @@
+namespace EdcHost;
+
+partial class EdcHost : IEdcHost
+{
+ void HandleAfterJudgementEvent(object? sender, Games.AfterJudgementEventArgs e)
+ {
+ if (e.Winner is null)
+ {
+ _logger.Information("No winner.");
+ }
+ else
+ {
+ _logger.Information($"Winner is {e.Winner?.PlayerId}");
+ }
+
+ _gameRunner.End();
+ }
+ void HandlePlayerDigEvent(object? sender, Games.PlayerDigEventArgs e)
+ {
+ // Store the event info to the queue
+ _playerEventQueue.Enqueue(e);
+ }
+ void HandlePlayerAttackEvent(object? sender, Games.PlayerAttackEventArgs e)
+ {
+ // Store the event info to the queue
+ _playerEventQueue.Enqueue(e);
+ }
+ void HandlePlayerPlaceEvent(object? sender, Games.PlayerPlaceEventArgs e)
+ {
+ // Store the event info to the queue
+ _playerEventQueue.Enqueue(e);
+ }
+}
diff --git a/host/src/EdcHost/EdcHost.SlaveServerEventHandlers.cs b/host/src/EdcHost/EdcHost.SlaveServerEventHandlers.cs
new file mode 100644
index 0000000..7a695df
--- /dev/null
+++ b/host/src/EdcHost/EdcHost.SlaveServerEventHandlers.cs
@@ -0,0 +1,121 @@
+using EdcHost.Games;
+using EdcHost.SlaveServers;
+
+namespace EdcHost;
+
+partial class EdcHost : IEdcHost
+{
+ void HandlePlayerTryAttackEvent(object? sender, PlayerTryAttackEventArgs e)
+ {
+ try
+ {
+ // Store the event info to the queue
+ _playerEventQueue.Enqueue(e);
+
+ string portName = e.PortName;
+
+ int? playerId = _playerHardwareInfo
+ .Where(kvp => kvp.Value.PortName == portName)
+ .Select(kvp => (int?)kvp.Key)
+ .FirstOrDefault((int?)null);
+
+ if (playerId is null)
+ {
+ return;
+ }
+
+ IPosition current = _game.Players[playerId.Value].PlayerPosition;
+ _game.Players[playerId.Value].Attack(e.TargetChunkId % MapWidth, e.TargetChunkId / MapWidth);
+
+ _logger.Information($"Player {playerId} attempted to attack ({e.TargetChunkId % MapWidth}, {e.TargetChunkId / MapWidth})");
+ }
+ catch (Exception ex)
+ {
+ _logger.Error($"PlayerTryAttack failed: {ex.Message}");
+ }
+ }
+
+ void HandlePlayerTryPlaceBlockEvent(object? sender, PlayerTryPlaceBlockEventArgs e)
+ {
+ try
+ {
+ // Store the event info to the queue
+ _playerEventQueue.Enqueue(e);
+
+ string portName = e.PortName;
+
+ int? playerId = _playerHardwareInfo
+ .Where(kvp => kvp.Value.PortName == portName)
+ .Select(kvp => (int?)kvp.Key)
+ .FirstOrDefault((int?)null);
+
+ if (playerId is null)
+ {
+ return;
+ }
+
+ IPosition current = _game.Players[playerId.Value].PlayerPosition;
+ _game.Players[playerId.Value].Place(e.TargetChunkId % MapWidth, e.TargetChunkId / MapWidth);
+
+ _logger.Information($"Player {playerId} attempted to place a block at ({e.TargetChunkId % MapWidth}, {e.TargetChunkId / MapWidth})");
+ }
+ catch (Exception ex)
+ {
+ _logger.Error($"PlayerTryPlaceBlock failed: {ex.Message}");
+ }
+ }
+
+ void HandlePlayerTryTradeEvent(object? sender, PlayerTryTradeEventArgs e)
+ {
+ try
+ {
+ // Store the event info to the queue
+ _playerEventQueue.Enqueue(e);
+
+ string portName = e.PortName;
+
+ int? playerId = _playerHardwareInfo
+ .Where(kvp => kvp.Value.PortName == portName)
+ .Select(kvp => (int?)kvp.Key)
+ .FirstOrDefault((int?)null);
+
+ if (playerId is null)
+ {
+ return;
+ }
+
+ switch ((ItemKind)e.Item)
+ {
+ case ItemKind.AgilityBoost:
+ _game.Players[playerId.Value].SendTradeRequest(IPlayer.CommodityKindType.AgilityBoost);
+ break;
+
+ case ItemKind.HealthBoost:
+ _game.Players[playerId.Value].SendTradeRequest(IPlayer.CommodityKindType.HealthBoost);
+ break;
+
+ case ItemKind.StrengthBoost:
+ _game.Players[playerId.Value].SendTradeRequest(IPlayer.CommodityKindType.StrengthBoost);
+ break;
+
+ case ItemKind.Wool:
+ _game.Players[playerId.Value].SendTradeRequest(IPlayer.CommodityKindType.Wool);
+ break;
+
+ case ItemKind.PotionOfHealing:
+ _game.Players[playerId.Value].SendTradeRequest(IPlayer.CommodityKindType.HealthPotion);
+ break;
+
+ default:
+ _logger.Error($"No item with id {e.Item}. PlayerTryTrade rejected."); // Do not throw exception here.
+ break;
+ }
+
+ _logger.Information($"Player {playerId} attempted to buy a item of {(ItemKind)e.Item}");
+ }
+ catch (Exception ex)
+ {
+ _logger.Error($"PlayerTryTrade failed: {ex.Message}");
+ }
+ }
+}
diff --git a/host/src/EdcHost/EdcHost.ViewerServerEventHandlers.cs b/host/src/EdcHost/EdcHost.ViewerServerEventHandlers.cs
new file mode 100644
index 0000000..a201531
--- /dev/null
+++ b/host/src/EdcHost/EdcHost.ViewerServerEventHandlers.cs
@@ -0,0 +1,444 @@
+using System.Diagnostics;
+using Emgu.CV.CvEnum;
+
+namespace EdcHost;
+
+partial class EdcHost : IEdcHost
+{
+ void HandleAfterMessageReceiveEvent(object? sender, ViewerServers.AfterMessageReceiveEventArgs e)
+ {
+ switch (e.Message)
+ {
+ case ViewerServers.CompetitionControlCommandMessage message:
+ switch (message.Command)
+ {
+ case "START":
+ HandleStartGame();
+ break;
+
+ case "END":
+ HandleEndGame();
+ break;
+
+ case "RESET":
+ HandleResetGame();
+ break;
+
+ case "GET_HOST_CONFIGURATION":
+ HandleGetHostConfiguration();
+ break;
+ default:
+ _logger.Error($"Invalid command: {message.Command}.");
+ break;
+ }
+ break;
+
+ case ViewerServers.HostConfigurationFromClientMessage message:
+ HandleUpdateConfiguration(message);
+ break;
+
+ default:
+ _logger.Error($"Invalid message type: {e.Message.MessageType}.");
+ break;
+ }
+ }
+
+ void HandleStartGame()
+ {
+ try
+ {
+ _gameRunner.Start();
+ }
+ catch (Exception e)
+ {
+ _logger.Error($"Failed to start game: {e}");
+ _viewerServer.Publish(new ViewerServers.ErrorMessage()
+ {
+ Message = e.Message
+ });
+ }
+ }
+
+ void HandleEndGame()
+ {
+ try
+ {
+ _gameRunner.End();
+ }
+ catch (Exception e)
+ {
+ _logger.Error($"Failed to end game: {e}");
+ _viewerServer.Publish(new ViewerServers.ErrorMessage()
+ {
+ Message = e.Message
+ });
+ }
+ }
+
+ void HandleResetGame()
+ {
+ try
+ {
+ _logger.Information("Reloading config...");
+ Config newConfig = ReLoadConfig();
+
+ _logger.Information("Resetting Game...");
+ if (_gameRunner.IsRunning)
+ {
+ _logger.Information("Game is running, Stopping.");
+ _gameRunner.End();
+ }
+
+ _game = Games.IGame.Create(
+ diamondMines: newConfig.Game.DiamondMines,
+ goldMines: newConfig.Game.GoldMines,
+ ironMines: newConfig.Game.IronMines
+ );
+ _gameRunner = Games.IGameRunner.Create(_game);
+
+ _game.AfterJudgementEvent += HandleAfterJudgementEvent;
+
+ for (int i = 0; i < _game.Players.Count; i++)
+ {
+ _game.Players[i].OnAttack += HandlePlayerAttackEvent;
+ _game.Players[i].OnPlace += HandlePlayerPlaceEvent;
+ _game.Players[i].OnDig += HandlePlayerDigEvent;
+ }
+ _logger.Information("Done.");
+ }
+ catch (Exception e)
+ {
+ _logger.Error($"Failed to reset game: {e}");
+ _viewerServer.Publish(new ViewerServers.ErrorMessage()
+ {
+ Message = e.Message
+ });
+ }
+ }
+
+ void HandleGetHostConfiguration()
+ {
+ try
+ {
+ ViewerServers.HostConfigurationFromServerMessage configMessage = new()
+ {
+ AvailableCameras = _cameraServer.AvailableCameraIndexes,
+ AvailableSerialPorts = _slaveServer.AvailablePortNames,
+ Configuration = new()
+ {
+ Cameras = _cameraServer.OpenCameraIndexes.Select((cameraIndex) =>
+ {
+ CameraServers.ICamera? cameraOrNull = _cameraServer.GetCamera(cameraIndex);
+ Debug.Assert(cameraOrNull != null);
+
+ CameraServers.ICamera camera = cameraOrNull!;
+
+ return new ViewerServers.HostConfiguration.CameraType()
+ {
+ CameraId = cameraIndex,
+
+ Calibration = camera.Locator.Options.Calibrate == false ? null : new()
+ {
+ TopLeft = new ViewerServers.HostConfiguration.CameraType.CalibrationType.Point()
+ {
+ X = camera.Locator.Options.TopLeftX,
+ Y = camera.Locator.Options.TopLeftY
+ },
+ TopRight = new ViewerServers.HostConfiguration.CameraType.CalibrationType.Point()
+ {
+ X = camera.Locator.Options.TopRightX,
+ Y = camera.Locator.Options.TopRightY
+ },
+ BottomLeft = new ViewerServers.HostConfiguration.CameraType.CalibrationType.Point()
+ {
+ X = camera.Locator.Options.BottomLeftX,
+ Y = camera.Locator.Options.BottomLeftY
+ },
+ BottomRight = new ViewerServers.HostConfiguration.CameraType.CalibrationType.Point()
+ {
+ X = camera.Locator.Options.BottomRightX,
+ Y = camera.Locator.Options.BottomRightY
+ }
+ },
+
+ Properties = new ViewerServers.HostConfiguration.CameraType.PropertiesType()
+ {
+ FrameWidth = camera.GetProperty(CapProp.FrameWidth),
+ FrameHeight = camera.GetProperty(CapProp.FrameHeight),
+ Fps = camera.GetProperty(CapProp.Fps),
+ Brightness = camera.GetProperty(CapProp.Brightness),
+ Contrast = camera.GetProperty(CapProp.Contrast),
+ Saturation = camera.GetProperty(CapProp.Saturation),
+ Hue = camera.GetProperty(CapProp.Hue),
+ Gain = camera.GetProperty(CapProp.Gain),
+ Exposure = camera.GetProperty(CapProp.Exposure),
+ Monochrome = camera.GetProperty(CapProp.Monochrome),
+ Sharpness = camera.GetProperty(CapProp.Sharpness),
+ AutoExposure = camera.GetProperty(CapProp.AutoExposure),
+ Gamma = camera.GetProperty(CapProp.Gamma),
+ Temperature = camera.GetProperty(CapProp.Temperature),
+ WhiteBalanceRedV = camera.GetProperty(CapProp.WhiteBalanceRedV),
+ Zoom = camera.GetProperty(CapProp.Zoom),
+ Focus = camera.GetProperty(CapProp.Focus),
+ IsoSpeed = camera.GetProperty(CapProp.IsoSpeed),
+ Iris = camera.GetProperty(CapProp.Iris),
+ Autofocus = camera.GetProperty(CapProp.Autofocus),
+ AutoWb = camera.GetProperty(CapProp.AutoWb),
+ WbTemperature = camera.GetProperty(CapProp.WbTemperature),
+ },
+
+ Recognition = new ViewerServers.HostConfiguration.CameraType.RecognitionType()
+ {
+ HueCenter = camera.Locator.Options.HueCenter,
+ HueRange = camera.Locator.Options.HueRange,
+ SaturationCenter = camera.Locator.Options.SaturationCenter,
+ SaturationRange = camera.Locator.Options.SaturationRange,
+ ValueCenter = camera.Locator.Options.ValueCenter,
+ ValueRange = camera.Locator.Options.ValueRange,
+ MinArea = camera.Locator.Options.MinArea,
+ ShowMask = camera.Locator.Options.ShowMask
+ },
+ };
+ }).ToList(),
+
+ Players = _playerHardwareInfo.Select((kv) =>
+ {
+ int playerIndex = kv.Key;
+ PlayerHardwareInfo playerHardwareInfo = kv.Value;
+
+ return new ViewerServers.HostConfiguration.PlayerType()
+ {
+ PlayerId = playerIndex,
+ Camera = playerHardwareInfo.CameraIndex,
+ SerialPort = playerHardwareInfo.PortName
+ };
+ }).ToList(),
+
+ SerialPorts = _slaveServer.OpenPortNames.Select((portName) =>
+ {
+ SlaveServers.ISlaveServer.PortInfo? portInfoOrNull = _slaveServer.GetPortInfo(portName);
+ Debug.Assert(portInfoOrNull != null);
+ SlaveServers.ISlaveServer.PortInfo portInfo = portInfoOrNull!;
+
+ return new ViewerServers.HostConfiguration.SerialPortType()
+ {
+ PortName = portName,
+ BaudRate = portInfo.BaudRate
+ };
+ }).ToList(),
+ },
+ };
+
+ _viewerServer.Publish(configMessage);
+ }
+ catch (Exception e)
+ {
+ _logger.Error($"Failed to get host configuration: {e}");
+ _viewerServer.Publish(new ViewerServers.ErrorMessage()
+ {
+ Message = e.Message
+ });
+ }
+ }
+
+ void HandleUpdateConfiguration(ViewerServers.HostConfigurationFromClientMessage message)
+ {
+ try
+ {
+ foreach (ViewerServers.HostConfiguration.CameraType camera in message.Configuration.Cameras)
+ {
+ if (!_cameraServer.OpenCameraIndexes.Contains(camera.CameraId))
+ {
+ _logger.Information($"Opening camera {camera.CameraId}...");
+ _cameraServer.OpenCamera(camera.CameraId, new CameraServers.Locator());
+ }
+
+ CameraServers.ICamera? cameraOrNull = _cameraServer.GetCamera(camera.CameraId);
+ Debug.Assert(cameraOrNull != null);
+ CameraServers.ICamera cameraInstance = cameraOrNull!;
+
+ CameraServers.RecognitionOptions recognitionOptions = cameraInstance.Locator.Options;
+
+ if (camera.Recognition is not null)
+ {
+ recognitionOptions.HueCenter = camera.Recognition.HueCenter;
+ recognitionOptions.HueRange = camera.Recognition.HueRange;
+ recognitionOptions.SaturationCenter = camera.Recognition.SaturationCenter;
+ recognitionOptions.SaturationRange = camera.Recognition.SaturationRange;
+ recognitionOptions.ValueCenter = camera.Recognition.ValueCenter;
+ recognitionOptions.ValueRange = camera.Recognition.ValueRange;
+ recognitionOptions.MinArea = camera.Recognition.MinArea;
+ recognitionOptions.ShowMask = camera.Recognition.ShowMask;
+ }
+
+ if (camera.Calibration is not null)
+ {
+ recognitionOptions.Calibrate = true;
+
+ recognitionOptions.TopLeftX = camera.Calibration.TopLeft.X;
+ recognitionOptions.TopLeftY = camera.Calibration.TopLeft.Y;
+ recognitionOptions.TopRightX = camera.Calibration.TopRight.X;
+ recognitionOptions.TopRightY = camera.Calibration.TopRight.Y;
+ recognitionOptions.BottomLeftX = camera.Calibration.BottomLeft.X;
+ recognitionOptions.BottomLeftY = camera.Calibration.BottomLeft.Y;
+ recognitionOptions.BottomRightX = camera.Calibration.BottomRight.X;
+ recognitionOptions.BottomRightY = camera.Calibration.BottomRight.Y;
+ }
+
+ if (camera.Properties is not null)
+ {
+ if (camera.Properties.FrameWidth is not null)
+ {
+ cameraInstance.SetProperty(CapProp.FrameWidth, camera.Properties.FrameWidth.Value);
+ }
+ if (camera.Properties.FrameHeight is not null)
+ {
+ cameraInstance.SetProperty(CapProp.FrameHeight, camera.Properties.FrameHeight.Value);
+ }
+ if (camera.Properties.Fps is not null)
+ {
+ cameraInstance.SetProperty(CapProp.Fps, camera.Properties.Fps.Value);
+ }
+ if (camera.Properties.Brightness is not null)
+ {
+ cameraInstance.SetProperty(CapProp.Brightness, camera.Properties.Brightness.Value);
+ }
+ if (camera.Properties.Contrast is not null)
+ {
+ cameraInstance.SetProperty(CapProp.Contrast, camera.Properties.Contrast.Value);
+ }
+ if (camera.Properties.Saturation is not null)
+ {
+ cameraInstance.SetProperty(CapProp.Saturation, camera.Properties.Saturation.Value);
+ }
+ if (camera.Properties.Hue is not null)
+ {
+ cameraInstance.SetProperty(CapProp.Hue, camera.Properties.Hue.Value);
+ }
+ if (camera.Properties.Gain is not null)
+ {
+ cameraInstance.SetProperty(CapProp.Gain, camera.Properties.Gain.Value);
+ }
+ if (camera.Properties.Exposure is not null)
+ {
+ cameraInstance.SetProperty(CapProp.Exposure, camera.Properties.Exposure.Value);
+ }
+ if (camera.Properties.Monochrome is not null)
+ {
+ cameraInstance.SetProperty(CapProp.Monochrome, camera.Properties.Monochrome.Value);
+ }
+ if (camera.Properties.Sharpness is not null)
+ {
+ cameraInstance.SetProperty(CapProp.Sharpness, camera.Properties.Sharpness.Value);
+ }
+ if (camera.Properties.AutoExposure is not null)
+ {
+ cameraInstance.SetProperty(CapProp.AutoExposure, camera.Properties.AutoExposure.Value);
+ }
+ if (camera.Properties.Gamma is not null)
+ {
+ cameraInstance.SetProperty(CapProp.Gamma, camera.Properties.Gamma.Value);
+ }
+ if (camera.Properties.Temperature is not null)
+ {
+ cameraInstance.SetProperty(CapProp.Temperature, camera.Properties.Temperature.Value);
+ }
+ if (camera.Properties.WhiteBalanceRedV is not null)
+ {
+ cameraInstance.SetProperty(CapProp.WhiteBalanceRedV, camera.Properties.WhiteBalanceRedV.Value);
+ }
+ if (camera.Properties.Zoom is not null)
+ {
+ cameraInstance.SetProperty(CapProp.Zoom, camera.Properties.Zoom.Value);
+ }
+ if (camera.Properties.Focus is not null)
+ {
+ cameraInstance.SetProperty(CapProp.Focus, camera.Properties.Focus.Value);
+ }
+ if (camera.Properties.IsoSpeed is not null)
+ {
+ cameraInstance.SetProperty(CapProp.IsoSpeed, camera.Properties.IsoSpeed.Value);
+ }
+ if (camera.Properties.Iris is not null)
+ {
+ cameraInstance.SetProperty(CapProp.Iris, camera.Properties.Iris.Value);
+ }
+ if (camera.Properties.Autofocus is not null)
+ {
+ cameraInstance.SetProperty(CapProp.Autofocus, camera.Properties.Autofocus.Value);
+ }
+ if (camera.Properties.AutoWb is not null)
+ {
+ cameraInstance.SetProperty(CapProp.AutoWb, camera.Properties.AutoWb.Value);
+ }
+ if (camera.Properties.WbTemperature is not null)
+ {
+ cameraInstance.SetProperty(CapProp.WbTemperature, camera.Properties.WbTemperature.Value);
+ }
+ }
+ }
+
+ foreach (KeyValuePair kvp in _playerHardwareInfo)
+ {
+ _playerHardwareInfo.AddOrUpdate(
+ kvp.Key,
+ new PlayerHardwareInfo()
+ {
+ CameraIndex = kvp.Value.CameraIndex,
+ PortName = null
+ },
+ (_, _) => new PlayerHardwareInfo()
+ {
+ CameraIndex = kvp.Value.CameraIndex,
+ PortName = null
+ }
+ );
+ }
+
+ foreach (string port in _slaveServer.OpenPortNames)
+ {
+ try
+ {
+ _slaveServer.ClosePort(port);
+ }
+ catch (Exception ex)
+ {
+ _logger.Error($"Failed to close port {port}: {ex}");
+ }
+ }
+
+ foreach (ViewerServers.HostConfiguration.SerialPortType serialPort in message.Configuration.SerialPorts)
+ {
+ ///
+ /// When the hardware disconnets, serial port is closed but not removed from OpenSerialPorts.
+ /// Therefore, we are not going to check whether a serial port is in OpenSerialPorts.
+ /// Instead, we will try to open a serial port which throws exception if failed.
+ ///
+ _slaveServer.OpenPort(serialPort.PortName, serialPort.BaudRate);
+ }
+
+ foreach (ViewerServers.HostConfiguration.PlayerType player in message.Configuration.Players)
+ {
+ // Do not need to check if a player exists because we do not care.
+
+ PlayerHardwareInfo playerHardwareInfo = new()
+ {
+ CameraIndex = player.Camera,
+ PortName = player.SerialPort
+ };
+
+ _logger.Information($"Setting playerHardwareInfo of player {player.PlayerId}:");
+ _logger.Information($"Camera: {playerHardwareInfo.CameraIndex}");
+ _logger.Information($"Serial port: {playerHardwareInfo.PortName}");
+
+ _playerHardwareInfo.AddOrUpdate(player.PlayerId, playerHardwareInfo, (_, _) => playerHardwareInfo);
+ }
+ }
+ catch (Exception e)
+ {
+ _logger.Error("Error updating configuration: {0}", e.Message);
+ _viewerServer.Publish(new ViewerServers.ErrorMessage());
+ }
+ }
+
+}
diff --git a/host/src/EdcHost/EdcHost.cs b/host/src/EdcHost/EdcHost.cs
new file mode 100644
index 0000000..b368a99
--- /dev/null
+++ b/host/src/EdcHost/EdcHost.cs
@@ -0,0 +1,461 @@
+using System.Collections.Concurrent;
+using System.Diagnostics;
+using System.Text.Json;
+using Serilog;
+
+namespace EdcHost;
+
+partial class EdcHost : IEdcHost
+{
+ const int FrequencyOfReadingCamera = 60;
+ const int FrequencyOfSendingToSlave = 20;
+ const int FrequencyOfSendingToViewer = 60;
+ const int MapHeight = 8;
+ const int MapWidth = 8;
+
+ readonly ILogger _logger = Log.ForContext("Component", "EdcHost");
+ readonly ConcurrentQueue _playerEventQueue = new();
+ // Note: this info does not ensure that the player is connected.
+ readonly ConcurrentDictionary _playerHardwareInfo = new();
+ readonly CameraServers.ICameraServer _cameraServer;
+ readonly SlaveServers.ISlaveServer _slaveServer;
+ readonly ViewerServers.IViewerServer _viewerServer;
+ readonly Config _config;
+
+ public bool IsRunning { get; private set; } = false;
+
+ Games.IGame _game;
+ Games.IGameRunner _gameRunner;
+ CancellationTokenSource? _taskCancellationTokenSource = null;
+ Task? _taskForReadingCamera = null;
+ Task? _taskForSendingToSlave = null;
+ Task? _taskForSendingToViewer = null;
+
+ public EdcHost(Config config)
+ {
+ _config = config;
+
+ _game = Games.IGame.Create(
+ diamondMines: _config.Game.DiamondMines,
+ goldMines: _config.Game.GoldMines,
+ ironMines: _config.Game.IronMines
+ );
+ _gameRunner = Games.IGameRunner.Create(_game);
+ _cameraServer = CameraServers.ICameraServer.Create();
+ _slaveServer = SlaveServers.ISlaveServer.Create();
+
+ _viewerServer = ViewerServers.IViewerServer.Create(_config.ServerPort);
+
+ _game.AfterJudgementEvent += HandleAfterJudgementEvent;
+
+ for (int i = 0; i < _game.Players.Count; i++)
+ {
+ _game.Players[i].OnAttack += HandlePlayerAttackEvent;
+ _game.Players[i].OnPlace += HandlePlayerPlaceEvent;
+ _game.Players[i].OnDig += HandlePlayerDigEvent;
+ }
+
+ _slaveServer.PlayerTryAttackEvent += HandlePlayerTryAttackEvent;
+ _slaveServer.PlayerTryTradeEvent += HandlePlayerTryTradeEvent;
+ _slaveServer.PlayerTryPlaceBlockEvent += HandlePlayerTryPlaceBlockEvent;
+
+ _viewerServer.AfterMessageReceiveEvent += HandleAfterMessageReceiveEvent;
+
+ _game.Players.ForEach(player => _playerHardwareInfo.GetOrAdd(player.PlayerId, new PlayerHardwareInfo()));
+ }
+
+ public void Start()
+ {
+
+ _logger.Information("Starting...");
+
+ Debug.Assert(_taskCancellationTokenSource is null);
+ Debug.Assert(_taskForReadingCamera is null);
+ Debug.Assert(_taskForSendingToSlave is null);
+ Debug.Assert(_taskForSendingToViewer is null);
+
+ try
+ {
+ _cameraServer.Start();
+ _slaveServer.Start();
+ _viewerServer.Start();
+
+ _taskCancellationTokenSource = new CancellationTokenSource();
+ _taskForReadingCamera = Task.Run(TaskForReadingCameraFunc);
+ _taskForSendingToSlave = Task.Run(TaskForSendingToSlaveFunc);
+ _taskForSendingToViewer = Task.Run(TaskForSendingToViewerFunc);
+
+ IsRunning = true;
+
+ _logger.Information("Started.");
+ }
+ catch (Exception ex)
+ {
+ _logger.Fatal($"An unhandled exception is caught when starting EdcHost: {ex}");
+ }
+
+ }
+
+ public void Stop()
+ {
+ _logger.Information("Stopping...");
+
+ Debug.Assert(_taskCancellationTokenSource is not null);
+ Debug.Assert(_taskForReadingCamera is not null);
+ Debug.Assert(_taskForSendingToSlave is not null);
+ Debug.Assert(_taskForSendingToViewer is not null);
+
+ try
+ {
+ _taskCancellationTokenSource.Cancel();
+ _taskForReadingCamera.Wait();
+ _taskForSendingToSlave.Wait();
+ _taskForSendingToViewer.Wait();
+
+ _taskCancellationTokenSource.Dispose();
+ _taskForReadingCamera.Dispose();
+
+ _cameraServer.Stop();
+ _slaveServer.Stop();
+ _viewerServer.Stop();
+
+ IsRunning = false;
+
+ _logger.Information("Stopped.");
+ }
+ catch (Exception ex)
+ {
+ _logger.Warning($"An unhandled exception occurred while stopping EdcHost: {ex}");
+ }
+ }
+
+ void TaskForReadingCameraFunc()
+ {
+ DateTime lastTickStartTime = DateTime.Now;
+
+ while (!_taskCancellationTokenSource?.IsCancellationRequested ?? false)
+ {
+ try
+ {
+ // Wait for next tick
+ DateTime currentTickStartTime = lastTickStartTime.AddMilliseconds(
+ (double)1000 / FrequencyOfReadingCamera);
+ if (currentTickStartTime > DateTime.Now)
+ {
+ Task.Delay(currentTickStartTime - DateTime.Now).Wait();
+ }
+ lastTickStartTime = DateTime.Now;
+
+ foreach (Games.IPlayer player in _game.Players)
+ {
+ // Skip if no hardware info is found
+ if (_playerHardwareInfo.TryGetValue(player.PlayerId, out PlayerHardwareInfo? playerHardwareInfo) is false)
+ {
+ continue;
+ }
+
+ // If the camera is not connected, skip this player
+ int? cameraIndex = playerHardwareInfo.CameraIndex;
+ if (cameraIndex is null)
+ {
+ continue;
+ }
+
+ CameraServers.ICamera camera = _cameraServer.GetCamera(cameraIndex.Value) ?? throw new Exception($"camera {cameraIndex} is not found");
+ Tuple? location = camera.TargetLocation;
+ Games.IPosition? position = location is null ? null : new Games.Position(location.Item1 * MapWidth, location.Item2 * MapHeight);
+
+ if (position is null)
+ {
+ // This is a magic number that means the player is not found.
+ player.Move(float.MinValue, float.MinValue);
+ }
+ else
+ {
+ player.Move(position.X, position.Y);
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ _logger.Fatal($"An unhandled exception occurred while reading camera: {ex}");
+ }
+ }
+ }
+
+ void TaskForSendingToSlaveFunc()
+ {
+ DateTime lastTickStartTime = DateTime.Now;
+
+ while (!_taskCancellationTokenSource?.IsCancellationRequested ?? false)
+ {
+ try
+ {
+ // Wait for next tick
+ DateTime currentTickStartTime = lastTickStartTime.AddMilliseconds(
+ (double)1000 / FrequencyOfSendingToSlave);
+ if (currentTickStartTime > DateTime.Now)
+ {
+ Task.Delay(currentTickStartTime - DateTime.Now).Wait();
+ }
+ lastTickStartTime = DateTime.Now;
+
+ List heightOfChunks = new();
+ foreach (Games.IChunk chunk in _game.GameMap.Chunks)
+ {
+ heightOfChunks.Add(chunk.Height);
+ }
+
+ List owningOreKindOfChunks = new();
+ foreach (Games.IChunk chunk in _game.GameMap.Chunks)
+ {
+ owningOreKindOfChunks.Add((int)chunk.OwningOreKind);
+ }
+
+ for (int i = 0; i < 2; i++)
+ {
+ string? portName = _playerHardwareInfo.GetValueOrDefault(_game.Players[i].PlayerId)?.PortName;
+ if (portName is null)
+ {
+ continue;
+ }
+
+ try
+ {
+ _slaveServer.Publish(
+ portName: portName,
+ gameStage: (int)_game.CurrentStage,
+ elapsedTime: _game.ElapsedTicks,
+ heightOfChunks: heightOfChunks,
+ hasBed: _game.Players[i].HasBed,
+ hasBedOpponent: _game.Players.Any(player => player.HasBed && player.PlayerId != _game.Players[i].PlayerId),
+ positionX: (
+ _game.Players[i].PlayerPosition.X
+ ),
+ positionY: (
+ _game.Players[i].PlayerPosition.Y
+ ),
+ positionOpponentX: (
+ _game.Players[(i == 0) ? 1 : 0].IsAlive == true ?
+ _game.Players[(i == 0) ? 1 : 0].PlayerPosition.X :
+ float.MinValue
+ ),
+ positionOpponentY: (
+ _game.Players[(i == 0) ? 1 : 0].IsAlive == true ?
+ _game.Players[(i == 0) ? 1 : 0].PlayerPosition.Y :
+ float.MinValue
+ ),
+ agility: _game.Players[i].ActionPoints,
+ health: _game.Players[i].Health,
+ maxHealth: _game.Players[i].MaxHealth,
+ strength: _game.Players[i].Strength,
+ emeraldCount: _game.Players[i].EmeraldCount,
+ woolCount: _game.Players[i].WoolCount,
+ owningOreKindOfChunks: owningOreKindOfChunks
+ );
+ }
+ catch (Exception e)
+ {
+ _logger.Error($"failed to publish to slave via port {portName}: {e.Message}");
+ }
+ }
+ }
+ catch (Exception ex)
+ {
+ _logger.Fatal($"An unhandled exception occurred while sending to slave: {ex}");
+ }
+ }
+ }
+
+ void TaskForSendingToViewerFunc()
+ {
+ DateTime lastTickStartTime = DateTime.Now;
+
+ while (!_taskCancellationTokenSource?.IsCancellationRequested ?? false)
+ {
+ try
+ {
+ // Wait for next tick
+ DateTime currentTickStartTime = lastTickStartTime.AddMilliseconds(
+ (double)1000 / FrequencyOfSendingToViewer);
+ if (currentTickStartTime > DateTime.Now)
+ {
+ Task.Delay(currentTickStartTime - DateTime.Now).Wait();
+ }
+ lastTickStartTime = DateTime.Now;
+
+ List cameraInfoList = new();
+ foreach (int cameraIndex in _cameraServer.AvailableCameraIndexes)
+ {
+ CameraServers.ICamera? camera = _cameraServer.GetCamera(cameraIndex);
+ if (camera?.IsOpened ?? false)
+ {
+ cameraInfoList.Add(new ViewerServers.CompetitionUpdateMessage.Camera
+ {
+ cameraId = cameraIndex,
+ height = camera.Height,
+ width = camera.Width,
+ frameData = Convert.ToBase64String(camera.JpegData ?? new byte[] { })
+ });
+ }
+ }
+
+ // Events for this tick;
+ List currentEvents = new();
+ while (!_playerEventQueue.IsEmpty)
+ {
+ if (_playerEventQueue.TryDequeue(out EventArgs? playerEvent) && playerEvent is not null)
+ {
+ ViewerServers.CompetitionUpdateMessage.Event currentEvent = new();
+ switch (playerEvent)
+ {
+ case Games.PlayerDigEventArgs digEvent:
+ currentEvent = new()
+ {
+ playerDigEvent = new()
+ {
+ playerId = digEvent.Player.PlayerId,
+ targetChunk = digEvent.TargetChunk
+ }
+ };
+ break;
+ case Games.PlayerPickUpEventArgs pickUpEvent:
+ currentEvent = new()
+ {
+ playerPickUpEvent = new()
+ {
+ playerId = pickUpEvent.Player.PlayerId,
+ itemCount = pickUpEvent.ItemCount,
+ itemType = (ViewerServers.CompetitionUpdateMessage.Event.PlayerPickUpEvent.ItemType)pickUpEvent.MineType
+ }
+ };
+ break;
+ case Games.PlayerPlaceEventArgs placeEvent:
+ currentEvent = new()
+ {
+ playerPlaceBlockEvent = new()
+ {
+ playerId = placeEvent.Player.PlayerId
+ }
+ };
+ break;
+ // TODO: finish other cases
+ default:
+ break;
+ }
+ currentEvents.Add(currentEvent);
+ }
+ }
+
+
+ // Send packet to the viewer
+ _viewerServer.Publish(new ViewerServers.CompetitionUpdateMessage()
+ {
+ cameras = cameraInfoList,
+
+ chunks = _game.GameMap.Chunks.Select(chunk => new ViewerServers.CompetitionUpdateMessage.Chunk()
+ {
+ chunkId = chunk.Position != null ? chunk.Position.X + chunk.Position.Y * 8 : -1,
+ height = chunk.Height,
+ position = chunk.Position != null ? new ViewerServers.CompetitionUpdateMessage.Chunk.Position()
+ {
+ x = chunk.Position.X,
+ y = chunk.Position.Y
+ } : null
+ }).ToList(),
+
+ events = currentEvents,
+
+ info = new ViewerServers.CompetitionUpdateMessage.Info()
+ {
+ stage = _game.CurrentStage switch
+ {
+ Games.IGame.Stage.Ready => ViewerServers.CompetitionUpdateMessage.Info.Stage.Ready,
+ Games.IGame.Stage.Running => ViewerServers.CompetitionUpdateMessage.Info.Stage.Running,
+ Games.IGame.Stage.Finished => ViewerServers.CompetitionUpdateMessage.Info.Stage.Finished,
+ Games.IGame.Stage.Battling => ViewerServers.CompetitionUpdateMessage.Info.Stage.Battling,
+ _ => throw new NotImplementedException($"{_game.CurrentStage} is not implemented")
+ },
+ elapsedTicks = _game.ElapsedTicks
+ },
+
+ mines = _game.Mines.Select(mine => new ViewerServers.CompetitionUpdateMessage.Mine()
+ {
+ mineId = mine.MineId.ToString(),
+ accumulatedOreCount = mine.AccumulatedOreCount,
+ oreType = (ViewerServers.CompetitionUpdateMessage.Mine.OreType)mine.OreKind,
+ position = new ViewerServers.CompetitionUpdateMessage.Mine.Position()
+ {
+ x = mine.Position.X,
+ y = mine.Position.Y
+ }
+ }).ToList(),
+
+ players = _game.Players.Select(player => new ViewerServers.CompetitionUpdateMessage.Player()
+ {
+ playerId = (player.PlayerId),
+
+ cameraId = player.PlayerId,
+
+ attributes = new()
+ {
+ agility = player.ActionPoints,
+ strength = player.Strength,
+ maxHealth = player.MaxHealth
+ },
+ health = player.Health,
+ homePosition = new ViewerServers.CompetitionUpdateMessage.Player.HomePosition()
+ {
+ x = player.SpawnPoint.X,
+ y = player.SpawnPoint.Y,
+ },
+ inventory = new ViewerServers.CompetitionUpdateMessage.Player.Inventory()
+ {
+ emerald = player.EmeraldCount,
+ wool = player.WoolCount
+ },
+ position = new ViewerServers.CompetitionUpdateMessage.Player.Position()
+ {
+ x = player.PlayerPosition.X,
+ y = player.PlayerPosition.Y
+ }
+ }).ToList()
+ });
+ }
+ catch (Exception ex)
+ {
+ _logger.Fatal($"An unhandled exception occurred while sending to viewer: {ex}");
+ }
+ }
+ }
+
+ Config ReLoadConfig()
+ {
+ Config config = new();
+ string path = Path.Combine(Directory.GetCurrentDirectory(), "config.json");
+ if (!File.Exists(path))
+ {
+ Log.Warning($"Config file not found at {path}, creating default config file...");
+ File.WriteAllText(path, JsonSerializer.Serialize(config, new JsonSerializerOptions { WriteIndented = true }));
+ }
+ else
+ {
+ try
+ {
+ config = JsonSerializer.Deserialize(File.ReadAllText(path))!;
+ }
+ catch (JsonException)
+ {
+ Log.Error($"Error parsing config file at {path}");
+
+#if DEBUG
+ throw;
+#else
+ Log.Information($"Using default config.");
+#endif
+ }
+ }
+
+ return config;
+ }
+}
diff --git a/host/src/EdcHost/EdcHost.csproj b/host/src/EdcHost/EdcHost.csproj
new file mode 100644
index 0000000..df12fc8
--- /dev/null
+++ b/host/src/EdcHost/EdcHost.csproj
@@ -0,0 +1,23 @@
+
+
+ Exe
+ net6.0
+ enable
+ enable
+ 0.4.0
+ true
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/host/src/EdcHost/Games/Chunk.cs b/host/src/EdcHost/Games/Chunk.cs
new file mode 100644
index 0000000..c78a958
--- /dev/null
+++ b/host/src/EdcHost/Games/Chunk.cs
@@ -0,0 +1,51 @@
+namespace EdcHost.Games;
+
+class Chunk : IChunk
+{
+ const int MaxHeight = 8;
+
+ public bool CanPlaceBlock => (Height < MaxHeight);
+ public bool CanRemoveBlock => (Height > 0);
+ public int Height { get; private set; }
+ public bool IsVoid => (Height == 0);
+ public IPosition Position { get; }
+
+ public IMine.OreKindType OwningOreKind { get; set; } = IMine.OreKindType.None;
+
+ ///
+ /// Creates a new chunk.
+ ///
+ /// Height of the chunk
+ /// Position of the chunk
+ public Chunk(int height, IPosition position)
+ {
+ Height = height;
+ Position = position;
+ }
+
+ ///
+ /// Places a block in the chunk.
+ ///
+ public void PlaceBlock()
+ {
+ if (CanPlaceBlock == false)
+ {
+ throw new InvalidOperationException("cannot place block in chunk");
+ }
+
+ Height++;
+ }
+
+ ///
+ /// Removes a block from the chunk.
+ ///
+ public void RemoveBlock()
+ {
+ if (CanRemoveBlock == false)
+ {
+ throw new InvalidOperationException("cannot remove block from chunk");
+ }
+
+ Height--;
+ }
+}
diff --git a/host/src/EdcHost/Games/EventArgs/AfterGameStartEventArgs.cs b/host/src/EdcHost/Games/EventArgs/AfterGameStartEventArgs.cs
new file mode 100644
index 0000000..f885451
--- /dev/null
+++ b/host/src/EdcHost/Games/EventArgs/AfterGameStartEventArgs.cs
@@ -0,0 +1,14 @@
+namespace EdcHost.Games;
+
+public class AfterGameStartEventArgs : EventArgs
+{
+ ///
+ /// The game.
+ ///
+ public IGame Game { get; }
+
+ public AfterGameStartEventArgs(IGame game)
+ {
+ Game = game;
+ }
+}
diff --git a/host/src/EdcHost/Games/EventArgs/AfterGameTickEventArgs.cs b/host/src/EdcHost/Games/EventArgs/AfterGameTickEventArgs.cs
new file mode 100644
index 0000000..b01f548
--- /dev/null
+++ b/host/src/EdcHost/Games/EventArgs/AfterGameTickEventArgs.cs
@@ -0,0 +1,20 @@
+namespace EdcHost.Games;
+
+public class AfterGameTickEventArgs : EventArgs
+{
+ ///
+ /// The game.
+ ///
+ public IGame Game { get; }
+
+ ///
+ /// Start time of the game.
+ ///
+ public int CurrentTick { get; }
+
+ public AfterGameTickEventArgs(IGame game, int currentTick)
+ {
+ Game = game;
+ CurrentTick = currentTick;
+ }
+}
diff --git a/host/src/EdcHost/Games/EventArgs/AfterJudgementEventArgs.cs b/host/src/EdcHost/Games/EventArgs/AfterJudgementEventArgs.cs
new file mode 100644
index 0000000..6344303
--- /dev/null
+++ b/host/src/EdcHost/Games/EventArgs/AfterJudgementEventArgs.cs
@@ -0,0 +1,20 @@
+namespace EdcHost.Games;
+
+public class AfterJudgementEventArgs : EventArgs
+{
+ ///
+ /// The game.
+ ///
+ public IGame Game { get; }
+
+ ///
+ /// Start time of the game.
+ ///
+ public IPlayer? Winner { get; }
+
+ public AfterJudgementEventArgs(IGame game, IPlayer? winner)
+ {
+ Game = game;
+ Winner = winner;
+ }
+}
diff --git a/host/src/EdcHost/Games/EventArgs/PlayerAttackEventArgs.cs b/host/src/EdcHost/Games/EventArgs/PlayerAttackEventArgs.cs
new file mode 100644
index 0000000..b91c80b
--- /dev/null
+++ b/host/src/EdcHost/Games/EventArgs/PlayerAttackEventArgs.cs
@@ -0,0 +1,23 @@
+namespace EdcHost.Games;
+
+public class PlayerAttackEventArgs : EventArgs
+{
+ ///
+ /// The player that moved.
+ ///
+ public IPlayer Player { get; }
+
+ public int Strength { get; }
+
+ ///
+ /// The position the player attack.
+ ///
+ public IPosition Position { get; }
+
+ public PlayerAttackEventArgs(IPlayer player, int strength, IPosition position)
+ {
+ Player = player;
+ Strength = strength;
+ Position = position;
+ }
+}
diff --git a/host/src/EdcHost/Games/EventArgs/PlayerDieEventArgs.cs b/host/src/EdcHost/Games/EventArgs/PlayerDieEventArgs.cs
new file mode 100644
index 0000000..f3f306b
--- /dev/null
+++ b/host/src/EdcHost/Games/EventArgs/PlayerDieEventArgs.cs
@@ -0,0 +1,14 @@
+namespace EdcHost.Games;
+
+public class PlayerDieEventArgs : EventArgs
+{
+ ///
+ /// The player that moved.
+ ///
+ public IPlayer Player { get; }
+
+ public PlayerDieEventArgs(IPlayer player)
+ {
+ Player = player;
+ }
+}
diff --git a/host/src/EdcHost/Games/EventArgs/PlayerDigEventArgs.cs b/host/src/EdcHost/Games/EventArgs/PlayerDigEventArgs.cs
new file mode 100644
index 0000000..1038bc9
--- /dev/null
+++ b/host/src/EdcHost/Games/EventArgs/PlayerDigEventArgs.cs
@@ -0,0 +1,16 @@
+namespace EdcHost.Games;
+
+public class PlayerDigEventArgs : EventArgs
+{
+ ///
+ /// The player that dig.
+ ///
+ public IPlayer Player { get; }
+ public int TargetChunk { get; }
+
+ public PlayerDigEventArgs(IPlayer player, int targetChunk)
+ {
+ Player = player;
+ TargetChunk = targetChunk;
+ }
+}
diff --git a/host/src/EdcHost/Games/EventArgs/PlayerMoveEventArgs.cs b/host/src/EdcHost/Games/EventArgs/PlayerMoveEventArgs.cs
new file mode 100644
index 0000000..e8c7737
--- /dev/null
+++ b/host/src/EdcHost/Games/EventArgs/PlayerMoveEventArgs.cs
@@ -0,0 +1,24 @@
+namespace EdcHost.Games;
+
+public class PlayerMoveEventArgs : EventArgs
+{
+ ///
+ /// The player that moved.
+ ///
+ public IPlayer Player { get; }
+ ///
+ /// The position of the player before the movement.
+ ///
+ public IPosition PositionBeforeMovement { get; }
+ ///
+ /// The position of the player after the movement.
+ ///
+ public IPosition Position { get; }
+
+ public PlayerMoveEventArgs(IPlayer player, IPosition positionBeforeMovement, IPosition position)
+ {
+ Player = player;
+ PositionBeforeMovement = positionBeforeMovement;
+ Position = position;
+ }
+}
diff --git a/host/src/EdcHost/Games/EventArgs/PlayerPickUpEventArgs.cs b/host/src/EdcHost/Games/EventArgs/PlayerPickUpEventArgs.cs
new file mode 100644
index 0000000..b3c430f
--- /dev/null
+++ b/host/src/EdcHost/Games/EventArgs/PlayerPickUpEventArgs.cs
@@ -0,0 +1,31 @@
+namespace EdcHost.Games;
+
+public class PlayerPickUpEventArgs : EventArgs
+{
+ ///
+ /// The player that dig.
+ ///
+ public IPlayer Player { get; }
+
+ ///
+ /// The type of the mine that is picked up.
+ ///
+ public IMine.OreKindType MineType { get; }
+
+ ///
+ /// The count of item
+ ///
+ public int ItemCount { get; }
+
+ ///
+ /// The id of the mine
+ ///
+ public string MineId { get; }
+ public PlayerPickUpEventArgs(IPlayer player, IMine.OreKindType mineType, int itemCount, string mineId)
+ {
+ Player = player;
+ MineType = mineType;
+ ItemCount = itemCount;
+ MineId = mineId;
+ }
+}
diff --git a/host/src/EdcHost/Games/EventArgs/PlayerPlaceEventArgs.cs b/host/src/EdcHost/Games/EventArgs/PlayerPlaceEventArgs.cs
new file mode 100644
index 0000000..bf9cc9f
--- /dev/null
+++ b/host/src/EdcHost/Games/EventArgs/PlayerPlaceEventArgs.cs
@@ -0,0 +1,20 @@
+namespace EdcHost.Games;
+
+public class PlayerPlaceEventArgs : EventArgs
+{
+ ///
+ /// The player that moved.
+ ///
+ public IPlayer Player { get; }
+
+ ///
+ /// The position the player place a block.
+ ///
+ public IPosition Position { get; }
+
+ public PlayerPlaceEventArgs(IPlayer player, IPosition position)
+ {
+ Player = player;
+ Position = position;
+ }
+}
diff --git a/host/src/EdcHost/Games/EventArgs/PlayerTradeEventArgs.cs b/host/src/EdcHost/Games/EventArgs/PlayerTradeEventArgs.cs
new file mode 100644
index 0000000..a9d5591
--- /dev/null
+++ b/host/src/EdcHost/Games/EventArgs/PlayerTradeEventArgs.cs
@@ -0,0 +1,13 @@
+namespace EdcHost.Games;
+
+public class PlayerTradeEventArgs : EventArgs
+{
+ public IPlayer Player { get; }
+ public IPlayer.CommodityKindType CommodityKind { get; }
+
+ public PlayerTradeEventArgs(IPlayer player, IPlayer.CommodityKindType commodityKind)
+ {
+ Player = player;
+ CommodityKind = commodityKind;
+ }
+}
diff --git a/host/src/EdcHost/Games/Game.Event.cs b/host/src/EdcHost/Games/Game.Event.cs
new file mode 100644
index 0000000..3b1bf88
--- /dev/null
+++ b/host/src/EdcHost/Games/Game.Event.cs
@@ -0,0 +1,19 @@
+namespace EdcHost.Games;
+
+partial class Game : IGame
+{
+ ///
+ /// Raised after game starts.
+ ///
+ public event EventHandler? AfterGameStartEvent;
+
+ ///
+ /// Raised after a new game tick.
+ ///
+ public event EventHandler? AfterGameTickEvent;
+
+ ///
+ /// Raised after judjement.
+ ///
+ public event EventHandler? AfterJudgementEvent;
+}
diff --git a/host/src/EdcHost/Games/Game.Mine.cs b/host/src/EdcHost/Games/Game.Mine.cs
new file mode 100644
index 0000000..79a89d7
--- /dev/null
+++ b/host/src/EdcHost/Games/Game.Mine.cs
@@ -0,0 +1,45 @@
+namespace EdcHost.Games;
+
+partial class Game : IGame
+{
+ ///
+ /// Generate mines according to game config
+ ///
+ /// Diamond mine list
+ /// Gold mine list
+ /// Iron mine list
+ private void GenerateMines(List>? diamondMines,
+ List>? goldMines, List>? ironMines)
+ {
+ if (diamondMines is not null)
+ {
+ foreach (Tuple minePos in diamondMines)
+ {
+ var position = new Position(minePos.Item1, minePos.Item2);
+ var mine = new Mine(IMine.OreKindType.Diamond, position, 0);
+ Mines.Add(mine);
+ GameMap.GetChunkAt(position).OwningOreKind = IMine.OreKindType.Diamond;
+ }
+ }
+ if (goldMines is not null)
+ {
+ foreach (Tuple minePos in goldMines)
+ {
+ var position = new Position(minePos.Item1, minePos.Item2);
+ var mine = new Mine(IMine.OreKindType.GoldIngot, position, 0);
+ Mines.Add(mine);
+ GameMap.GetChunkAt(position).OwningOreKind = IMine.OreKindType.GoldIngot;
+ }
+ }
+ if (ironMines is not null)
+ {
+ foreach (Tuple minePos in ironMines)
+ {
+ var position = new Position(minePos.Item1, minePos.Item2);
+ var mine = new Mine(IMine.OreKindType.IronIngot, position, 0);
+ Mines.Add(mine);
+ GameMap.GetChunkAt(position).OwningOreKind = IMine.OreKindType.IronIngot;
+ }
+ }
+ }
+}
diff --git a/host/src/EdcHost/Games/Game.Player.Event.cs b/host/src/EdcHost/Games/Game.Player.Event.cs
new file mode 100644
index 0000000..b8c8074
--- /dev/null
+++ b/host/src/EdcHost/Games/Game.Player.Event.cs
@@ -0,0 +1,257 @@
+namespace EdcHost.Games;
+
+partial class Game : IGame
+{
+ ///
+ /// Enqueue a event.
+ ///
+ ///
+ /// Event args
+ void EnqueueEvent(object? sender, EventArgs e)
+ {
+ if (CurrentStage != IGame.Stage.Running && CurrentStage != IGame.Stage.Battling)
+ {
+ return;
+ }
+
+ _playerEventQueue.Enqueue(e);
+ }
+
+ ///
+ /// Handle PlayerMoveEvent
+ ///
+ /// Event args
+ void HandlePlayerMoveEvent(PlayerMoveEventArgs e)
+ {
+ if (CurrentStage != IGame.Stage.Running && CurrentStage != IGame.Stage.Battling)
+ {
+ // Do not handle player events when game is not running
+ return;
+ }
+
+ try
+ {
+ if (e.Player.IsAlive == false && e.Player.HasBed == true
+ && ElapsedTicks - _playerDeathTickList[e.Player.PlayerId] > TicksBeforeRespawn
+ && IsSamePosition(
+ ToIntPosition(e.Position), e.Player.SpawnPoint
+ ) == true)
+ {
+ Players[e.Player.PlayerId].Spawn(e.Player.MaxHealth);
+ _playerDeathTickList[e.Player.PlayerId] = null;
+ }
+
+ //Kill fallen player. Use 'if' instead of 'else if' to avoid fake spawn.
+ if (e.Player.IsAlive == true && IsValidPosition(ToIntPosition(e.Position)) == false)
+ {
+ Players[e.Player.PlayerId].Hurt(InstantDeathDamage);
+ return;
+ }
+ if (e.Player.IsAlive == true && GameMap.GetChunkAt(ToIntPosition(e.Position)).IsVoid == true)
+ {
+ Players[e.Player.PlayerId].Hurt(InstantDeathDamage);
+ return;
+ }
+
+ }
+ catch (Exception exception)
+ {
+ _logger.Error($"Failed to move: {exception}");
+ }
+ }
+
+ ///
+ /// Handle PlayerAttackEvent
+ ///
+ /// Event args
+ void HandlePlayerAttackEvent(PlayerAttackEventArgs e)
+ {
+ if (CurrentStage != IGame.Stage.Running && CurrentStage != IGame.Stage.Battling)
+ {
+ return;
+ }
+
+ if (e.Player.IsAlive == false)
+ {
+ _logger.Error($"Player {e.Player.PlayerId} is dead. PlayerAttack rejected.");
+ return;
+ }
+ if (ElapsedTicks - _playerLastAttackTickList[e.Player.PlayerId] < AttackTickInterval(e.Player))
+ {
+ _logger.Error(@$"Player {e.Player.PlayerId} has already attacked recently.
+ PlayerAttack rejected.");
+ return;
+ }
+ if (IsAdjacent(ToIntPosition(e.Player.PlayerPosition), e.Position) == false)
+ {
+ _logger.Error(@$"Position ({e.Position.X}, {e.Position.Y})
+ is not adjacent to player {e.Player.PlayerId}. PlayerAttack rejected.");
+ return;
+ }
+ if (IsValidPosition(e.Position) == false)
+ {
+ _logger.Error(@$"Position ({e.Position.X}, {e.Position.Y}) is not valid.
+ PlayerAttack rejected.");
+ return;
+ }
+
+ bool attacked = false;
+ for (int i = 0; i < PlayerNum; i++)
+ {
+ if (Players[i].PlayerId != e.Player.PlayerId && Players[i].IsAlive == true
+ && IsSamePosition(e.Position,
+ ToIntPosition(Players[i].PlayerPosition)) == true)
+ {
+ Players[i].Hurt(e.Player.Strength);
+ attacked = true;
+ }
+ }
+
+ if (attacked == true)
+ {
+ _playerLastAttackTickList[e.Player.PlayerId] = ElapsedTicks;
+ }
+ else
+ {
+ if (GameMap.GetChunkAt(e.Position).CanRemoveBlock == false)
+ {
+ _logger.Error("Target chunk is empty. PlayerAttack rejected.");
+ return;
+ }
+
+ try
+ {
+ GameMap.GetChunkAt(e.Position).RemoveBlock();
+ _playerLastAttackTickList[e.Player.PlayerId] = ElapsedTicks;
+
+ if (GameMap.GetChunkAt(e.Position).IsVoid == true)
+ {
+ for (int i = 0; i < PlayerNum; i++)
+ {
+ if (Players[i].HasBed == true && IsSamePosition(
+ Players[i].SpawnPoint, e.Position) == true)
+ {
+ Players[i].DestroyBed();
+ }
+ }
+ }
+ }
+ catch (Exception exception)
+ {
+ _logger.Error($"Failed to dig: {exception}");
+ return;
+ }
+ }
+ }
+
+ ///
+ /// Handle PlayerPlaceEvent
+ ///
+ /// Event args
+ void HandlePlayerPlaceEvent(PlayerPlaceEventArgs e)
+ {
+ if (CurrentStage != IGame.Stage.Running && CurrentStage != IGame.Stage.Battling)
+ {
+ return;
+ }
+
+ if (e.Player.IsAlive == false)
+ {
+ _logger.Error($"Player {e.Player.PlayerId} is dead. PlayerPlace rejected.");
+ return;
+ }
+ if (e.Player.WoolCount <= 0)
+ {
+ _logger.Error($"Player {e.Player.PlayerId} doesn't have enough wool. PlayerPlace rejected.");
+ }
+ if (IsAdjacent(ToIntPosition(e.Player.PlayerPosition), e.Position) == false)
+ {
+ _logger.Error(@$"Position ({e.Position.X}, {e.Position.Y})
+ is not adjecant to player {e.Player.PlayerId}. PlayerPlace rejected.");
+ return;
+ }
+ if (IsValidPosition(e.Position) == false)
+ {
+ _logger.Error(@$"Position ({e.Position.X}, {e.Position.Y}) is not valid.
+ PlayerPlace rejected.");
+ return;
+ }
+
+ try
+ {
+ if (GameMap.GetChunkAt(e.Position).CanPlaceBlock == true)
+ {
+ GameMap.GetChunkAt(e.Position).PlaceBlock();
+ Players[e.Player.PlayerId].DecreaseWoolCount();
+ }
+ else
+ {
+ _logger.Error(@$"The chunk at position ({e.Position.X}, {e.Position.Y})
+ has already reached its maximum height. PlayerPlace rejected.");
+ }
+ }
+ catch (Exception exception)
+ {
+ _logger.Error($"Failed to place wool: {exception}");
+ return;
+ }
+ }
+
+ ///
+ /// Handle PlayerDieEvent
+ ///
+ /// Event args
+ void HandlePlayerDieEvent(PlayerDieEventArgs e)
+ {
+ if (CurrentStage != IGame.Stage.Running && CurrentStage != IGame.Stage.Battling)
+ {
+ return;
+ }
+
+ if (_playerDeathTickList[e.Player.PlayerId] is not null)
+ {
+ _logger.Error($"Player {e.Player.PlayerId} is already dead. PlayerDie rejected.");
+ return;
+ }
+
+ _playerDeathTickList[e.Player.PlayerId] = ElapsedTicks;
+ }
+
+ ///
+ /// Handle PlayerTradeEvent
+ ///
+ /// Event args
+ void HandlePlayerTradeEvent(PlayerTradeEventArgs e)
+ {
+ if (CurrentStage != IGame.Stage.Running)
+ {
+ _logger.Error($"Failed to trade: Trade is allowed at stage Running");
+ return;
+ }
+ if (Players[e.Player.PlayerId].IsAlive == false)
+ {
+ _logger.Error($"Failed to trade: Player {e.Player.PlayerId} is dead.");
+ return;
+ }
+ if (IsSamePosition(
+ ToIntPosition(Players[e.Player.PlayerId].PlayerPosition), Players[e.Player.PlayerId].SpawnPoint
+ ) == false)
+ {
+ _logger.Error($"Failed to trade: Player {e.Player.PlayerId} is not at spawn point");
+ return;
+ }
+
+ try
+ {
+ bool result = Players[e.Player.PlayerId].Trade(e.CommodityKind);
+ if (result == false)
+ {
+ _logger.Error($"Failed to trade: Player {e.Player.PlayerId} cannot buy {e.CommodityKind}");
+ }
+ }
+ catch (Exception ex)
+ {
+ _logger.Error($"Failed to trade: {ex}");
+ }
+ }
+}
diff --git a/host/src/EdcHost/Games/Game.Player.cs b/host/src/EdcHost/Games/Game.Player.cs
new file mode 100644
index 0000000..0778437
--- /dev/null
+++ b/host/src/EdcHost/Games/Game.Player.cs
@@ -0,0 +1,50 @@
+using System.Collections.Concurrent;
+
+namespace EdcHost.Games;
+
+partial class Game : IGame
+{
+ const int TicksBeforeRespawn = 300;
+
+ ///
+ /// Maximum count of same type of items a player can hold.
+ ///
+ public const int MaximumItemCount = 128;
+
+ ///
+ /// The damage which will kill a player instantly.
+ ///
+ const int InstantDeathDamage = 114514;
+
+ ///
+ /// This means a player hasn't done something (for example, Attack) yet
+ /// after game started.
+ ///
+ const int Never = -10000;
+
+ ///
+ /// Number of players.
+ ///
+ public int PlayerNum { get; }
+
+ ///
+ /// All players.
+ ///
+ public List Players { get; private set; }
+
+ ///
+ /// Whether all beds are destroyed or not.
+ ///
+ bool _isAllBedsDestroyed;
+
+ readonly List _playerDeathTickList;
+ readonly List _playerLastAttackTickList;
+
+ readonly ConcurrentQueue _playerEventQueue;
+
+ int AttackTickInterval(IPlayer player)
+ {
+ return (int)(Math.Max(8.5 - 0.25 * player.ActionPoints, 0.5) * TicksPerSecondExpected);
+ }
+
+}
diff --git a/host/src/EdcHost/Games/Game.Position.cs b/host/src/EdcHost/Games/Game.Position.cs
new file mode 100644
index 0000000..797d93c
--- /dev/null
+++ b/host/src/EdcHost/Games/Game.Position.cs
@@ -0,0 +1,67 @@
+namespace EdcHost.Games;
+
+partial class Game : IGame
+{
+ ///
+ /// Convert a float position to an int position.
+ ///
+ /// The float position
+ /// The int position
+ IPosition ToIntPosition(IPosition floatPosition)
+ {
+ int x = (floatPosition.X < -1e-6) ? -(1 + (int)(-floatPosition.X)) : (int)floatPosition.X;
+ int y = (floatPosition.Y < -1e-6) ? -(1 + (int)(-floatPosition.Y)) : (int)floatPosition.Y;
+ return new Position(x, y);
+ }
+
+ IPosition ToFloatPosition(IPosition intPosition)
+ {
+ float offset = 0.5f;
+ return new Position(offset + (float)intPosition.X, offset + (float)intPosition.Y);
+ }
+
+ ///
+ /// Whether the position is a valid position or not.
+ ///
+ /// The position
+ /// True if valid, false otherwise
+ bool IsValidPosition(IPosition position)
+ {
+ return (position.X >= 0 && position.X < 8 && position.Y >= 0 && position.Y < 8);
+ }
+
+ ///
+ /// Whether two positions is adjacent or not.
+ ///
+ /// First position
+ /// Second position
+ /// True if adjacant, false otherwise
+ bool IsAdjacent(IPosition position1, IPosition position2)
+ {
+ return (Math.Abs(position1.X - position2.X) <= 1
+ && Math.Abs(position1.Y - position2.Y) <= 1);
+ }
+
+ ///
+ /// Whether two positions is same or not.
+ ///
+ /// First position
+ /// Second position
+ /// True if same, fale otherwise
+ bool IsSamePosition(IPosition position1, IPosition position2)
+ {
+ return (position1.X == position2.X && position1.Y == position2.Y);
+ }
+
+ ///
+ /// Eucilid distance between two positions.
+ ///
+ /// First position
+ /// Second position
+ /// THe eucilid distance
+ double EucilidDistance(IPosition position1, IPosition position2)
+ {
+ return Math.Sqrt((position1.X - position2.X) * (position1.X - position2.X)
+ + (position1.Y - position2.Y) * (position1.Y - position2.Y));
+ }
+}
diff --git a/host/src/EdcHost/Games/Game.cs b/host/src/EdcHost/Games/Game.cs
new file mode 100644
index 0000000..6ef77f3
--- /dev/null
+++ b/host/src/EdcHost/Games/Game.cs
@@ -0,0 +1,392 @@
+using Serilog;
+
+namespace EdcHost.Games;
+
+///
+/// Game handles the game logic.
+///
+partial class Game : IGame
+{
+ const int TickBattlingModeStart = 12000;
+ public const int TicksPerSecondExpected = 20;
+ const int TicksBattlingDamageInterval = 100;
+ const int BattlingDamage = 1;
+
+ ///
+ /// Current stage of the game.
+ ///
+ public IGame.Stage CurrentStage { get; private set; } = IGame.Stage.Ready;
+
+ ///
+ /// Elapsed ticks of the game.
+ ///
+ public int ElapsedTicks { get; private set; } = 0;
+
+ ///
+ /// Winner of the game.
+ ///
+ ///
+ /// Winner can be null in case there is no winner.
+ ///
+ public IPlayer? Winner { get; private set; } = null;
+
+ ///
+ /// The game map.
+ ///
+ public IMap GameMap { get; private set; }
+
+ ///
+ /// All mines.
+ ///
+ public List Mines { get; private set; }
+
+ ///
+ /// Default players.
+ ///
+ readonly IPlayer[] _defaultPlayerList = {
+ new Player(0, 0, 0, 0.5f, 0.5f),
+ new Player(1, 7, 7, 7.5f, 7.5f)
+ };
+
+ ///
+ /// Default spawn points.
+ ///
+ readonly IPosition[] _defaultSpawnPoints = {
+ new Position(0, 0),
+ new Position(7, 7)
+ };
+
+ ///
+ /// Used to lock some blocks.
+ ///
+ readonly object _gameLocker = new();
+
+ readonly ILogger _logger = Log.Logger.ForContext("Component", "Games");
+
+ public Game(
+ List>? diamondMines = null,
+ List>? goldMines = null,
+ List>? ironMines = null,
+ List? playerList = null,
+ IPosition[]? spawnPoints = null
+ )
+ {
+ spawnPoints ??= _defaultSpawnPoints;
+ playerList ??= new(_defaultPlayerList);
+
+ PlayerNum = playerList.Count;
+
+ if (PlayerNum != spawnPoints.Length)
+ {
+ throw new ArgumentException(
+ "Number of players does not match number of spawn points");
+ }
+
+ GameMap = new Map(spawnPoints);
+
+ _playerLastAttackTickList = new();
+ for (int i = 0; i < PlayerNum; i++)
+ {
+ _playerLastAttackTickList.Add(Never);
+ }
+
+ _playerDeathTickList = new();
+ for (int i = 0; i < PlayerNum; i++)
+ {
+ _playerDeathTickList.Add(null);
+ }
+
+ _playerEventQueue = new();
+ _playerEventQueue.Clear();
+
+ Mines = new();
+ GenerateMines(
+ diamondMines: diamondMines,
+ goldMines: goldMines,
+ ironMines: ironMines
+ );
+
+ _isAllBedsDestroyed = false;
+
+ Players = new(playerList);
+
+ for (int i = 0; i < PlayerNum; i++)
+ {
+ Players[i].OnMove += EnqueueEvent;
+ Players[i].OnAttack += EnqueueEvent;
+ Players[i].OnPlace += EnqueueEvent;
+ Players[i].OnDie += EnqueueEvent;
+ Players[i].OnTrade += EnqueueEvent;
+ }
+
+ for (int i = 0; i < PlayerNum; i++)
+ {
+ _playerLastAttackTickList[i] = Never;
+ }
+
+ for (int i = 0; i < PlayerNum; i++)
+ {
+ _playerDeathTickList[i] = null;
+ }
+
+ Winner = null;
+
+ _isAllBedsDestroyed = false;
+ }
+
+ public void Start()
+ {
+ _logger.Information("Starting...");
+
+ if (CurrentStage != IGame.Stage.Ready)
+ {
+ throw new InvalidOperationException("the game has already started");
+ }
+
+ _playerEventQueue.Clear();
+
+ CurrentStage = IGame.Stage.Running;
+ AfterGameStartEvent?.Invoke(this, new AfterGameStartEventArgs(this));
+
+ _logger.Information("Started.");
+ }
+
+ public void End()
+ {
+ _logger.Information("Ending...");
+
+ if (CurrentStage != IGame.Stage.Running && CurrentStage != IGame.Stage.Battling)
+ {
+ throw new InvalidOperationException("the game is not running");
+ }
+
+ CurrentStage = IGame.Stage.Finished;
+
+ _logger.Information("Ended.");
+ }
+
+ public void Tick()
+ {
+ ++ElapsedTicks;
+
+ try
+ {
+ lock (_gameLocker)
+ {
+ HandlePlayerEvents();
+
+ if (IsFinished())
+ {
+ Judge();
+ CurrentStage = IGame.Stage.Finished;
+ return;
+ }
+
+ if (ElapsedTicks > TickBattlingModeStart && CurrentStage == IGame.Stage.Running)
+ {
+ CurrentStage = IGame.Stage.Battling;
+ }
+
+ if (CurrentStage == IGame.Stage.Battling)
+ {
+ if (_isAllBedsDestroyed == false)
+ {
+ for (int i = 0; i < PlayerNum; i++)
+ {
+ Players[i].DestroyBed();
+ }
+ _isAllBedsDestroyed = true;
+ }
+
+ if ((ElapsedTicks - TickBattlingModeStart) % TicksBattlingDamageInterval == 0)
+ {
+ for (int i = 0; i < PlayerNum; i++)
+ {
+ Players[i].Hurt(BattlingDamage);
+ }
+ }
+ }
+
+ UpdatePlayerInfo();
+ UpdateMines();
+ }
+
+ AfterGameTickEvent?.Invoke(
+ this, new AfterGameTickEventArgs(this, ElapsedTicks));
+ }
+ catch (Exception ex)
+ {
+ _logger.Fatal($"An unhandled exception occurred at tick {ElapsedTicks}: {ex}");
+ }
+ }
+
+ void HandlePlayerEvents()
+ {
+ while (_playerEventQueue.IsEmpty == false)
+ {
+ if (_playerEventQueue.TryDequeue(out EventArgs? playerEvent) && playerEvent is not null)
+ {
+ switch (playerEvent)
+ {
+ case PlayerAttackEventArgs attackEvent:
+ HandlePlayerAttackEvent(attackEvent);
+ break;
+ case PlayerMoveEventArgs moveEvent:
+ HandlePlayerMoveEvent(moveEvent);
+ break;
+ case PlayerPlaceEventArgs placeEvent:
+ HandlePlayerPlaceEvent(placeEvent);
+ break;
+ case PlayerDieEventArgs dieEvent:
+ HandlePlayerDieEvent(dieEvent);
+ break;
+ case PlayerTradeEventArgs tradeEvent:
+ HandlePlayerTradeEvent(tradeEvent);
+ break;
+
+ default:
+ _logger.Error($"Unknown event: {playerEvent}");
+ break;
+ }
+ }
+ }
+ }
+
+ void UpdatePlayerInfo()
+ {
+ for (int i = 0; i < PlayerNum; i++)
+ {
+ if (Players[i].HasBed == true
+ && GameMap.GetChunkAt(Players[i].SpawnPoint).IsVoid == true)
+ {
+ Players[i].DestroyBed();
+ }
+
+ if (Players[i].IsAlive == false && Players[i].HasBed == true
+ && ElapsedTicks - _playerDeathTickList[i] > TicksBeforeRespawn
+ && IsSamePosition(
+ ToIntPosition(Players[i].PlayerPosition), Players[i].SpawnPoint
+ ) == true)
+ {
+ Players[i].Spawn(Players[i].MaxHealth);
+ _playerDeathTickList[i] = null;
+
+ }
+
+ if (Players[i].IsAlive == true && IsValidPosition(
+ ToIntPosition(Players[i].PlayerPosition)) == false)
+ {
+ Players[i].Hurt(InstantDeathDamage);
+ }
+ else if (Players[i].IsAlive == true && GameMap.GetChunkAt(
+ ToIntPosition(Players[i].PlayerPosition)).IsVoid == true)
+ {
+ Players[i].Hurt(InstantDeathDamage);
+ }
+ }
+ }
+
+ ///
+ /// Update mines.
+ ///
+ void UpdateMines()
+ {
+ foreach (IMine mine in Mines)
+ {
+ if (CurrentStage == IGame.Stage.Running
+ && ElapsedTicks - mine.LastOreGeneratedTick >= mine.AccumulateOreInterval)
+ {
+ mine.GenerateOre(ElapsedTicks);
+ }
+
+ List existingPlayerId = new();
+ existingPlayerId.Clear();
+ for (int i = 0; i < PlayerNum; i++)
+ {
+ if (Players[i].IsAlive == true
+ && IsSamePosition(
+ ToIntPosition(Players[i].PlayerPosition), mine.Position
+ ) == true)
+ {
+ existingPlayerId.Add(Players[i].PlayerId);
+ }
+ }
+
+ // Collect ore only if there is just one player.
+ if (existingPlayerId.Count == 1)
+ {
+ int playerId = existingPlayerId[0];
+ //Remaining capacity of a player
+ int capacity = MaximumItemCount - Players[playerId].EmeraldCount;
+
+ //Value of an ore
+ int value = mine.OreKind switch
+ {
+ IMine.OreKindType.IronIngot => 1,
+ IMine.OreKindType.GoldIngot => 4,
+ IMine.OreKindType.Diamond => 16,
+ _ => throw new ArgumentOutOfRangeException(nameof(mine.OreKind), "No such ore kind.")
+ };
+
+ //Collected ore count
+ int collectedOre = Math.Min(capacity / value, mine.AccumulatedOreCount);
+
+ Players[playerId].EmeraldAdd(collectedOre * value);
+ // Invoke the event
+ Players[playerId].PickUpEventInvoker(mine.OreKind, collectedOre, mine.MineId.ToString());
+
+ mine.PickUpOre(collectedOre);
+ }
+ }
+ }
+
+ ///
+ /// Whether the game is finished or not.
+ ///
+ /// True if finished, false otherwise.
+ bool IsFinished()
+ {
+ int remainingPlayers = PlayerNum;
+ for (int i = 0; i < PlayerNum; i++)
+ {
+ if (Players[i].IsAlive == false && Players[i].HasBed == false)
+ {
+ remainingPlayers--;
+ }
+ }
+ return remainingPlayers <= 1;
+ }
+
+ ///
+ /// Judge the game. Choose a winner or report there is no winner.
+ ///
+ void Judge()
+ {
+ int remainingPlayers = 0;
+ for (int i = 0; i < PlayerNum; i++)
+ {
+ if (Players[i].IsAlive == true || Players[i].HasBed == true)
+ {
+ remainingPlayers++;
+ }
+ }
+
+ if (remainingPlayers == 0 || remainingPlayers > 1)
+ {
+ Winner = null;
+ }
+ else
+ {
+ for (int i = 0; i < PlayerNum; i++)
+ {
+ if (Players[i].IsAlive == true || Players[i].HasBed == true)
+ {
+ Winner = Players[i];
+ break;
+ }
+ }
+ }
+
+ AfterJudgementEvent?.Invoke(this, new AfterJudgementEventArgs(this, Winner));
+ }
+}
diff --git a/host/src/EdcHost/Games/GameRunner.cs b/host/src/EdcHost/Games/GameRunner.cs
new file mode 100644
index 0000000..485fefc
--- /dev/null
+++ b/host/src/EdcHost/Games/GameRunner.cs
@@ -0,0 +1,76 @@
+using System.Diagnostics;
+
+namespace EdcHost.Games;
+
+class GameRunner : IGameRunner
+{
+ const int TicksPerSecondExpected = 20;
+
+ public bool IsRunning { get; private set; } = false;
+
+ public double ActualTps => Game.CurrentStage is not IGame.Stage.Running ? 0 : 1000 / _lastTickDuration.TotalMilliseconds;
+ public IGame Game { get; }
+
+ TimeSpan _lastTickDuration = TimeSpan.MaxValue;
+ Task? _task = null;
+
+ public GameRunner(IGame game)
+ {
+ Game = game;
+ }
+
+ public void Start()
+ {
+ if (Game.CurrentStage is not IGame.Stage.Ready)
+ {
+ throw new InvalidOperationException($"Game is already at stage {Game.CurrentStage}");
+ }
+
+ IsRunning = true;
+
+ Game.Start();
+
+ _task = Task.Run(TaskFunc);
+ }
+
+ public void End()
+ {
+ if (Game.CurrentStage is not IGame.Stage.Running && Game.CurrentStage is not IGame.Stage.Battling)
+ {
+ throw new InvalidOperationException($"Game is already at stage {Game.CurrentStage}");
+ }
+
+ Debug.Assert(_task is not null);
+
+ Game.End();
+ IsRunning = false;
+ _task.Wait();
+ }
+
+ void TaskFunc()
+ {
+ DateTime lastTickStartTime = DateTime.Now;
+
+ while (IsRunning)
+ {
+ if (Game.CurrentStage is not IGame.Stage.Running && Game.CurrentStage is not IGame.Stage.Battling)
+ {
+ break;
+ }
+
+ // Wait for next tick
+ DateTime currentTickStartTime = lastTickStartTime.AddMilliseconds((double)1000 / TicksPerSecondExpected);
+ if (currentTickStartTime > DateTime.Now)
+ {
+ Task.Delay(currentTickStartTime - DateTime.Now).Wait();
+ }
+ currentTickStartTime = DateTime.Now;
+
+ _lastTickDuration = DateTime.Now - lastTickStartTime;
+
+ Game.Tick();
+
+ lastTickStartTime = currentTickStartTime;
+ }
+ }
+}
diff --git a/host/src/EdcHost/Games/IChunk.cs b/host/src/EdcHost/Games/IChunk.cs
new file mode 100644
index 0000000..57c2846
--- /dev/null
+++ b/host/src/EdcHost/Games/IChunk.cs
@@ -0,0 +1,49 @@
+namespace EdcHost.Games;
+
+public interface IChunk
+{
+ static IChunk Create(int height, IPosition position)
+ {
+ return new Chunk(height, position);
+ }
+
+ ///
+ /// Whether a block can be placed in the chunk.
+ ///
+ bool CanPlaceBlock { get; }
+ ///
+ /// Whether a block can be removed from the chunk.
+ ///
+ bool CanRemoveBlock { get; }
+ ///
+ /// The height of the chunk.
+ ///
+ int Height { get; }
+ ///
+ /// Whether the chunk is void.
+ ///
+ bool IsVoid { get; }
+ ///
+ /// The position of the chunk.
+ ///
+ IPosition Position { get; }
+ ///
+ /// Which kind of ore the chunk owns.
+ ///
+ IMine.OreKindType OwningOreKind { get; set; }
+
+ ///
+ /// Places a block in the chunk.
+ ///
+ ///
+ /// Thrown when the chunk cannot have a block placed in it.
+ ///
+ void PlaceBlock();
+ ///
+ /// Removes a block from the chunk.
+ ///
+ ///
+ /// Thrown when the chunk cannot have a block removed from it.
+ ///
+ void RemoveBlock();
+}
diff --git a/host/src/EdcHost/Games/IGame.cs b/host/src/EdcHost/Games/IGame.cs
new file mode 100644
index 0000000..ada5582
--- /dev/null
+++ b/host/src/EdcHost/Games/IGame.cs
@@ -0,0 +1,78 @@
+namespace EdcHost.Games;
+
+///
+/// Game handles the game logic.
+///
+public interface IGame
+{
+ static IGame Create(List>? diamondMines = null,
+ List>? goldMines = null, List>? ironMines = null)
+ {
+ return new Game(
+ diamondMines: diamondMines,
+ goldMines: goldMines,
+ ironMines: ironMines
+ );
+ }
+
+ ///
+ /// Stage of game.
+ ///
+ enum Stage
+ {
+ Ready,
+ Running,
+ Battling,
+ Finished,
+ }
+
+ event EventHandler? AfterGameStartEvent;
+ event EventHandler? AfterGameTickEvent;
+ event EventHandler? AfterJudgementEvent;
+
+ ///
+ /// Current stage of the game.
+ ///
+ Stage CurrentStage { get; }
+
+ ///
+ /// Elapsed time of the game.
+ ///
+ int ElapsedTicks { get; }
+
+ ///
+ /// Winner of the game.
+ ///
+ ///
+ /// Winner can be null in case there is no winner.
+ ///
+ IPlayer? Winner { get; }
+
+ ///
+ /// The players.
+ ///
+ List Players { get; }
+
+ ///
+ /// The game map.
+ ///
+ IMap GameMap { get; }
+
+ ///
+ /// The mines.
+ ///
+ List Mines { get; }
+
+ ///
+ /// Starts the game.
+ ///
+ void Start();
+
+ ///
+ /// Ends the game.
+ ///
+ void End();
+
+ void Tick();
+
+}
diff --git a/host/src/EdcHost/Games/IGameRunner.cs b/host/src/EdcHost/Games/IGameRunner.cs
new file mode 100644
index 0000000..a825cb9
--- /dev/null
+++ b/host/src/EdcHost/Games/IGameRunner.cs
@@ -0,0 +1,17 @@
+namespace EdcHost.Games;
+
+public interface IGameRunner
+{
+ static IGameRunner Create(IGame game)
+ {
+ return new GameRunner(game);
+ }
+
+ double ActualTps { get; }
+ IGame Game { get; }
+
+ void Start();
+ void End();
+
+ bool IsRunning { get; }
+}
diff --git a/host/src/EdcHost/Games/IMap.cs b/host/src/EdcHost/Games/IMap.cs
new file mode 100644
index 0000000..1aba90e
--- /dev/null
+++ b/host/src/EdcHost/Games/IMap.cs
@@ -0,0 +1,24 @@
+namespace EdcHost.Games;
+
+///
+/// Map represents the map of the game.
+///
+public interface IMap
+{
+ static IMap Create(IPosition[] spawnPoints)
+ {
+ return new Map(spawnPoints);
+ }
+
+ ///
+ /// The list of chunks.
+ ///
+ List Chunks { get; }
+
+ ///
+ /// Gets the chunk at the position.
+ ///
+ ///
+ ///
+ IChunk GetChunkAt(IPosition position);
+}
diff --git a/host/src/EdcHost/Games/IMine.cs b/host/src/EdcHost/Games/IMine.cs
new file mode 100644
index 0000000..01752de
--- /dev/null
+++ b/host/src/EdcHost/Games/IMine.cs
@@ -0,0 +1,63 @@
+namespace EdcHost.Games;
+
+///
+/// Mine represents a mine in the game.
+///
+public interface IMine
+{
+ static IMine Create(OreKindType oreKind, IPosition position, int tick)
+ {
+ return new Mine(oreKind, position, tick);
+ }
+
+ ///
+ /// The ore kind.
+ ///
+ enum OreKindType
+ {
+ IronIngot = 0,
+ GoldIngot = 1,
+ Diamond = 2,
+ None = 3
+ }
+ ///
+ /// The id of the mine
+ ///
+ Guid MineId { get; }
+
+ ///
+ /// The count of accumulated ores.
+ ///
+ int AccumulatedOreCount { get; }
+
+ ///
+ /// The kind of the ore.
+ ///
+ OreKindType OreKind { get; }
+
+ ///
+ /// The position of the mine.
+ ///
+ IPosition Position { get; }
+
+ ///
+ /// How much time required to generate ore.
+ ///
+ int AccumulateOreInterval { get; }
+
+ ///
+ /// Last time ore generated.
+ ///
+ int LastOreGeneratedTick { get; }
+
+ ///
+ /// Picks up some ore.
+ ///
+ /// The count of ore to pick up.
+ void PickUpOre(int count);
+
+ ///
+ /// Generate ore automaticly.
+ ///
+ void GenerateOre(int tick);
+}
diff --git a/host/src/EdcHost/Games/IPlayer.cs b/host/src/EdcHost/Games/IPlayer.cs
new file mode 100644
index 0000000..087f230
--- /dev/null
+++ b/host/src/EdcHost/Games/IPlayer.cs
@@ -0,0 +1,109 @@
+namespace EdcHost.Games;
+
+///
+/// Player represents a player in the game.
+///
+public interface IPlayer
+{
+ static IPlayer Create(int id = 1, int spawnX = 0, int spawnY = 0, float x = 0, float y = 0)
+ {
+ return new Player(id, spawnX, spawnY, x, y);
+ }
+
+ ///
+ /// The kind of a commodity.
+ ///
+ enum CommodityKindType
+ {
+ AgilityBoost,
+ HealthBoost,
+ HealthPotion,
+ StrengthBoost,
+ Wool,
+ }
+
+ ///
+ /// The kind of an action.
+ ///
+ enum ActionKindType
+ {
+ Attack,
+ PlaceBlock
+
+ }
+
+ ///
+ /// Triggered when the player moves.
+ ///
+ event EventHandler OnMove;
+ event EventHandler OnAttack;
+ event EventHandler OnPlace;
+ event EventHandler OnDie;
+ event EventHandler OnDig;
+ event EventHandler OnPickUp;
+ event EventHandler OnTrade;
+
+ void EmeraldAdd(int count);
+ void Move(float newX, float newY);
+ void Attack(int newX, int newY);
+ void Place(int newX, int newY);
+ void Hurt(int EnemyStrength);
+ void Spawn(int MaxHealth);
+ void DestroyBed();
+ void DestroyBedOpponent();
+ void DecreaseWoolCount();
+ void DigEventInvoker(int targetChunk);
+ void PickUpEventInvoker(IMine.OreKindType mineType, int count, string mineId);
+
+ ///
+ /// The Id of the player
+ ///
+ int PlayerId { get; }
+ ///
+ /// The count of emeralds the player has.
+ ///
+ int EmeraldCount { get; }
+ ///
+ /// Whether the player is alive.
+ ///
+ bool IsAlive { get; }
+ ///
+ /// Whether the player has a bed.
+ ///
+ bool HasBed { get; }
+ ///
+ /// Whether the player has a bed.
+ ///
+ bool HasBedOpponent { get; }
+ ///
+ /// The spawn point of the player.
+ ///
+ IPosition SpawnPoint { get; }
+ ///
+ /// The position of the player.
+ ///
+ IPosition PlayerPosition { get; }
+ ///
+ /// The count of wool blocks the player has.
+ ///
+ int WoolCount { get; }
+ int Health { get; }
+ int MaxHealth { get; }
+ int Strength { get; }
+ int ActionPoints { get; }
+ ///
+ /// Performs an action.
+ ///
+ /// The action kind.
+ void PerformActionPosition(ActionKindType actionKind, int X, int Y);
+ ///
+ /// Send a trade request.
+ ///
+ /// The commodity kind.
+ void SendTradeRequest(CommodityKindType commodityKind);
+ ///
+ /// Trades a commodity.
+ ///
+ /// The commodity kind.
+ bool Trade(CommodityKindType commodityKind);
+}
diff --git a/host/src/EdcHost/Games/IPosition.cs b/host/src/EdcHost/Games/IPosition.cs
new file mode 100644
index 0000000..e275440
--- /dev/null
+++ b/host/src/EdcHost/Games/IPosition.cs
@@ -0,0 +1,20 @@
+namespace EdcHost.Games;
+
+///
+/// Position represents a position in 2D space.
+///
+/// The type of the position.
+public interface IPosition
+{
+ static IPosition Create(T x, T y) => new Position(x, y);
+
+ ///
+ /// The X coordinate of the position.
+ ///
+ T X { get; set; }
+
+ ///
+ /// The Y coordinate of the position.
+ ///
+ T Y { get; set; }
+}
diff --git a/host/src/EdcHost/Games/Map.cs b/host/src/EdcHost/Games/Map.cs
new file mode 100644
index 0000000..4801abd
--- /dev/null
+++ b/host/src/EdcHost/Games/Map.cs
@@ -0,0 +1,69 @@
+namespace EdcHost.Games;
+
+///
+/// Map represents the map of the game.
+///
+class Map : IMap
+{
+
+ ///
+ /// Total count of chunks.
+ ///
+ const int TotalChunkCount = 64;
+
+ ///
+ /// Maximum value of x coordinate.
+ ///
+ ///
+ /// A valid value of x coordinate must be strictly greater than MaxX.
+ /// Equal is not allowed.
+ ///
+ const int MaxX = 8;
+
+ ///
+ /// Maximum value of y coordinate.
+ ///
+ ///
+ /// A valid value of y coordinate must be strictly greater than MaxY.
+ /// Equal is not allowed.
+ ///
+ const int MaxY = 8;
+
+ ///
+ /// The list of chunks.
+ ///
+ public List Chunks { get; }
+
+ ///
+ /// Constructor
+ ///
+ public Map(IPosition[] spawnPoints)
+ {
+ Chunks = new();
+ for (int y = 0; y < MaxY; y++)
+ {
+ for (int x = 0; x < MaxX; x++)
+ {
+ Chunks.Add(new Chunk(0, new Position(x, y)));
+ }
+ }
+ foreach (IPosition spawnPoint in spawnPoints)
+ {
+ Chunks[MaxX * spawnPoint.Y + spawnPoint.X] = new Chunk(1, spawnPoint);
+ }
+ }
+
+ ///
+ /// Gets the chunk at the position.
+ ///
+ /// The position
+ /// The chunk
+ public IChunk GetChunkAt(IPosition position)
+ {
+ if (position.X < 0 || position.X >= MaxX || position.Y < 0 || position.Y >= MaxY)
+ {
+ throw new ArgumentException("No such chunk.");
+ }
+ return Chunks[MaxX * position.Y + position.X];
+ }
+}
diff --git a/host/src/EdcHost/Games/Mine.cs b/host/src/EdcHost/Games/Mine.cs
new file mode 100644
index 0000000..759f91d
--- /dev/null
+++ b/host/src/EdcHost/Games/Mine.cs
@@ -0,0 +1,74 @@
+namespace EdcHost.Games;
+
+///
+/// Mine represents a mine in the game.
+///
+class Mine : IMine
+{
+ ///
+ /// The id of the mine
+ ///
+ public Guid MineId { get; }
+
+ ///
+ /// The count of accumulated ores.
+ ///
+ public int AccumulatedOreCount { get; private set; }
+
+ ///
+ /// The kind of the ore.
+ ///
+ public IMine.OreKindType OreKind { get; }
+
+ ///
+ /// The position of the mine.
+ ///
+ public IPosition Position { get; }
+
+ public int AccumulateOreInterval
+ {
+ get => 10 * Game.TicksPerSecondExpected;
+ }
+
+ ///
+ /// Last time ore generated.
+ ///
+ public int LastOreGeneratedTick { get; private set; }
+
+ ///
+ /// Constructor
+ ///
+ /// The ore kind
+ /// The position
+ public Mine(IMine.OreKindType oreKind, IPosition position, int tick)
+ {
+ MineId = Guid.NewGuid();
+ AccumulatedOreCount = 0;
+ OreKind = oreKind;
+ Position = position;
+ LastOreGeneratedTick = tick;
+ }
+
+ ///
+ /// Picks up some ore.
+ ///
+ /// The count of ore to pick up.
+ public void PickUpOre(int count)
+ {
+ if (AccumulatedOreCount < count)
+ {
+ throw new InvalidOperationException("No enough ore.");
+ }
+ AccumulatedOreCount -= count;
+ }
+
+ ///
+ /// Generate ore automaticly.
+ ///
+ public void GenerateOre(int tick)
+ {
+ AccumulatedOreCount++;
+ LastOreGeneratedTick = tick;
+ }
+
+}
diff --git a/host/src/EdcHost/Games/Player.cs b/host/src/EdcHost/Games/Player.cs
new file mode 100644
index 0000000..7afa414
--- /dev/null
+++ b/host/src/EdcHost/Games/Player.cs
@@ -0,0 +1,211 @@
+namespace EdcHost.Games;
+
+class Player : IPlayer
+{
+ const int InitialEmeraldCount = 0;
+ const int InitialWoolCount = 8;
+ const int InitialHealth = 20;
+ const int InitialMaxHealth = 20;
+ const int InitialStrength = 1;
+ const int InitialAgility = 0;
+ public int PlayerId { get; private set; }
+ public int EmeraldCount { get; private set; }
+ public bool HasBed { get; private set; }
+ public bool HasBedOpponent { get; private set; }
+ public bool IsAlive { get; private set; }
+ public IPosition SpawnPoint { get; private set; }
+ public IPosition PlayerPosition { get; private set; }
+ public int WoolCount { get; private set; }
+
+ public int Health { get; private set; } /// Health property
+ public int MaxHealth { get; private set; } /// Max health property
+ public int Strength { get; private set; } /// Strength property
+ public int ActionPoints { get; private set; } /// Action points property
+
+ public event EventHandler OnMove = delegate { };
+ public event EventHandler OnAttack = delegate { };
+ public event EventHandler OnPlace = delegate { };
+ public event EventHandler OnDie = delegate { };
+
+ public event EventHandler OnDig = delegate { };
+ public event EventHandler OnPickUp = delegate { };
+ public event EventHandler OnTrade = delegate { };
+
+ public void PickUpEventInvoker(IMine.OreKindType mineType, int count, string mineId)
+ {
+ OnPickUp?.Invoke(this, new PlayerPickUpEventArgs(this, mineType, count, mineId));
+ }
+ public void DigEventInvoker(int targetChunk)
+ {
+ OnDig?.Invoke(this, new PlayerDigEventArgs(this, targetChunk));
+ }
+
+ public void EmeraldAdd(int count)
+ {
+ /// update the player's Emeraldcount
+ EmeraldCount += count;
+ }
+
+ public void Move(float newX, float newY)
+ {
+ /// Trigger the OnMove event to notify other parts that the player has moved
+ OnMove?.Invoke(this, new PlayerMoveEventArgs(this, PlayerPosition, new Position(newX, newY)));
+ /// Update the player's position information
+ PlayerPosition.X = newX;
+ PlayerPosition.Y = newY;
+ }
+
+ public void Attack(int newX, int newY)
+ {
+ /// Trigger the OnAttack event to notify the attacked block
+ OnAttack?.Invoke(this, new PlayerAttackEventArgs(this, Strength, new Position(newX, newY)));
+ }
+ public void Place(int newX, int newY)
+ {
+ /// Check if the player has wool in their inventory, and if so, process wool data.
+ /// Trigger the OnPlace event to notify the placed block
+ if (WoolCount > 0)
+ {
+ OnPlace?.Invoke(this, new PlayerPlaceEventArgs(this, new Position(newX, newY)));
+ }
+ }
+ public void Hurt(int EnemyStrength)
+ {
+ /// Implement the logic for being hurt
+ if (Health > EnemyStrength)
+ {
+ Health -= EnemyStrength;
+ }
+ else
+ {
+ Health = 0;
+ IsAlive = false;
+ OnDie?.Invoke(this, new PlayerDieEventArgs(this));
+ }
+ }
+ public void Spawn(int MaxHealth)
+ {
+ if (HasBed == true)
+ {
+ IsAlive = true;
+ Health = MaxHealth;
+ ///
+ /// SpawnPoint should not change.
+ ///
+ }
+ }
+ public void DestroyBed()
+ {
+ /// Destroy a player's bed.
+ HasBed = false;
+ }
+ public void DestroyBedOpponent()
+ {
+ /// Destroy a player's bed.
+ HasBedOpponent = false;
+ }
+ public void DecreaseWoolCount()
+ {
+ /// Decrease wool count by 1.
+ WoolCount -= 1;
+ }
+ public Player(int id = 1, int spawnPointX = 0, int spawnPointY = 0, float X = 0, float Y = 0)
+ {
+ PlayerId = id;
+ IsAlive = true;
+ HasBed = true;
+ HasBedOpponent = true;
+ SpawnPoint = new Position(spawnPointX, spawnPointY);
+ PlayerPosition = new Position(X, Y);
+
+ EmeraldCount = InitialEmeraldCount;
+ WoolCount = InitialWoolCount;
+
+ Health = InitialHealth; /// Initial health
+ MaxHealth = InitialMaxHealth; /// Initial max health
+ Strength = InitialStrength; /// Initial strength
+ ActionPoints = InitialAgility; /// Initial action points
+ }
+ public void PerformActionPosition(IPlayer.ActionKindType actionKind, int X, int Y)
+ {
+ switch (actionKind)
+ {
+ case IPlayer.ActionKindType.Attack:
+ /// Implement the logic for attacking
+ Attack(X, Y);
+ break;
+ case IPlayer.ActionKindType.PlaceBlock:
+ /// Implement the logic for placing a block
+ Place(X, Y);
+ break;
+ default:
+ /// Handle unknown action types
+ break;
+ }
+ }
+ public void SendTradeRequest(IPlayer.CommodityKindType commodityKind)
+ {
+ OnTrade?.Invoke(this, new PlayerTradeEventArgs(this, commodityKind));
+ }
+ public bool Trade(IPlayer.CommodityKindType commodityKind)
+ {
+ int price = commodityKind switch
+ {
+ IPlayer.CommodityKindType.AgilityBoost => 32,
+ IPlayer.CommodityKindType.HealthBoost => 32,
+ IPlayer.CommodityKindType.StrengthBoost => 64,
+ IPlayer.CommodityKindType.Wool => 2,
+ IPlayer.CommodityKindType.HealthPotion => 4,
+ _ => throw new ArgumentOutOfRangeException(
+ $"No commodity {commodityKind}."
+ )
+ };
+
+ if (EmeraldCount < price)
+ {
+ Serilog.Log.Error(
+ $"Failed to trade: Player {PlayerId} doesn't have enough emerald."
+ );
+ return false;
+ }
+
+ switch (commodityKind)
+ {
+ case IPlayer.CommodityKindType.AgilityBoost:
+ EmeraldCount -= price;
+ ActionPoints += 1;
+ return true;
+ case IPlayer.CommodityKindType.HealthBoost:
+ EmeraldCount -= price;
+ MaxHealth += 3;
+ Health += 3;
+ return true;
+ case IPlayer.CommodityKindType.HealthPotion:
+ EmeraldCount -= price;
+ if (Health < MaxHealth)
+ {
+ Health += 1;
+ }
+ return true;
+ case IPlayer.CommodityKindType.StrengthBoost:
+ EmeraldCount -= price;
+ Strength += 1;
+ return true;
+ case IPlayer.CommodityKindType.Wool:
+ if (WoolCount >= Game.MaximumItemCount)
+ {
+ Serilog.Log.Error(
+ $"Failed to trade: Player {PlayerId} cannot hold more wools."
+ );
+ return false;
+ }
+ EmeraldCount -= price;
+ WoolCount += 1;
+ return true;
+ default:
+ throw new ArgumentOutOfRangeException(
+ $"No commodity {commodityKind}."
+ );
+ }
+ }
+}
diff --git a/host/src/EdcHost/Games/Position.cs b/host/src/EdcHost/Games/Position.cs
new file mode 100644
index 0000000..3446f7b
--- /dev/null
+++ b/host/src/EdcHost/Games/Position.cs
@@ -0,0 +1,30 @@
+namespace EdcHost.Games;
+
+///
+/// Position represents a position in 2D space.
+///
+/// The type of the position.
+struct Position : IPosition
+{
+ ///
+ /// The X coordinate of the position.
+ ///
+ public T X { get; set; }
+
+ ///
+ /// The Y coordinate of the position.
+ ///
+ public T Y { get; set; }
+
+ ///
+ /// Constructor
+ ///
+ /// The x coordinate
+ /// The y coordinate
+ public Position(T x, T y)
+ {
+ X = x;
+ Y = y;
+ }
+
+}
diff --git a/host/src/EdcHost/IEdcHost.cs b/host/src/EdcHost/IEdcHost.cs
new file mode 100644
index 0000000..f14988b
--- /dev/null
+++ b/host/src/EdcHost/IEdcHost.cs
@@ -0,0 +1,19 @@
+namespace EdcHost;
+
+///
+/// EdcHost does all the work of the program.
+///
+public interface IEdcHost
+{
+ bool IsRunning { get; }
+
+ ///
+ /// Starts the host.
+ ///
+ void Start();
+
+ ///
+ /// Stops the host.
+ ///
+ void Stop();
+}
diff --git a/host/src/EdcHost/PlayerHardwareInfo.cs b/host/src/EdcHost/PlayerHardwareInfo.cs
new file mode 100644
index 0000000..6506718
--- /dev/null
+++ b/host/src/EdcHost/PlayerHardwareInfo.cs
@@ -0,0 +1,7 @@
+namespace EdcHost;
+
+public class PlayerHardwareInfo
+{
+ public string? PortName;
+ public int? CameraIndex;
+}
diff --git a/host/src/EdcHost/Program.cs b/host/src/EdcHost/Program.cs
new file mode 100644
index 0000000..80e7358
--- /dev/null
+++ b/host/src/EdcHost/Program.cs
@@ -0,0 +1,124 @@
+using System.Text.Json;
+using Serilog;
+using Serilog.Templates;
+using Serilog.Templates.Themes;
+
+namespace EdcHost;
+
+class Program
+{
+ const string SerilogTemplate = "[{@t:HH:mm:ss} {@l:u3}] {#if Component is not null}{Component,-13} {#end}{@m}\n{@x}";
+
+ static void Main()
+ {
+ // Setup logger using default settings before calling dotenv.
+ Log.Logger = new LoggerConfiguration()
+ .WriteTo.Console()
+ .CreateLogger();
+
+ Config config = LoadConfig();
+
+ SetupLogging(config.LoggingLevel);
+
+ Version version = typeof(Program).Assembly.GetName().Version ?? new Version(0, 0, 0, 0);
+ Log.Information($"EDCHost version: {version.Major}.{version.Minor}.{version.Build}");
+
+ SetupAndRunEdcHost(config);
+
+ // Wait forever
+ Task.Delay(-1).Wait();
+ }
+
+ static void SetupAndRunEdcHost(Config config)
+ {
+ IEdcHost edcHost = new EdcHost(config);
+
+ edcHost.Start();
+ }
+
+ static Config LoadConfig()
+ {
+ Config config = new();
+ string path = Path.Combine(Directory.GetCurrentDirectory(), "config.json");
+ if (!File.Exists(path))
+ {
+ Log.Warning($"Config file not found at {path}, creating default config file...");
+ File.WriteAllText(path, JsonSerializer.Serialize(config, new JsonSerializerOptions { WriteIndented = true }));
+ }
+ else
+ {
+ try
+ {
+ config = JsonSerializer.Deserialize(File.ReadAllText(path))!;
+ }
+ catch (JsonException)
+ {
+ Log.Error($"Error parsing config file at {path}");
+
+#if DEBUG
+ throw;
+#else
+ Log.Information($"Using default config.");
+#endif
+ }
+ }
+
+ return config;
+ }
+
+ static void SetupLogging(string loggingLevelString)
+ {
+ // Configure Serilog
+ Log.Logger = loggingLevelString switch
+ {
+ "Verbose" => new LoggerConfiguration()
+ .MinimumLevel.Verbose()
+ .WriteTo.Console(new ExpressionTemplate(SerilogTemplate, theme: TemplateTheme.Literate))
+ .CreateLogger(),
+ "Debug" => new LoggerConfiguration()
+ .MinimumLevel.Debug()
+ .WriteTo.Console(new ExpressionTemplate(SerilogTemplate, theme: TemplateTheme.Literate))
+ .CreateLogger(),
+ "Information" => new LoggerConfiguration()
+ .MinimumLevel.Information()
+ .WriteTo.Console(new ExpressionTemplate(SerilogTemplate, theme: TemplateTheme.Literate))
+ .CreateLogger(),
+ "Warning" => new LoggerConfiguration()
+ .MinimumLevel.Warning()
+ .WriteTo.Console(new ExpressionTemplate(SerilogTemplate, theme: TemplateTheme.Literate))
+ .CreateLogger(),
+ "Error" => new LoggerConfiguration()
+ .MinimumLevel.Error()
+ .WriteTo.Console(new ExpressionTemplate(SerilogTemplate, theme: TemplateTheme.Literate))
+ .CreateLogger(),
+ "Fatal" => new LoggerConfiguration()
+ .MinimumLevel.Fatal()
+ .WriteTo.Console(new ExpressionTemplate(SerilogTemplate, theme: TemplateTheme.Literate))
+ .CreateLogger(),
+ _ => throw new ArgumentOutOfRangeException(nameof(loggingLevelString), loggingLevelString, "invalid logging level")
+ };
+
+ // Configure Fleck logging
+ ILogger fleckLogger = Log.Logger.ForContext("Component", "Fleck");
+ Fleck.FleckLog.LogAction = (level, message, ex) =>
+ {
+ switch (level)
+ {
+ case Fleck.LogLevel.Debug:
+ fleckLogger.Debug(message, ex);
+ break;
+ case Fleck.LogLevel.Info:
+ fleckLogger.Information(message, ex);
+ break;
+ case Fleck.LogLevel.Warn:
+ fleckLogger.Warning(message, ex);
+ break;
+ case Fleck.LogLevel.Error:
+ fleckLogger.Error(message, ex);
+ break;
+ }
+ };
+
+ Log.Information($"logging level set to {loggingLevelString}");
+ }
+}
diff --git a/host/src/EdcHost/SlaveServers/ActionKind.cs b/host/src/EdcHost/SlaveServers/ActionKind.cs
new file mode 100644
index 0000000..7e7a833
--- /dev/null
+++ b/host/src/EdcHost/SlaveServers/ActionKind.cs
@@ -0,0 +1,8 @@
+namespace EdcHost.SlaveServers;
+
+enum ActionKind
+{
+ Attack = 0,
+ Use,
+ Trade,
+}
diff --git a/host/src/EdcHost/SlaveServers/EventArgs/PlayerTryAttackEventArgs.cs b/host/src/EdcHost/SlaveServers/EventArgs/PlayerTryAttackEventArgs.cs
new file mode 100644
index 0000000..1afccd4
--- /dev/null
+++ b/host/src/EdcHost/SlaveServers/EventArgs/PlayerTryAttackEventArgs.cs
@@ -0,0 +1,13 @@
+namespace EdcHost.SlaveServers;
+
+public class PlayerTryAttackEventArgs : System.EventArgs
+{
+ public string PortName { get; }
+ public int TargetChunkId { get; }
+
+ public PlayerTryAttackEventArgs(string portName, int targetChunkId)
+ {
+ PortName = portName;
+ TargetChunkId = targetChunkId;
+ }
+}
diff --git a/host/src/EdcHost/SlaveServers/EventArgs/PlayerTryPlaceBlockEventArgs.cs b/host/src/EdcHost/SlaveServers/EventArgs/PlayerTryPlaceBlockEventArgs.cs
new file mode 100644
index 0000000..9bbe656
--- /dev/null
+++ b/host/src/EdcHost/SlaveServers/EventArgs/PlayerTryPlaceBlockEventArgs.cs
@@ -0,0 +1,13 @@
+namespace EdcHost.SlaveServers;
+
+public class PlayerTryPlaceBlockEventArgs : System.EventArgs
+{
+ public string PortName { get; }
+ public int TargetChunkId { get; }
+
+ public PlayerTryPlaceBlockEventArgs(string portName, int targetChunkId)
+ {
+ PortName = portName;
+ TargetChunkId = targetChunkId;
+ }
+}
diff --git a/host/src/EdcHost/SlaveServers/EventArgs/PlayerTryTradeEventArgs.cs b/host/src/EdcHost/SlaveServers/EventArgs/PlayerTryTradeEventArgs.cs
new file mode 100644
index 0000000..ce76062
--- /dev/null
+++ b/host/src/EdcHost/SlaveServers/EventArgs/PlayerTryTradeEventArgs.cs
@@ -0,0 +1,13 @@
+namespace EdcHost.SlaveServers;
+
+public class PlayerTryTradeEventArgs : System.EventArgs
+{
+ public string PortName { get; }
+ public int Item { get; }
+
+ public PlayerTryTradeEventArgs(string portName, int item)
+ {
+ PortName = portName;
+ Item = item;
+ }
+}
diff --git a/host/src/EdcHost/SlaveServers/IPacket.cs b/host/src/EdcHost/SlaveServers/IPacket.cs
new file mode 100644
index 0000000..2a22c90
--- /dev/null
+++ b/host/src/EdcHost/SlaveServers/IPacket.cs
@@ -0,0 +1,78 @@
+namespace EdcHost.SlaveServers;
+
+public interface IPacket
+{
+ static byte CalculateChecksum(byte[] bytes)
+ {
+ byte checksum = 0x00;
+ foreach (byte byte_item in bytes)
+ {
+ checksum ^= byte_item;
+ }
+ return checksum;
+ }
+
+ ///
+ /// Generate the header of some data.
+ ///
+ /// The packet ID.
+ /// The data.
+ ///
+ static byte[] GeneratePacketHeader(byte[] data)
+ {
+ short dataLength = (short)data.Length;
+ byte checksum = IPacket.CalculateChecksum(data);
+
+ byte[] header = new byte[5];
+ header[0] = (byte)0x55;
+ header[1] = (byte)0xAA;
+ Array.Copy(BitConverter.GetBytes(dataLength), 0, header, 2, 2);
+ header[4] = checksum;
+
+ return header;
+ }
+
+ ///
+ /// Extract the data from a packet in raw byte array form.
+ ///
+ ///
+ /// The packet in raw byte array form.
+ ///
+ /// The data.
+ static byte[] GetPacketData(byte[] bytes)
+ {
+ // Validate the byte array
+ if (bytes.Length < 5)
+ {
+ throw new Exception("The header of the packet is broken.");
+ }
+
+ if (bytes[0] != 0x55 || bytes[1] != 0xAA)
+ {
+ throw new Exception("The header of the packet is broken.");
+ }
+
+ short dataLength = BitConverter.ToInt16(bytes, 2);
+ byte checksum = bytes[4];
+
+ if (bytes.Length < dataLength + 5)
+ {
+ throw new Exception("The data length of the packet is incorrect.");
+ }
+
+ byte[] data = new byte[dataLength];
+ Array.Copy(bytes, 5, data, 0, dataLength);
+
+ if (checksum != CalculateChecksum(data))
+ {
+ throw new Exception("The data of the packet is broken.");
+ }
+
+ return data;
+ }
+
+ ///
+ /// Get the data from the byte array without header to the packet object
+ ///
+ byte[] ToBytes();
+}
diff --git a/host/src/EdcHost/SlaveServers/IPacketFromHost.cs b/host/src/EdcHost/SlaveServers/IPacketFromHost.cs
new file mode 100644
index 0000000..75a90a9
--- /dev/null
+++ b/host/src/EdcHost/SlaveServers/IPacketFromHost.cs
@@ -0,0 +1,20 @@
+namespace EdcHost.SlaveServers;
+
+public interface IPacketFromHost : IPacket
+{
+ public int GameStage { get; }
+ public int ElapsedTime { get; }
+ public List InformationOfChunks { get; }
+ public bool HasBed { get; }
+ public bool HasBedOpponent { get; }
+ public float PositionX { get; }
+ public float PositionY { get; }
+ public float PositionOpponentX { get; }
+ public float PositionOpponentY { get; }
+ public int Agility { get; }
+ public int Health { get; }
+ public int MaxHealth { get; }
+ public int Strength { get; }
+ public int EmeraldCount { get; }
+ public int WoolCount { get; }
+}
diff --git a/host/src/EdcHost/SlaveServers/IPacketFromSlave.cs b/host/src/EdcHost/SlaveServers/IPacketFromSlave.cs
new file mode 100644
index 0000000..5a3b391
--- /dev/null
+++ b/host/src/EdcHost/SlaveServers/IPacketFromSlave.cs
@@ -0,0 +1,7 @@
+namespace EdcHost.SlaveServers;
+
+public interface IPacketFromSlave : IPacket
+{
+ public int ActionType { get; }
+ public int Param { get; }
+}
diff --git a/host/src/EdcHost/SlaveServers/ISerialPortHub.cs b/host/src/EdcHost/SlaveServers/ISerialPortHub.cs
new file mode 100644
index 0000000..533cc45
--- /dev/null
+++ b/host/src/EdcHost/SlaveServers/ISerialPortHub.cs
@@ -0,0 +1,8 @@
+namespace EdcHost.SlaveServers;
+
+public interface ISerialPortHub
+{
+ List PortNames { get; }
+
+ ISerialPortWrapper Get(string portName, int baudRate);
+}
diff --git a/host/src/EdcHost/SlaveServers/ISerialPortWrapper.cs b/host/src/EdcHost/SlaveServers/ISerialPortWrapper.cs
new file mode 100644
index 0000000..15475ac
--- /dev/null
+++ b/host/src/EdcHost/SlaveServers/ISerialPortWrapper.cs
@@ -0,0 +1,25 @@
+namespace EdcHost.SlaveServers;
+
+public interface ISerialPortWrapper : IDisposable
+{
+ class AfterReceiveEventArgs : EventArgs
+ {
+ public byte[] Bytes { get; }
+ public string PortName { get; }
+
+ public AfterReceiveEventArgs(string portName, byte[] bytes)
+ {
+ PortName = portName;
+ Bytes = bytes;
+ }
+ }
+
+ event EventHandler AfterReceive;
+
+ string PortName { get; }
+ int BaudRate { get; }
+
+ void Close();
+ void Open();
+ void Send(byte[] bytes);
+}
diff --git a/host/src/EdcHost/SlaveServers/ISlaveServer.cs b/host/src/EdcHost/SlaveServers/ISlaveServer.cs
new file mode 100644
index 0000000..280bf05
--- /dev/null
+++ b/host/src/EdcHost/SlaveServers/ISlaveServer.cs
@@ -0,0 +1,66 @@
+namespace EdcHost.SlaveServers;
+
+///
+/// SlaveServer handles the communication with the slaves via UART.
+///
+public interface ISlaveServer : IDisposable
+{
+ static ISlaveServer Create()
+ {
+ ISerialPortHub serialPortHub = new SerialPortHub();
+
+ return new SlaveServer(serialPortHub);
+ }
+
+ public record PortInfo
+ {
+ public int BaudRate { get; init; } = 0;
+ }
+
+ event EventHandler? PlayerTryAttackEvent;
+ event EventHandler? PlayerTryPlaceBlockEvent;
+ event EventHandler? PlayerTryTradeEvent;
+
+ ///
+ /// Gets the available port names.
+ ///
+ List AvailablePortNames { get; }
+
+ List OpenPortNames { get; }
+
+ ///
+ /// Starts the server.
+ ///
+ void Start();
+
+ ///
+ /// Stops the server.
+ ///
+ void Stop();
+
+ void OpenPort(string portName, int baudRate);
+
+ void ClosePort(string portName);
+
+ PortInfo? GetPortInfo(string portName);
+
+ void Publish(
+ string portName,
+ int gameStage,
+ int elapsedTime,
+ List heightOfChunks,
+ bool hasBed,
+ bool hasBedOpponent,
+ double positionX,
+ double positionY,
+ double positionOpponentX,
+ double positionOpponentY,
+ int agility,
+ int health,
+ int maxHealth,
+ int strength,
+ int emeraldCount,
+ int woolCount,
+ List owningOreKindOfChunks
+ );
+}
diff --git a/host/src/EdcHost/SlaveServers/ItemKind.cs b/host/src/EdcHost/SlaveServers/ItemKind.cs
new file mode 100644
index 0000000..31c27f2
--- /dev/null
+++ b/host/src/EdcHost/SlaveServers/ItemKind.cs
@@ -0,0 +1,10 @@
+namespace EdcHost.SlaveServers;
+
+enum ItemKind
+{
+ AgilityBoost = 0,
+ HealthBoost,
+ StrengthBoost,
+ Wool,
+ PotionOfHealing
+}
diff --git a/host/src/EdcHost/SlaveServers/PacketFromHost.cs b/host/src/EdcHost/SlaveServers/PacketFromHost.cs
new file mode 100644
index 0000000..b3f48a2
--- /dev/null
+++ b/host/src/EdcHost/SlaveServers/PacketFromHost.cs
@@ -0,0 +1,199 @@
+namespace EdcHost.SlaveServers;
+
+public class PacketFromHost : IPacketFromHost
+{
+ const int ChunkCount = 64;
+
+ public int GameStage { get; private set; }
+ public int ElapsedTime { get; private set; }
+ public List InformationOfChunks { get; private set; } = new();
+ public bool HasBed { get; private set; }
+ public bool HasBedOpponent { get; private set; }
+ public float PositionX { get; private set; }
+ public float PositionY { get; private set; }
+ public float PositionOpponentX { get; private set; }
+ public float PositionOpponentY { get; private set; }
+ public int Agility { get; private set; }
+ public int Health { get; private set; }
+ public int MaxHealth { get; private set; }
+ public int Strength { get; private set; }
+ public int EmeraldCount { get; private set; }
+ public int WoolCount { get; private set; }
+
+ public PacketFromHost(byte[] bytes)
+ {
+ int datalength = (
+ 1 + // GameStage
+ 4 + // ElapsedTime
+ 1 * ChunkCount + // InformationOfChunks
+ 1 + // HasBed
+ 1 + // HasBedOpponet
+ 4 * 4 + // Position
+ 1 * 6 //agility health maxHealth strength emeraldCount woolCount
+ );
+
+ if (bytes.Length != datalength + 5)
+ {
+ throw new ArgumentException("bytes.Length != datalength + 5");
+ }
+
+ byte[] data = IPacket.GetPacketData(bytes);
+ byte dataChecksum = IPacket.CalculateChecksum(data);
+ byte checksum = bytes[4];
+
+ if (dataChecksum != checksum)
+ {
+ throw new ArgumentException("dataChecksum != checksum");
+ }
+
+ int currentIndex = 0;
+
+ GameStage = Convert.ToInt32(data[currentIndex++]);
+ ElapsedTime = BitConverter.ToInt32(data, currentIndex);
+ currentIndex += 4;
+
+ for (int i = 0; i < 64; i++)
+ {
+ InformationOfChunks.Add(Convert.ToInt32(data[currentIndex++]));
+ }
+
+ HasBed = Convert.ToBoolean(data[currentIndex++]);
+ HasBedOpponent = Convert.ToBoolean(data[currentIndex++]);
+
+ PositionX = BitConverter.ToSingle(data, currentIndex);
+ currentIndex += 4;
+ PositionY = BitConverter.ToSingle(data, currentIndex);
+ currentIndex += 4;
+
+ PositionOpponentX = BitConverter.ToSingle(data, currentIndex);
+ currentIndex += 4;
+ PositionOpponentY = BitConverter.ToSingle(data, currentIndex);
+ currentIndex += 4;
+
+ Agility = Convert.ToInt32(data[currentIndex++]);
+ Health = Convert.ToInt32(data[currentIndex++]);
+ MaxHealth = Convert.ToInt32(data[currentIndex++]);
+ Strength = Convert.ToInt32(data[currentIndex++]);
+ EmeraldCount = Convert.ToInt32(data[currentIndex++]);
+ WoolCount = Convert.ToInt32(data[currentIndex++]);
+ }
+
+ public PacketFromHost(
+ int gameStage, int elapsedTime, List heightOfChunks, bool hasBed, bool hasBedOpponent,
+ float positionX, float positionY, float positionOpponentX, float positionOpponentY,
+ int agility, int health, int maxHealth, int strength,
+ int emeraldCount, int woolCount, List owningOreKindOfChunks
+ )
+ {
+ if (heightOfChunks.Count != ChunkCount)
+ {
+ throw new ArgumentException("heightOfChunks.Count != ChunkCount");
+ }
+
+ GameStage = gameStage;
+ ElapsedTime = elapsedTime;
+
+ InformationOfChunks = new(heightOfChunks);
+ for (int i = 0; i < owningOreKindOfChunks.Count; i++)
+ {
+ InformationOfChunks[i] += (owningOreKindOfChunks[i] << 4);
+ }
+
+ HasBed = hasBed;
+ HasBedOpponent = hasBedOpponent;
+
+ PositionX = positionX;
+ PositionY = positionY;
+ PositionOpponentX = positionOpponentX;
+ PositionOpponentY = positionOpponentY;
+
+ Agility = agility;
+ Health = health;
+ MaxHealth = maxHealth;
+ Strength = strength;
+ EmeraldCount = emeraldCount;
+ WoolCount = woolCount;
+ }
+
+ public byte[] ToBytes()
+ {
+ int datalength = (
+ 1 + // GameStage
+ 4 + // ElapsedTime
+ 1 * ChunkCount + // InformationOfChunks
+ 1 + // HasBed
+ 1 + // HasBedOpponet
+ 4 * 4 + // Position
+ 1 * 6 // agility health maxHealth strength emeraldCount woolCount
+ );
+
+ byte[] data = new byte[datalength];
+
+ int currentIndex = 0;
+
+ //GameStage
+ data[currentIndex] = Convert.ToByte(GameStage);
+ currentIndex++;
+
+ //ElapsedTime
+ BitConverter.GetBytes(ElapsedTime).CopyTo(data, currentIndex);
+ currentIndex += 4;
+
+ //InformationOfChunks
+ for (int i = 0; i < InformationOfChunks.Count; i++)
+ {
+ data[currentIndex] = Convert.ToByte(InformationOfChunks[i]);
+ currentIndex++;
+ }
+
+ //HasBed
+ data[currentIndex] = Convert.ToByte(HasBed);
+ currentIndex++;
+
+ //HasBedOpponent
+ data[currentIndex] = Convert.ToByte(HasBedOpponent);
+ currentIndex++;
+
+ //Position
+ byte[] temp = BitConverter.GetBytes((float)PositionX); //convert float to 4 bytes
+ for (int i = 0; i < temp.Length; i++)
+ {
+ data[currentIndex] = temp[i];
+ currentIndex++;
+ }
+ temp = BitConverter.GetBytes(PositionY);
+ for (int i = 0; i < 4; i++)
+ {
+ data[currentIndex] = temp[i];
+ currentIndex++;
+ }
+ temp = BitConverter.GetBytes(PositionOpponentX);
+ for (int i = 0; i < 4; i++)
+ {
+ data[currentIndex] = temp[i];
+ currentIndex++;
+ }
+ temp = BitConverter.GetBytes(PositionOpponentY);
+ for (int i = 0; i < 4; i++)
+ {
+ data[currentIndex] = temp[i];
+ currentIndex++;
+ }
+
+
+ //1 byte factors
+ data[currentIndex++] = Convert.ToByte(Agility);
+ data[currentIndex++] = Convert.ToByte(Health);
+ data[currentIndex++] = Convert.ToByte(MaxHealth);
+ data[currentIndex++] = Convert.ToByte(Strength);
+ data[currentIndex++] = Convert.ToByte(EmeraldCount);
+ data[currentIndex++] = Convert.ToByte(WoolCount);
+
+ //add header
+ byte[] header = IPacket.GeneratePacketHeader(data);
+ byte[] bytes = new byte[header.Length + data.Length];
+ header.CopyTo(bytes, 0);
+ data.CopyTo(bytes, header.Length);
+ return bytes;
+ }
+}
diff --git a/host/src/EdcHost/SlaveServers/PacketFromSlave.cs b/host/src/EdcHost/SlaveServers/PacketFromSlave.cs
new file mode 100644
index 0000000..f9aa869
--- /dev/null
+++ b/host/src/EdcHost/SlaveServers/PacketFromSlave.cs
@@ -0,0 +1,62 @@
+namespace EdcHost.SlaveServers;
+
+public class PacketFromSlave : IPacketFromSlave
+{
+ const int HeaderLength = 5;
+ const int DataLength = 2;
+
+ public int ActionType { get; private set; }
+ public int Param { get; private set; }
+
+ public PacketFromSlave(byte[] bytes)
+ {
+ if (bytes.Length != HeaderLength + DataLength)
+ {
+ throw new Exception("The length of the packet is incorrect.");
+ }
+
+ if (bytes[0] != 0x55 || bytes[1] != 0xAA)
+ {
+ throw new Exception("The header of the packet is broken.");
+ }
+
+ short dataLength = BitConverter.ToInt16(bytes, 2);
+ if (dataLength != DataLength)
+ {
+ throw new Exception("The data length of the packet is incorrect.");
+ }
+
+ byte checksum = bytes[4];
+ if (checksum != IPacket.CalculateChecksum(IPacket.GetPacketData(bytes)))
+ {
+ throw new Exception("The checksum of the packet is incorrect.");
+ }
+
+ int currentIndex = 5;
+ ActionType = Convert.ToInt32(bytes[currentIndex++]);
+ Param = Convert.ToInt32(bytes[currentIndex]);
+ }
+
+ public PacketFromSlave(int actionType, int param)
+ {
+ ActionType = actionType;
+ Param = param;
+ }
+
+ public byte[] ToBytes()
+ {
+ int datalength = 2;
+ byte[] data = new byte[datalength];
+
+ int currentIndex = 0;
+ data[currentIndex++] = Convert.ToByte(ActionType);
+ data[currentIndex] = Convert.ToByte(Param);
+
+ //add header
+ byte[] header = IPacket.GeneratePacketHeader(data);
+ byte[] bytes = new byte[header.Length + data.Length];
+ header.CopyTo(bytes, 0);
+ data.CopyTo(bytes, header.Length);
+ return bytes;
+ }
+}
diff --git a/host/src/EdcHost/SlaveServers/SerialPortHub.cs b/host/src/EdcHost/SlaveServers/SerialPortHub.cs
new file mode 100644
index 0000000..27c6e0d
--- /dev/null
+++ b/host/src/EdcHost/SlaveServers/SerialPortHub.cs
@@ -0,0 +1,10 @@
+using System.IO.Ports;
+
+namespace EdcHost.SlaveServers;
+
+class SerialPortHub : ISerialPortHub
+{
+ public List PortNames => SerialPort.GetPortNames().ToList();
+
+ public ISerialPortWrapper Get(string portName, int baudRate) => new SerialPortWrapper(portName, baudRate);
+}
diff --git a/host/src/EdcHost/SlaveServers/SerialPortWrapper.cs b/host/src/EdcHost/SlaveServers/SerialPortWrapper.cs
new file mode 100644
index 0000000..678abca
--- /dev/null
+++ b/host/src/EdcHost/SlaveServers/SerialPortWrapper.cs
@@ -0,0 +1,147 @@
+using System.Collections.Concurrent;
+using System.Diagnostics;
+using System.IO.Ports;
+
+namespace EdcHost.SlaveServers;
+
+class SerialPortWrapper : ISerialPortWrapper
+{
+ public event EventHandler