diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..def9802e8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +/.idea/ +/.gradle/ +/testbed/ +/build/ diff --git a/.idea/libraries/Maven__org_bukkit_bukkit_1_12_2_R0_1_SNAPSHOT.xml b/.idea/libraries/Maven__org_bukkit_bukkit_1_12_2_R0_1_SNAPSHOT.xml deleted file mode 100644 index 49760b2e5..000000000 --- a/.idea/libraries/Maven__org_bukkit_bukkit_1_12_2_R0_1_SNAPSHOT.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Maven__org_spigotmc_spigot_api_1_12_2_R0_1_SNAPSHOT.xml b/.idea/libraries/Maven__org_spigotmc_spigot_api_1_12_2_R0_1_SNAPSHOT.xml deleted file mode 100644 index 42f0d6f90..000000000 --- a/.idea/libraries/Maven__org_spigotmc_spigot_api_1_12_2_R0_1_SNAPSHOT.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/.idea/libraries/Maven__org_yaml_snakeyaml_1_19.xml b/.idea/libraries/Maven__org_yaml_snakeyaml_1_19.xml deleted file mode 100644 index 33ccf19e2..000000000 --- a/.idea/libraries/Maven__org_yaml_snakeyaml_1_19.xml +++ /dev/null @@ -1,13 +0,0 @@ - - - - - - - - - - - - - \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 000000000..f288702d2 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md index 83b5dcc7f..1d9ad7858 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,126 @@ -# EliteMobs +Thank you for using EliteMobs! -This is the GitHub project for the Minecraft plugin EliteMobs (Spigot page can be seen here: https://www.spigotmc.org/resources/elitemobs.40090/) +This plugin is made to both work from the very start with no additional config work and to be highly customizable. -Feel free to check the source code and do any edits you might deem necessary for your own servers. +If you want to make some deep configuration changes to the plugin, try to read the GitHub wiki I've created ahead of time or as you're making the changes so you know what the options are doing. https://github.com/MagmaGuy/EliteMobs -At this time, I am not interested in accepting contributions to the code. This is my first project of this dimension, and I'd like to have all components of it be written by me. +If you need support with this plugin, you can reach me at my discord support channel: https://discord.gg/QSA2wgh -That being said, I am deeply interested in any suggestions, be they for improving existing features or creating new ones. +For all things EliteMobs related, you can go to my website to find all resources I've made available, such as the github page, the wiki, the custom loot maker, so on. -# There's a wiki, it has a few entries, if you want more info maybe try reading it. +Hope you enjoy! If you do, leave rating on the resource page and / or buy me a coffee ! (paypal links can be found in the spigot resource page) -# //TODO: add description of features and how they work, some day, maybe \ No newline at end of file + +# Dev notes: + +## API + +EliteMobs has a few basic APIs to interface with in the `com.magmaguy.elitemobs.api` package. Here's the breakdown: + +### DamageEliteMob + +Used for applying custom damage to Elite Mobs. Uses: +- Bypass EliteMobs' custom damage system for a specific damage event +- Apply an automatically recommended custom amount of damage which varies based on the tier of the boss. + +*Note:* the variable damage takes the elite's tier into account and deals more damage to higher tiers. It does not take the health multiplier into account for custom bosses for balance reasons. + +### EliteMobDamagedByEliteMobEvent + +Used for listening to moments when one Elite damages another Elite. Uses: +- Same as Bukkit's EntityDamagedByEntity event but for elites specifically +- Cancelling it might not work. Report if it doesn't. + +### EliteMobDamagedByPlayerAntiExploit +Used for listening to events which trigger an antiexploit **check** - doesn't necessarily mean that it detected an exploit. Uses: +- Same as Bukkit's EntityDamagedByEntity event but for elites specifically +- Can be cancelled + +### EliteMobDamagedByPlayerEvent: +Used for listening to moments when a player damages an Elite. Uses: + +- Same as Bukkit's EntityDamagedByEntity event but for players damaging elites specifically +- ***Important:*** can't be cancelled as it only fires after applying the damage + +### EliteMobDamagedEvent: +Used for listening to moments when an elite is damaged in general. Uses: + +- Same as Bukkit's EntityDamageEvent +- ***Important*** Cancelling this event might not 100% work, report if it doesn't + +### EliteMobDeathEvent: +Used to listening to moments when an elite is killed. Uses: + +- Same as Bukkit's EntityDeathEvent. + +### EliteMobEnterCombatEvent: +Used for listening to moments when an elite enters combat against a player. Uses: + +- Get the target (player only) of the Elite +- Get the elite which entered in combat + +#### EliteMobExitCombatEvent: +Used for listening to moments when an elite leaves combat against a player. Uses: + +- Get the elite which just let combat. + +### EliteMobsItemDetector: +Used for detecting whether an ItemStack is an EliteMobs ItemStack (like a custom item or a procedurally generated item). Uses: + +- Detect if an ItemStack is an EliteMobs custom or dynamic item. + +### EliteMobSpawnEvent: +Used for detecting when an Elite spawns. USes: + +- Detect when an Elite spawns +- Detect which Elite spawned + +### EliteMobTargetPlayerEvent: +Used for detecting when an Elite has targetted a player. Uses: + +- Detect when an Elite targets a player. +- Cancel an Elite's detection of a player. + +### GenericAntiExploitEvent + +Used for listening to moments when the antiexploit runs a check but no players damaged it. Uses: + +- Detect when the antiexploit is doing a non-player based exploit check +- Cancel an antiexploit check + +### PlayerDamagedByEliteMobEvent + +Used for listening to moments when players are damaged by an Elite. Uses: + +- Same as Bukkit's EntityDamageEvent + +--- + + +## To add new item enchantments: +1) Add new enchantment class to the `com.magmaguy.elitemobs.config.enchantments.premade` **extending** `EnchantmentsConfigFields` to initialize create its config file (naming convention: [EnchantmentName]Config) +2) Initialize enchantment in `CustomEnchantment` to initialize the config file +3) Add enchantment class to `com.magmaguy.elitemobs.items.customenchantments` **extending** `CustomEnchantment` to write the logic for the enchantment (naming convention [EnchantmentName]Enchantment) +4) Add a public static String called "key" to register using the ItemTagger class for persistent enchantment tracking +5) Add an customLootEntry to the parseEnchantments() method in `CustomItem` so custom items detect it correctly +6) (Alternative) Add an customLootEntry to `generateCustomEnchantments()` method in `EnchantmentGenerator` if the enchantment should appear in procedurally generated items + +Note: +- Don't forget to register events in `EventsRegistrer` if the part with logic in it requires events. +- Don't forget to use the damage bypass if the power is supposed to deal custom damage. Damage dealt by the player to an elite can be overwritten in `CombatSystem` through the static "bypass" boolean field - it makes the next damage dealt to the elite use the raw damage value. For correctly assigning damage, use Bukkit's `Damageable#damage(double amount, Entity source)` and assign the source to your player. + +## To add new powers to elites: + +to be documented + +## To add new events: + +to be documented + +## To add new default NPCs: + +to be documented + +## To add new mob types: + +to be documented diff --git a/build.gradle b/build.gradle new file mode 100644 index 000000000..b74b62e05 --- /dev/null +++ b/build.gradle @@ -0,0 +1,166 @@ +plugins { + id 'java-library' + id 'idea' + id 'maven-publish' + id "com.github.johnrengelman.shadow" version "7.0.0" +} + +//Fixes issues related to special characters being used +compileJava.options.encoding = "UTF-8" +compileTestJava.options.encoding = "UTF-8" + +group 'com.magmaguy' +version '7.3.15-SNAPSHOT-5' + +repositories { + maven { + url = 'https://hub.spigotmc.org/nexus/content/repositories/snapshots/' + + // As of Gradle 5.1, you can limit this to only those + // dependencies you expect from it + content { + includeGroup 'org.bukkit' + includeGroup 'org.spigotmc' + } + } + + mavenCentral() + jcenter() + mavenLocal() + + //Spigot API & CloudCommands + maven { url = 'https://oss.sonatype.org/content/repositories/snapshots' } + maven { url = 'https://oss.sonatype.org/content/repositories/central' } + + maven { url "https://hub.spigotmc.org/nexus/content/repositories/snapshots" } + + //Bstats API + maven { url = 'https://repo.codemc.org/repository/maven-public' } + //CloudCommands + maven { url = 'https://oss.sonatype.org/content/repositories/snapshots' } + //Vault + maven { url = 'https://jitpack.io' } + //DiscordSRV + maven { url = 'https://m2.dv8tion.net/releases/' } + maven { url = 'https://nexus.scarsz.me/content/groups/public/' } + //LibsDisguises + maven { url = 'https://repo.md-5.net/content/groups/public/' } + //PlaceholderAPI + maven { url = 'https://repo.extendedclip.com/content/repositories/placeholderapi/' } + + //WorldGuard API + maven { url = 'https://maven.enginehub.org/repo/' } + + //Model Engine + maven { + url = 'https://mvn.lumine.io/repository/maven-public/' + metadataSources { + artifact() + } + } + + //Geyser + maven { url = 'https://repo.opencollab.dev/main/' } + +} + +dependencies { + //Spigot API + compileOnly "org.spigotmc:spigot-api:1.18-R0.1-SNAPSHOT" + + //compileOnly 'org.spigotmc:spigot:1.17-R0.1-SNAPSHOT' + // The full CraftBukkit server with no shadowing. Requires mavenLocal. + //BStats API + implementation group: 'org.bstats', name: 'bstats-bukkit', version: '2.2.1' + //WorldGuard API + compileOnly group: 'com.sk89q.worldguard', name: 'worldguard-bukkit', version: '7.0.0' + //CloudCommands + implementation group: 'cloud.commandframework', name: 'cloud-paper', version: '1.5.0' + //CloudCommands Minecraft Extras module + implementation group: 'cloud.commandframework', name: 'cloud-minecraft-extras', version: '1.5.0' + //CloudCommands Adventure Platform module + implementation("net.kyori:adventure-platform-bukkit:4.0.0") + //I can't remember what this was for but it's in CloudCommands + implementation group: 'io.leangen.geantyref', name: 'geantyref', version: '1.3.4' + //Vault + //compileOnly group: 'com.github.MilkBowl', name: 'VaultAPI', version: '1.7' + compileOnly("com.github.MilkBowl:VaultAPI:1.7") { + exclude group: 'org.bukkit', module: 'bukkit' + } + //DiscordSRV + //compileOnly 'net.dv8tion:JDA:4.2.1_262' + compileOnly 'com.discordsrv:discordsrv:1.24.0' + //SQLite + compileOnly group: 'org.xerial', name: 'sqlite-jdbc', version: '3.32.3' + //LibsDisguises + compileOnly group: 'com.comphenix.protocol', name: 'ProtocolLib', version: '4.7.0'; + compileOnly group: 'LibsDisguises', name: 'LibsDisguises', version: '10.0.26' + //PlaceholderAPI + compileOnly group: 'me.clip', name: 'placeholderapi', version: '2.10.9' + + implementation group: 'commons-io', name: 'commons-io', version: '2.6' + + //reflections - used for config initialization + implementation group: 'org.reflections', name: 'reflections', version: '0.9.12' + + //lombok + compileOnly 'org.projectlombok:lombok:1.18.22' + annotationProcessor 'org.projectlombok:lombok:1.18.22' + + //Model Engine + compileOnly "com.ticxo.modelengine:api:R2.5.0" + + testCompileOnly 'org.projectlombok:lombok:1.18.20' + testAnnotationProcessor 'org.projectlombok:lombok:1.18.20' + + //Geyser for bedrock player detection + //This needs java 16 to work so you will want to change gradle.properties to match your directory for it + //compileOnly("org.geysermc:geyser-api:2.0.2-SNAPSHOT") disabled because I couldn't find an easy way to see if a player is using geyser through their api due to the bungeecord / waterfall specific implementations + +} + +/* +java { + toolchain { + languageVersion.set(JavaLanguageVersion.of(16)) + } +} + */ + +artifacts { // task 'build' runs generates uberjar + archives shadowJar +} + +jar { + archiveClassifier.set('min') // we want the Uberjar to be distributed, this is the minified version +} + +String packagePath = 'com.magmaguy.shaded' + +// Relocating a Package +shadowJar { + dependencies { + relocate('org.bstats', packagePath + '.bstats') + relocate('cloud.commandframework', packagePath + '.cloud') + relocate('net.kyori', packagePath + '.adventure-platform-bukkit') + relocate('io.leangen.geantyref', packagePath + '.geantyref') + relocate('org.reflections', packagePath + '.reflections') + } + archiveClassifier.set(null) + archiveFileName.set(project.name + ".jar") + destinationDirectory.set(new File("testbed/plugins")) +} + +tasks.withType(JavaCompile) { + options.encoding = 'UTF-8' +} + +ext { + resourceTokens = [ + 'Version': version + ] +} + +processResources { + filter org.apache.tools.ant.filters.ReplaceTokens, tokens: resourceTokens +} \ No newline at end of file diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 000000000..e099597eb --- /dev/null +++ b/gradle.properties @@ -0,0 +1,5 @@ +projectName=EliteMobs +group=com.magmaguy.elitemobs +version=7.2.33 +author=MagmaGuy +mainClass=EliteMobs \ No newline at end of file diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..e708b1c02 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..f371643ee --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.0-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/pom.xml b/pom.xml deleted file mode 100644 index e9421a232..000000000 --- a/pom.xml +++ /dev/null @@ -1,109 +0,0 @@ - - - - - 4.0.0 - - com.magmaguy - EliteMobs - 6.6.5 - jar - - - UTF-8 - - - - ${project.artifactId} - clean resources:resources package - - - org.apache.maven.plugins - maven-compiler-plugin - 3.6.2 - - 1.8 - 1.8 - - - - org.apache.maven.plugins - maven-shade-plugin - 2.3 - - false - - - org.bstats:* - - - - - org.bstats - - com.magmaguy.elitemobs - - - - - - package - - shade - - - - - - - - - - spigotmc-repo - https://hub.spigotmc.org/nexus/content/groups/public/ - - - bstats-repo - http://repo.bstats.org/content/repositories/releases/ - - - - - - - org.spigotmc - spigot-api - 1.12.2-R0.1-SNAPSHOT - provided - - - - org.bukkit - bukkit - 1.12.2-R0.1-SNAPSHOT - provided - - - - org.bstats - bstats-bukkit - 1.1 - - - - \ No newline at end of file diff --git a/settings.gradle b/settings.gradle new file mode 100644 index 000000000..b4b573413 --- /dev/null +++ b/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "EliteMobs" \ No newline at end of file diff --git a/src/main/java/com/magmaguy/elitemobs/ChatColorConverter.java b/src/main/java/com/magmaguy/elitemobs/ChatColorConverter.java index 59721b1b2..14fdea1d8 100644 --- a/src/main/java/com/magmaguy/elitemobs/ChatColorConverter.java +++ b/src/main/java/com/magmaguy/elitemobs/ChatColorConverter.java @@ -1,31 +1,28 @@ -/* - * 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 . - */ - package com.magmaguy.elitemobs; import org.bukkit.ChatColor; +import java.util.ArrayList; +import java.util.List; + /** * Created by MagmaGuy on 13/05/2017. */ public class ChatColorConverter { - public static String convert(String string) { + private ChatColorConverter() { + } + public static String convert(String string) { + if (string == null) return ""; return ChatColor.translateAlternateColorCodes('&', string); + } + public static List convert(List list) { + List convertedList = new ArrayList<>(); + for (String string : list) + convertedList.add(convert(string)); + return convertedList; } } diff --git a/src/main/java/com/magmaguy/elitemobs/CrashFix.java b/src/main/java/com/magmaguy/elitemobs/CrashFix.java new file mode 100644 index 000000000..45845ee01 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/CrashFix.java @@ -0,0 +1,79 @@ +package com.magmaguy.elitemobs; + +import com.magmaguy.elitemobs.utils.ChunkVectorizer; +import com.magmaguy.elitemobs.utils.PersistentVanillaData; +import org.bukkit.Bukkit; +import org.bukkit.Chunk; +import org.bukkit.World; +import org.bukkit.entity.Entity; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.world.ChunkLoadEvent; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.HashSet; + +public class CrashFix implements Listener { + + private static final HashSet temporarilyCachedChunks = new HashSet<>(); + public static String key = "EliteMobsCullable"; + public static HashSet knownSessionChunks = new HashSet<>(); + + public static void persistentTracker(Entity entity) { + PersistentVanillaData.write(entity, key, "delete_me"); + } + + public static boolean isPersistentEntity(Entity entity) { + return PersistentVanillaData.hasString(entity, key); + } + + public static void startupCheck() { + for (World world : Bukkit.getWorlds()) + for (Chunk chunk : world.getLoadedChunks()) { + chunkCheck(chunk); + knownSessionChunks.add(ChunkVectorizer.hash(chunk)); + } + } + + private static void chunkCheck(Chunk chunk) { + for (Entity entity : chunk.getEntities()) + if (isPersistentEntity(entity)) + entity.remove(); + } + + /** + * This runs during startup. There is currently an issue with entities not getting scanned correctly when the chunk + * loads, as well as an issue with double chunk loading. Additionally, since all elites are initialized during startup, + * delaying the chunk by 1 tick causes the valid entities to be deleted as soon as they load in. To fix this, entities + * that exist in a chunk when it is loaded are instead cached, and the chunk getting loaded is cached as well. The + * chunk cache prevents a double check from happening, and entity cache prevents the plugin from scanning entities + * other than the ones that persisted through a restart. + * + * @param chunk + */ + private static void delayedChunkCheck(Chunk chunk, int hashedChunk) { + Entity[] entities = chunk.getEntities().clone(); + new BukkitRunnable() { + @Override + public void run() { + for (Entity entity : entities) + if (isPersistentEntity(entity)) + entity.remove(); + temporarilyCachedChunks.remove(hashedChunk); + } + }.runTaskLater(MetadataHandler.PLUGIN, 1); + } + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + public void onChunkLoad(ChunkLoadEvent event) { + int hashedChunk = ChunkVectorizer.hash(event.getChunk()); + //For some reason there is double chunk loading going on, and entities aren't getting detected correctly + if (temporarilyCachedChunks.contains(hashedChunk)) return; + temporarilyCachedChunks.add(hashedChunk); + if (knownSessionChunks.contains(hashedChunk)) return; + knownSessionChunks.add(hashedChunk); + delayedChunkCheck(event.getChunk(), hashedChunk); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/EliteMobs.java b/src/main/java/com/magmaguy/elitemobs/EliteMobs.java index 92a9358e3..fbea77666 100644 --- a/src/main/java/com/magmaguy/elitemobs/EliteMobs.java +++ b/src/main/java/com/magmaguy/elitemobs/EliteMobs.java @@ -4,61 +4,183 @@ * Created by MagmaGuy on 07/10/2016. */ +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerEvent; import com.magmaguy.elitemobs.commands.CommandHandler; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.DefaultConfig; -import com.magmaguy.elitemobs.config.ValidMobsConfig; -import com.magmaguy.elitemobs.events.EventLauncher; -import com.magmaguy.elitemobs.items.CustomItemConstructor; -import com.magmaguy.elitemobs.items.customenchantments.CustomEnchantmentCache; -import com.magmaguy.elitemobs.items.uniqueitems.UniqueItemInitializer; -import com.magmaguy.elitemobs.mobconstructor.CombatSystem; +import com.magmaguy.elitemobs.commands.guild.AdventurersGuildCommand; +import com.magmaguy.elitemobs.config.*; +import com.magmaguy.elitemobs.config.commands.CommandsConfig; +import com.magmaguy.elitemobs.config.customarenas.CustomArenasConfig; +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfig; +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import com.magmaguy.elitemobs.config.customevents.CustomEventsConfig; +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfig; +import com.magmaguy.elitemobs.config.customquests.CustomQuestsConfig; +import com.magmaguy.elitemobs.config.customspawns.CustomSpawnConfig; +import com.magmaguy.elitemobs.config.customtreasurechests.CustomTreasureChestsConfig; +import com.magmaguy.elitemobs.config.dungeonpackager.DungeonPackagerConfig; +import com.magmaguy.elitemobs.config.dungeonpackager.DungeonPackagerConfigFields; +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfig; +import com.magmaguy.elitemobs.config.menus.MenusConfig; +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; +import com.magmaguy.elitemobs.config.npcs.NPCsConfig; +import com.magmaguy.elitemobs.config.potioneffects.PotionEffectsConfig; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.config.wormholes.WormholeConfig; +import com.magmaguy.elitemobs.dungeons.Minidungeon; +import com.magmaguy.elitemobs.economy.VaultCompatibility; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.events.ActionEvent; +import com.magmaguy.elitemobs.events.TimedEvent; +import com.magmaguy.elitemobs.explosionregen.Explosion; +import com.magmaguy.elitemobs.gamemodes.nightmaremodeworld.DaylightWatchdog; +import com.magmaguy.elitemobs.gamemodes.zoneworld.Grid; +import com.magmaguy.elitemobs.instanced.MatchInstance; +import com.magmaguy.elitemobs.items.LootTables; +import com.magmaguy.elitemobs.items.customenchantments.CustomEnchantment; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import com.magmaguy.elitemobs.mobconstructor.custombosses.RegionalBossEntity; import com.magmaguy.elitemobs.mobconstructor.mobdata.PluginMobProperties; -import com.magmaguy.elitemobs.mobpowers.majorpowers.SkeletonTrackingArrow; -import com.magmaguy.elitemobs.playerdata.PlayerData; +import com.magmaguy.elitemobs.mobs.passive.EggRunnable; +import com.magmaguy.elitemobs.mobs.passive.PassiveEliteMobDeathHandler; +import com.magmaguy.elitemobs.playerdata.ElitePlayerInventory; +import com.magmaguy.elitemobs.playerdata.database.PlayerData; import com.magmaguy.elitemobs.powerstances.MajorPowerStanceMath; import com.magmaguy.elitemobs.powerstances.MinorPowerStanceMath; -import com.magmaguy.elitemobs.runnables.*; +import com.magmaguy.elitemobs.quests.QuestTracking; +import com.magmaguy.elitemobs.thirdparty.bstats.CustomCharts; +import com.magmaguy.elitemobs.thirdparty.libsdisguises.DisguiseEntity; +import com.magmaguy.elitemobs.thirdparty.placeholderapi.Placeholders; +import com.magmaguy.elitemobs.thirdparty.worldguard.WorldGuardCompatibility; +import com.magmaguy.elitemobs.treasurechest.TreasureChest; +import com.magmaguy.elitemobs.utils.InfoMessage; +import com.magmaguy.elitemobs.utils.ServerTime; +import com.magmaguy.elitemobs.utils.WarningMessage; import com.magmaguy.elitemobs.versionnotifier.VersionChecker; -import com.magmaguy.elitemobs.versionnotifier.VersionWarner; -import org.bstats.Metrics; +import com.magmaguy.elitemobs.worlds.CustomWorldLoading; +import com.magmaguy.elitemobs.wormhole.Wormhole; +import org.bstats.bukkit.Metrics; import org.bukkit.Bukkit; import org.bukkit.World; -import org.bukkit.entity.Arrow; +import org.bukkit.entity.EntityType; +import org.bukkit.event.HandlerList; import org.bukkit.plugin.java.JavaPlugin; +import java.io.File; +import java.io.IOException; +import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; public class EliteMobs extends JavaPlugin { public static List validWorldList = new ArrayList(); + public static boolean worldGuardIsEnabled = false; + public static List zoneBasedSpawningWorlds = new ArrayList<>(); + public static List nightmareWorlds = new ArrayList<>(); + public static Metrics metrics; + public Object placeholders = null; + + public static void initializeConfigs() { + DefaultConfig.initializeConfig(); + ItemSettingsConfig.initializeConfig(); + ProceduralItemGenerationSettingsConfig.initializeConfig(); + PotionEffectsConfig.initializeConfigs(); + TranslationConfig.initializeConfig(); + EconomySettingsConfig.initializeConfig(); + EventsConfig.initializeConfig(); + new EnchantmentsConfig(); + AntiExploitConfig.initializeConfig(); + CombatTagConfig.initializeConfig(); + AntiExploitConfig.initializeConfig(); + AdventurersGuildConfig.initializeConfig(); + ValidWorldsConfig.initializeConfig(); + + new MenusConfig(); + new PowersConfig(); + MobPropertiesConfig.initializeConfigs(); + CustomEnchantment.initializeCustomEnchantments(); + + MobCombatSettingsConfig.initializeConfig(); + CommandsConfig.initializeConfigs(); + DiscordSRVConfig.initializeConfig(); + ReadMeForTranslationsConfig.initialize(); + ItemUpgradeSystemConfig.initializeConfig(); + new CustomEventsConfig(); + QuestsConfig.initializeConfig(); + WormholesConfig.initializeConfig(); + ArenasConfig.initializeConfig(); + } + + public static void worldScanner() { + for (World world : Bukkit.getWorlds()) + if (ValidWorldsConfig.getFileConfiguration().getBoolean("Valid worlds." + world.getName())) { + validWorldList.add(world); + if (ValidWorldsConfig.getZoneBasedWorlds().contains(world.getName())) + zoneBasedSpawningWorlds.add(world); + if (ValidWorldsConfig.getNightmareWorlds().contains(world.getName())) { + nightmareWorlds.add(world); + DaylightWatchdog.preventDaylight(world); + } + } + + } @Override public void onEnable() { - //Enable stats - Metrics metrics = new Metrics(this); + Bukkit.getLogger().info(" _____ _ _____ _____ ________ ______________ _____"); + Bukkit.getLogger().info("| ___| | |_ _|_ _| ___| \\/ | _ | ___ \\/ ___|"); + Bukkit.getLogger().info("| |__ | | | | | | | |__ | . . | | | | |_/ /\\ `--."); + Bukkit.getLogger().info("| __|| | | | | | | __|| |\\/| | | | | ___ \\ `--. \\"); + Bukkit.getLogger().info("| |___| |_____| |_ | | | |___| | | \\ \\_/ / |_/ //\\__/ /"); + Bukkit.getLogger().info("\\____/\\_____/\\___/ \\_/ \\____/\\_| |_/\\___/\\____/ \\____/"); + MetadataHandler.PLUGIN = this; + Bukkit.getLogger().info("By MagmaGuy - v. " + MetadataHandler.PLUGIN.getDescription().getVersion()); + + ServerTime.startTickCounter(); + + if (Bukkit.getServer().spigot().getConfig().getDouble("settings.attribute.maxHealth.max") < 100000000) { + Bukkit.getServer().spigot().getConfig().set("settings.attribute.maxHealth.max", 100000000); + try { + File spigotConfigContainer = new File(Paths.get(MetadataHandler.PLUGIN.getDataFolder().getParentFile().getCanonicalFile().getParentFile().toString() + "/spigot.yml").toString()); + Bukkit.getServer().spigot().getConfig().save(spigotConfigContainer); + new InfoMessage("New default max health set correctly!"); + } catch (IOException e) { + new WarningMessage("Failed to save max health value! For the plugin to work correctly, you should increase your max health on the spigot.yml config file to " + 100000000); + } + } + + //Remove entities that should not exist + CrashFix.startupCheck(); - //Initialize custom enchantments - CustomEnchantmentCache.initialize(); + /* + New config loading + */ + initializeConfigs(); - //Load loot from config - ConfigValues.intializeConfigurations(); - ConfigValues.initializeCachedConfigurations(); + if (Bukkit.getPluginManager().isPluginEnabled("LibsDisguises")) + DisguiseEntity.initialize(); - //Parse loot - CustomItemConstructor superDrops = new CustomItemConstructor(); - superDrops.superDropParser(); + if (worldGuardIsEnabled) + Bukkit.getLogger().info("[EliteMobs] WorldGuard compatibility is enabled!"); + else + Bukkit.getLogger().warning("[EliteMobs] WorldGuard compatibility is not enabled!"); - UniqueItemInitializer.initialize(); + //Enable Vault + try { + VaultCompatibility.vaultSetup(); + } catch (Exception e) { + Bukkit.getLogger().warning("[EliteMobs] Something went wrong with the vault configuration - your Vault " + + "version is probably not compatible with this EliteMobs version. Please contact the dev about this error."); + VaultCompatibility.VAULT_ENABLED = false; + } //Hook up all listeners, some depend on config EventsRegistrer.registerEvents(); //Launch the local data cache - PlayerData.initializePlayerData(); - PlayerData.synchronizeDatabases(); + PlayerData.initializeDatabaseConnection(); + ElitePlayerInventory.initialize(); //Get world list worldScanner(); @@ -66,15 +188,12 @@ public void onEnable() { //Start the repeating tasks such as scanners launchRunnables(); - //Commands - this.getCommand("elitemobs").setExecutor(new CommandHandler()); - //launch events - EventLauncher eventLauncher = new EventLauncher(); - eventLauncher.eventRepeatingTask(); + ActionEvent.initializeBlueprintEvents(); + TimedEvent.initializeBlueprintEvents(); //launch internal clock for attack cooldown - CombatSystem.launchInternalClock(); + EliteMobDamagedByPlayerEvent.EliteMobDamagedByPlayerEventFilter.launchInternalClock(); /* Initialize mob values @@ -88,68 +207,189 @@ public void onEnable() { MajorPowerStanceMath.initializeVectorCache(); /* - Check for new plugin version + Scan for loaded SuperMobs */ - VersionChecker.updateComparer(); - if (!VersionChecker.pluginIsUpToDate) - this.getServer().getPluginManager().registerEvents(new VersionWarner(), this); + PassiveEliteMobDeathHandler.SuperMobScanner.scanSuperMobs(); - } + // Small check to make sure that PlaceholderAPI is installed + if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null) { + Placeholders placeholders = new Placeholders(); + placeholders.register(); + this.placeholders = placeholders; + } - @Override - public void onDisable() { + //Enable stats + metrics = new Metrics(this, 1081); + //Initialize custom charts + new CustomCharts(); + + //Imports custom configurations and mindungeons from the import folder + ConfigurationImporter.initializeConfigs(); + ConfigurationExporter.initializeConfigs(); + + //Import custom items after potentially importing new items + new CustomItemsConfig(); + CustomItem.initializeCustomItems(); + LootTables.initialize(); + + //Load minidungeons, most of all load the worlds of minidungeons + new DungeonPackagerConfig(); + //Load Adventurer's Guild + if (AdventurersGuildConfig.isGuildWorldIsEnabled()) { + try { + CustomWorldLoading.startupWorldInitialization(); + AdventurersGuildCommand.defineTeleportLocation(); + if (AdventurersGuildConfig.getGuildWorldLocation() == null) + AdventurersGuildConfig.toggleGuildInstall(); + } catch (Exception e) { + AdventurersGuildConfig.toggleGuildInstall(); + new WarningMessage("Failed to initialize the Adventurer's Guild Hub! It is now disabled. You can try to" + + "reenable it in /em setup"); + } + } + + //Load all regional bosses + new CustomBossesConfig(); + new CustomTreasureChestsConfig(); + + //Find the stats of bosses in minidungeons + for (Minidungeon minidungeon : Minidungeon.getMinidungeons().values()) { + if (minidungeon.getDungeonPackagerConfigFields().getDungeonLocationType() != null) + if (minidungeon.getDungeonPackagerConfigFields().getDungeonLocationType().equals(DungeonPackagerConfigFields.DungeonLocationType.WORLD)) + minidungeon.quantifyWorldBosses(); + else if (minidungeon.getDungeonPackagerConfigFields().getDungeonLocationType().equals(DungeonPackagerConfigFields.DungeonLocationType.SCHEMATIC)) + minidungeon.quantifySchematicBosses(false); + } + + //Initialize npcs + new NPCsConfig(); + + //Initialize custom spawn methods, this runs late because it compares loaded worlds against worlds listed in the config + try { + new CustomSpawnConfig(); + } catch (Exception ex) { + new WarningMessage("You are using a version of Spigot or a branch thereof (Paper, Purpur, so on) that is (probably) HORRIBLY outdated!" + + " This issue will probably be fixed if you update your server version to the latest patch of the version you are running."); + new WarningMessage( + " This does not mean that you have to update your Minecraft version, but it does mean you must update your server version to the latest patch" + + " available for that Minecraft version. Download from trustworthy sources, as if you download Spigot from some random website other than Spigot," + + " you are probably not getting the latest version (and also there's a high chance you'll get a virus)."); + } + + new CustomQuestsConfig(); + + new WormholeConfig(); - EntityTracker.shutdownPurger(); + //Commands + new CommandHandler(); + + //Arenas + new CustomArenasConfig(); /* - Flush lingering arrows from the arrow tracking power + Check for new plugin version or for dungeon updates */ - for (Arrow arrow : SkeletonTrackingArrow.trackingArrowList) - arrow.remove(); - SkeletonTrackingArrow.trackingArrowList.clear(); - - CustomItemConstructor.customItemList.clear(); - CustomItemConstructor.staticCustomItemHashMap.clear(); - CustomItemConstructor.dynamicRankedItemStacks.clear(); - UniqueItemInitializer.uniqueItemsList.clear(); - validWorldList.clear(); + VersionChecker.check(); + } - //save cached data - Bukkit.getScheduler().cancelTask(PlayerData.databaseSyncTaskID); - Bukkit.getLogger().info("[EliteMobs] Saving EliteMobs databases..."); - PlayerData.saveDatabases(); - Bukkit.getLogger().info("[EliteMobs] All saved! Good night."); - PlayerData.clearPlayerData(); + @Override + public void onLoad() { + //WorldGuard hook + try { + worldGuardIsEnabled = WorldGuardCompatibility.initialize(); + } catch (NoClassDefFoundError | IllegalStateException ex) { + Bukkit.getLogger().warning("[EliteMobs] Error loading WorldGuard. EliteMob-specific flags will not work." + + " Except if you just reloaded the plugin, in which case they will totally work."); + worldGuardIsEnabled = false; + } + if (!worldGuardIsEnabled) + if (Bukkit.getPluginManager().getPlugin("WorldGuard") != null) + worldGuardIsEnabled = true; } - public void worldScanner() { + @Override + public void onDisable() { - for (World world : Bukkit.getWorlds()) - if (ConfigValues.validWorldsConfig.getBoolean("Valid worlds." + world.getName())) - validWorldList.add(world); + new InfoMessage("Starting EliteMobs shutdown sequence..."); + + new InfoMessage("Regenerating exploded blocks..."); + Explosion.regenerateAllPendingBlocks(); + + new InfoMessage("Cancelling tasks..."); + Bukkit.getServer().getScheduler().cancelTasks(MetadataHandler.PLUGIN); + + new InfoMessage("Closing wormholes..."); + Wormhole.shutdown(); + + new InfoMessage("Spinning Regional Bosses down..."); + //save all pending respawns + RegionalBossEntity.save(); + RegionalBossEntity.getTrackableCustomBosses().clear(); + RegionalBossEntity.getRegionalBossEntitySet().clear(); + + new InfoMessage("Wiping Elite entities clean..."); + EntityTracker.wipeShutdown(); + + new InfoMessage("Clearing events..."); + TimedEvent.shutdown(); + ActionEvent.shutdown(); + + new InfoMessage("Clearing valid worlds..."); + validWorldList.clear(); + new InfoMessage("Clearing zone based worlds..."); + zoneBasedSpawningWorlds.clear(); + new InfoMessage("Clearing config regional elites..."); + CustomBossesConfigFields.getRegionalElites().clear(); + new InfoMessage("Clearing custom enchantments..."); + CustomEnchantment.getCustomEnchantments().clear(); + new InfoMessage("Clearing custom items..."); + CustomItem.getCustomItems().clear(); + CustomItem.getCustomItemStackList().clear(); + CustomItem.getCustomItemStackShopList().clear(); + CustomItem.getLimitedItem().clear(); + CustomItem.getScalableItems().clear(); + CustomItem.getFixedItems().clear(); + CustomItem.getTieredLoot().clear(); + CustomItem.getWeighedFixedItems().clear(); + new InfoMessage("Clearing Minidungeons..."); + Minidungeon.getMinidungeons().clear(); + RegionalBossEntity.regionalBossesShutdown(); + + new InfoMessage("Unregistering placeholders..."); + if (this.placeholders != null) + ((Placeholders) placeholders).unregister(); + + new InfoMessage("Unregistering handlers..."); + HandlerList.unregisterAll(MetadataHandler.PLUGIN); + + new InfoMessage("Clearing Treasure Chests..."); + TreasureChest.clearTreasureChests(); + + new InfoMessage("Untracking quests..."); + QuestTracking.clear(); + + MatchInstance.shutdown(); + + //save cached data + Bukkit.getLogger().info("[EliteMobs] Saving EliteMobs databases..."); + PlayerData.closeConnection(); + Bukkit.getLogger().info("[EliteMobs] All done! Good night."); } /* Repeating tasks that run as long as the server is on */ - public void launchRunnables() { - - int eggTimerInterval = 20 * 60 * 10 / ConfigValues.defaultConfig.getInt(DefaultConfig.SUPERMOB_STACK_AMOUNT); - - new EntityScanner().runTaskTimer(this, 20, 20 * 10); - new PotionEffectApplier().runTaskTimer(this, 20, 20); - if (ConfigValues.defaultConfig.getBoolean(DefaultConfig.ENABLE_POWER_SCOREBOARDS)) - new ScoreboardUpdater().runTaskTimer(this, 20, 20); - if (ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.ALLOW_PASSIVE_SUPERMOBS) && - ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.CHICKEN) && - ConfigValues.defaultConfig.getInt(DefaultConfig.SUPERMOB_STACK_AMOUNT) > 0) + private void launchRunnables() { + if (!zoneBasedSpawningWorlds.isEmpty()) + Grid.initializeGrid(); + int eggTimerInterval = 20 * 60 * 10 / DefaultConfig.getSuperMobStackAmount(); + if (MobPropertiesConfig.getMobProperties().get(EntityType.CHICKEN).isEnabled() && DefaultConfig.getSuperMobStackAmount() > 0) { new EggRunnable().runTaskTimer(this, eggTimerInterval, eggTimerInterval); - new DynamicLoreUpdater().runTaskTimer(this, 20, 20 * 2); -// new ReapplyDisplayEffects().runTaskTimer(this, 20, 20); -// EntityListUpdater.startUpdating(); - + } + //save regional bosses when the files update + RegionalBossEntity.regionalDataSaver(); } } diff --git a/src/main/java/com/magmaguy/elitemobs/EntityTracker.java b/src/main/java/com/magmaguy/elitemobs/EntityTracker.java deleted file mode 100644 index 2f9f51790..000000000 --- a/src/main/java/com/magmaguy/elitemobs/EntityTracker.java +++ /dev/null @@ -1,319 +0,0 @@ -package com.magmaguy.elitemobs; - -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.DefaultConfig; -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; -import com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs.EliteMobProperties; -import com.magmaguy.elitemobs.mobconstructor.mobdata.passivemobs.SuperMobProperties; -import com.magmaguy.elitemobs.mobpowers.ElitePower; -import org.bukkit.entity.*; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.CreatureSpawnEvent; -import org.bukkit.event.entity.EntityDeathEvent; -import org.bukkit.event.world.ChunkUnloadEvent; -import org.bukkit.scheduler.BukkitRunnable; - -import java.util.HashSet; -import java.util.Iterator; - -public class EntityTracker implements Listener { - - /* - These HashSets track basically everything for live plugin entities - */ - private static HashSet superMobs = new HashSet<>(); - private static HashSet eliteMobs = new HashSet<>(); - private static HashSet eliteMobsLivingEntities = new HashSet<>(); - - private static HashSet naturalEntities = new HashSet<>(); - private static HashSet armorStands = new HashSet<>(); - private static HashSet itemVisualEffects = new HashSet<>(); - - /* - This HashSet shouldn't really be scanned during runtime for aside from the occasional updates, it mostly exists to - cull entities once the server shuts down - */ - private static HashSet cullablePluginEntities = new HashSet<>(); - - /* - Starts tracking elite mobs - */ - public static void registerEliteMob(EliteMobEntity eliteMobEntity) { - eliteMobs.add(eliteMobEntity); - eliteMobsLivingEntities.add(eliteMobEntity.getLivingEntity()); - registerCullableEntity(eliteMobEntity.getLivingEntity()); - } - - /* - Starts tracking super mob - */ - public static void registerSuperMob(LivingEntity livingEntity) { - if (!SuperMobProperties.isValidSuperMobType(livingEntity)) return; - superMobs.add(livingEntity); - } - - /* - Registers mobs that spawn naturally, necessary for elite mob rewards - */ - public static void registerNaturalEntity(LivingEntity entity) { - if (!EliteMobProperties.isValidEliteMobType(entity)) return; - naturalEntities.add(entity); - } - - - public static void registerArmorStands(ArmorStand armorStand) { - armorStands.add(armorStand); - registerCullableEntity(armorStand); - } - - public static void registerItemVisualEffects(Item item) { - itemVisualEffects.add(item); - registerCullableEntity(item); - } - - /* - Starts tracking any entity generated or managed by EliteMobs, useful for when they need to be culled - Does not include super mobs to avoid culling them by mistake - */ - public static void registerCullableEntity(Entity entity) { - cullablePluginEntities.add(entity); - } - - public static void checkEntityState() { - - new BukkitRunnable() { - @Override - public void run() { - new BukkitRunnable() { - @Override - public void run() { - updateSuperMobs(); - updateEliteMobEntities(); - updateLivingEntities(); - updateCullables(); - updateAmorStands(); - updateItems(); - } - }.runTaskAsynchronously(MetadataHandler.PLUGIN); - } - }.runTaskTimer(MetadataHandler.PLUGIN, 20 * 60 * 5, 20 * 60 * 5); - - } - - private static void updateSuperMobs() { - Iterator iterator = superMobs.iterator(); - while (iterator.hasNext()) { - Entity entity = (Entity) iterator.next(); - if (!entity.isValid()) - iterator.remove(); - } - } - - private static void updateLivingEntities() { - Iterator iterator = naturalEntities.iterator(); - while (iterator.hasNext()) { - Entity entity = (Entity) iterator.next(); - if (!entity.isValid()) - iterator.remove(); - } - } - - private static void updateEliteMobEntities() { - Iterator iterator = eliteMobs.iterator(); - while (iterator.hasNext()) { - Entity entity = ((EliteMobEntity) iterator.next()).getLivingEntity(); - if (entity.isDead() || - !entity.isValid() && ((LivingEntity) entity).getRemoveWhenFarAway()) - iterator.remove(); - } - } - - private static void updateAmorStands() { - Iterator iterator = armorStands.iterator(); - while (iterator.hasNext()) { - Entity entity = (Entity) iterator.next(); - if (!entity.isValid()) - iterator.remove(); - } - } - - private static void updateCullables() { - Iterator iterator = cullablePluginEntities.iterator(); - while (iterator.hasNext()) { - Entity entity = (Entity) iterator.next(); - if (!entity.isValid()) - iterator.remove(); - } - } - - private static void updateItems() { - Iterator iterator = itemVisualEffects.iterator(); - while (iterator.hasNext()) { - Entity entity = (Entity) iterator.next(); - if (!entity.isValid()) - iterator.remove(); - } - } - - public static boolean isSuperMob(Entity entity) { - if (!SuperMobProperties.isValidSuperMobType(entity)) return false; - return superMobs.contains(entity); - } - - public static boolean isEliteMob(Entity entity) { - if (!EliteMobProperties.isValidEliteMobType(entity)) return false; - return eliteMobsLivingEntities.contains(entity); - } - - public static EliteMobEntity getEliteMobEntity(Entity entity) { - if (!EliteMobProperties.isValidEliteMobType(entity)) return null; - for (EliteMobEntity eliteMobEntity : eliteMobs) - if (eliteMobEntity.getLivingEntity().equals(entity)) - return eliteMobEntity; - return null; - } - - public static EliteMobEntity getAsyncEliteMobEntity(Entity entity) { - if (!EliteMobProperties.isValidEliteMobType(entity)) return null; - HashSet localEntities = (HashSet) eliteMobs.clone(); - for (EliteMobEntity eliteMobEntity : localEntities) - if (eliteMobEntity.getLivingEntity().equals(entity)) - return eliteMobEntity; - return null; - } - - public static boolean isNaturalEntity(Entity entity) { - if (!EliteMobProperties.isValidEliteMobType(entity)) return false; - return naturalEntities.contains(entity); - } - - public static boolean isItemVisualEffect(Entity entity) { - return (itemVisualEffects.contains(entity)); - } - - public static boolean hasPower(ElitePower mobPower, Entity entity) { - EliteMobEntity eliteMobEntity = getEliteMobEntity(entity); - if (eliteMobEntity == null) return false; - return eliteMobEntity.hasPower(mobPower); - } - - public static boolean hasPower(ElitePower mobPower, EliteMobEntity eliteMobEntity) { - if (eliteMobEntity == null) return false; - return eliteMobEntity.hasPower(mobPower); - } - - public static void unregisterCullableEntity(Entity entity) { - cullablePluginEntities.remove(entity); - } - - public static void unregisterItemEntity(Item item) { - itemVisualEffects.remove(item); - } - - /* - Used outside this class to remove individual elite mobs - */ - public static void unregisterEliteMob(EliteMobEntity eliteMobEntity) { - eliteMobs.remove(eliteMobEntity); - naturalEntities.remove(eliteMobEntity.getLivingEntity()); - cullablePluginEntities.remove(eliteMobEntity.getLivingEntity()); - } - - /* - Used in this class to do mass wipes of data - */ - private static void unregisterEliteMob(Entity entity) { - if (!isEliteMob(entity)) return; - EliteMobEntity eliteMobEntity = getAsyncEliteMobEntity(entity); - if (eliteMobEntity == null) return; - eliteMobEntity.getLivingEntity().remove(); - eliteMobs.remove(eliteMobEntity); - eliteMobsLivingEntities.remove(eliteMobEntity.getLivingEntity()); - } - - public static void unregisterArmorStand(Entity armorStand) { - if (!armorStand.getType().equals(EntityType.ARMOR_STAND)) return; - armorStands.remove(armorStand); - } - - public static HashSet getEliteMobs() { - return eliteMobs; - } - - public static boolean getIsArmorStand(Entity entity) { - if (!entity.getType().equals(EntityType.ARMOR_STAND)) return false; - return (armorStands.contains(entity)); - } - - public static void unregisterSuperMob(Entity entity) { - if (!SuperMobProperties.isValidSuperMobType(entity)) return; - superMobs.remove(entity); - } - - public static void unregisterNaturalEntity(Entity entity) { - if (EliteMobProperties.isValidEliteMobType(entity)) return; - naturalEntities.remove(entity); - } - - /* - Custom spawn reasons can be considered as natural spawns under specific config options - */ - @EventHandler(priority = EventPriority.LOW) - public void registerNaturalEntity(CreatureSpawnEvent event) { - if (event.isCancelled()) return; - if (event.getSpawnReason().equals(CreatureSpawnEvent.SpawnReason.NATURAL) || - event.getSpawnReason().equals(CreatureSpawnEvent.SpawnReason.CUSTOM) && - !ConfigValues.defaultConfig.getBoolean(DefaultConfig.STRICT_SPAWNING_RULES)) - registerNaturalEntity(event.getEntity()); - } - - /* - Natural entities get unregistered from being natural when exploit abuse is detected from the players - */ - public static void unregisterNaturalEntity(LivingEntity livingEntity) { - naturalEntities.remove(livingEntity); - } - - public static void shutdownPurger() { - - for (Entity entity : cullablePluginEntities) - entity.remove(); - - eliteMobs.clear(); - eliteMobsLivingEntities.clear(); - superMobs.clear(); - itemVisualEffects.clear(); - armorStands.clear(); - naturalEntities.clear(); - cullablePluginEntities.clear(); - - } - - /* - This is run in sync for performance reasons - */ - public static void wipeEntity(Entity entity) { - new BukkitRunnable() { - @Override - public void run() { - unregisterEliteMob(entity); - unregisterSuperMob(entity); - unregisterNaturalEntity(entity); - unregisterArmorStand(entity); - unregisterCullableEntity(entity); - } - }.runTaskAsynchronously(MetadataHandler.PLUGIN); - } - - public static void chunkWiper(ChunkUnloadEvent event) { - for (Entity entity : event.getChunk().getEntities()) - wipeEntity(entity); - } - - public static void deathWipe(EntityDeathEvent event) { - wipeEntity(event.getEntity()); - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/EventsRegistrer.java b/src/main/java/com/magmaguy/elitemobs/EventsRegistrer.java index 1441924a5..55ef6107d 100644 --- a/src/main/java/com/magmaguy/elitemobs/EventsRegistrer.java +++ b/src/main/java/com/magmaguy/elitemobs/EventsRegistrer.java @@ -1,206 +1,405 @@ package com.magmaguy.elitemobs; -import com.magmaguy.elitemobs.adventurersguild.AdventurersGuildGUI; +import com.magmaguy.elitemobs.adventurersguild.GuildRank; +import com.magmaguy.elitemobs.adventurersguild.GuildRankMenuHandler; +import com.magmaguy.elitemobs.adventurersguild.WorldSwitchBehavior; +import com.magmaguy.elitemobs.api.*; import com.magmaguy.elitemobs.collateralminecraftchanges.*; -import com.magmaguy.elitemobs.combattag.CombatTag; -import com.magmaguy.elitemobs.commands.LootGUI; -import com.magmaguy.elitemobs.commands.shops.CustomShopHandler; -import com.magmaguy.elitemobs.commands.shops.ItemSaleEvent; -import com.magmaguy.elitemobs.commands.shops.ShopHandler; +import com.magmaguy.elitemobs.combatsystem.EliteCreeperExplosionHandler; +import com.magmaguy.elitemobs.combatsystem.EliteMobDamagedByEliteMobHandler; +import com.magmaguy.elitemobs.combatsystem.EliteMobGenericDamagedHandler; +import com.magmaguy.elitemobs.combatsystem.PlayerDamagedByEliteMobHandler; +import com.magmaguy.elitemobs.combatsystem.antiexploit.*; +import com.magmaguy.elitemobs.combatsystem.combattag.CombatTag; +import com.magmaguy.elitemobs.combatsystem.displays.HealthDisplay; +import com.magmaguy.elitemobs.combatsystem.displays.PopupDisplay; +import com.magmaguy.elitemobs.commands.admin.RemoveCommand; +import com.magmaguy.elitemobs.commands.setup.SetupMenu; import com.magmaguy.elitemobs.config.*; -import com.magmaguy.elitemobs.events.DeadMoon; -import com.magmaguy.elitemobs.events.SmallTreasureGoblin; -import com.magmaguy.elitemobs.events.actionevents.BalrogEvent; -import com.magmaguy.elitemobs.events.actionevents.FaeEvent; -import com.magmaguy.elitemobs.events.actionevents.KrakenEvent; -import com.magmaguy.elitemobs.events.mobs.*; -import com.magmaguy.elitemobs.events.mobs.sharedeventpowers.SpiritWalk; +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfig; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.events.ActionEvent; +import com.magmaguy.elitemobs.explosionregen.Explosion; +import com.magmaguy.elitemobs.gamemodes.nightmaremodeworld.DaylightWatchdog; +import com.magmaguy.elitemobs.gamemodes.zoneworld.ZoneWarner; +import com.magmaguy.elitemobs.initialsetup.FirstTimeSetup; +import com.magmaguy.elitemobs.instanced.ArenaInstance; +import com.magmaguy.elitemobs.instanced.MatchInstance; import com.magmaguy.elitemobs.items.*; -import com.magmaguy.elitemobs.items.customenchantments.FlamethrowerEnchantment; -import com.magmaguy.elitemobs.mobconstructor.CombatSystem; +import com.magmaguy.elitemobs.items.customenchantments.*; +import com.magmaguy.elitemobs.items.potioneffects.PlayerPotionEffects; +import com.magmaguy.elitemobs.menus.*; import com.magmaguy.elitemobs.mobconstructor.MergeHandler; -import com.magmaguy.elitemobs.mobconstructor.displays.DamageDisplay; -import com.magmaguy.elitemobs.mobconstructor.displays.DisplayMob; -import com.magmaguy.elitemobs.mobconstructor.displays.HealthDisplay; -import com.magmaguy.elitemobs.mobpowers.AggroPrevention; -import com.magmaguy.elitemobs.mobpowers.defensivepowers.InvulnerabilityArrow; -import com.magmaguy.elitemobs.mobpowers.defensivepowers.InvulnerabilityFallDamage; -import com.magmaguy.elitemobs.mobpowers.defensivepowers.InvulnerabilityFire; -import com.magmaguy.elitemobs.mobpowers.defensivepowers.InvulnerabilityKnockback; -import com.magmaguy.elitemobs.mobpowers.majorpowers.*; -import com.magmaguy.elitemobs.mobpowers.miscellaneouspowers.BonusLoot; -import com.magmaguy.elitemobs.mobpowers.miscellaneouspowers.Taunt; -import com.magmaguy.elitemobs.mobpowers.offensivepowers.*; +import com.magmaguy.elitemobs.mobconstructor.SimplePersistentEntity; +import com.magmaguy.elitemobs.mobconstructor.custombosses.*; +import com.magmaguy.elitemobs.mobconstructor.custombosses.transitiveblocks.TransitiveBlockCommand; +import com.magmaguy.elitemobs.mobconstructor.custombosses.transitiveblocks.TransitiveBossBlock; import com.magmaguy.elitemobs.mobs.passive.*; -import com.magmaguy.elitemobs.mobspawning.NaturalEliteMobSpawnEventHandler; import com.magmaguy.elitemobs.mobspawning.NaturalMobSpawnEventHandler; +import com.magmaguy.elitemobs.npcs.NPCDamageEvent; +import com.magmaguy.elitemobs.npcs.NPCInteractions; +import com.magmaguy.elitemobs.npcs.chatter.NPCProximitySensor; +import com.magmaguy.elitemobs.ondeathcommands.OnDeathCommands; +import com.magmaguy.elitemobs.playerdata.ElitePlayerInventory; +import com.magmaguy.elitemobs.playerdata.PlayerStatsTracker; +import com.magmaguy.elitemobs.playerdata.database.PlayerData; +import com.magmaguy.elitemobs.playerdata.statusscreen.*; +import com.magmaguy.elitemobs.powers.bosspowers.*; +import com.magmaguy.elitemobs.powers.defensivepowers.InvulnerabilityArrow; +import com.magmaguy.elitemobs.powers.defensivepowers.InvulnerabilityFallDamage; +import com.magmaguy.elitemobs.powers.defensivepowers.InvulnerabilityKnockback; +import com.magmaguy.elitemobs.powers.defensivepowers.ShieldWall; +import com.magmaguy.elitemobs.powers.majorpowers.blaze.TrackingFireball; +import com.magmaguy.elitemobs.powers.majorpowers.enderdragon.EnderDragonEmpoweredLightning; +import com.magmaguy.elitemobs.powers.majorpowers.skeleton.SkeletonPillar; +import com.magmaguy.elitemobs.powers.majorpowers.skeleton.SkeletonTrackingArrow; +import com.magmaguy.elitemobs.powers.majorpowers.zombie.ZombieBloat; +import com.magmaguy.elitemobs.powers.majorpowers.zombie.ZombieFriends; +import com.magmaguy.elitemobs.powers.majorpowers.zombie.ZombieNecronomicon; +import com.magmaguy.elitemobs.powers.majorpowers.zombie.ZombieParents; +import com.magmaguy.elitemobs.powers.meta.Bombardment; +import com.magmaguy.elitemobs.powers.meta.CombatEnterScanPower; +import com.magmaguy.elitemobs.powers.meta.CustomSummonPower; +import com.magmaguy.elitemobs.powers.miscellaneouspowers.*; +import com.magmaguy.elitemobs.powers.offensivepowers.*; +import com.magmaguy.elitemobs.powers.specialpowers.EnderCrystalLightningRod; import com.magmaguy.elitemobs.powerstances.EffectEventHandlers; import com.magmaguy.elitemobs.powerstances.VisualEffectObfuscator; +import com.magmaguy.elitemobs.quests.CustomQuest; +import com.magmaguy.elitemobs.quests.QuestTracking; +import com.magmaguy.elitemobs.quests.menus.QuestInventoryMenu; +import com.magmaguy.elitemobs.quests.objectives.CustomFetchObjective; +import com.magmaguy.elitemobs.quests.objectives.DialogObjective; +import com.magmaguy.elitemobs.quests.objectives.KillObjective; +import com.magmaguy.elitemobs.quests.playercooldowns.PlayerQuestCooldownsLogout; +import com.magmaguy.elitemobs.thirdparty.modelengine.CustomModel; +import com.magmaguy.elitemobs.thirdparty.worldguard.WorldGuardDungeonFlag; +import com.magmaguy.elitemobs.thirdparty.worldguard.WorldGuardEliteMobOnlySpawnFlag; +import com.magmaguy.elitemobs.thirdparty.worldguard.WorldGuardSpawnEventBypasser; +import com.magmaguy.elitemobs.treasurechest.TreasureChest; import com.magmaguy.elitemobs.utils.VersionChecker; +import com.magmaguy.elitemobs.wormhole.WormholeEntry; import org.bukkit.Bukkit; +import org.bukkit.event.Listener; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; public class EventsRegistrer { + private static PluginManager pluginManager; + private static Plugin plugin; + + private EventsRegistrer() { + } + public static void registerEvents() { - PluginManager pluginManager = Bukkit.getPluginManager(); - Plugin plugin = MetadataHandler.PLUGIN; + pluginManager = Bukkit.getPluginManager(); + plugin = MetadataHandler.PLUGIN; + + register(new FirstTimeSetup()); + + register(new com.magmaguy.elitemobs.versionnotifier.VersionChecker.VersionCheckerEvents()); + + register(new PlayerData.PlayerDataEvents()); + register(new ElitePlayerInventory.ElitePlayerInventoryEvents()); + register(new PlayerStatsTracker()); + register(new PlayerQuestCooldownsLogout()); - //Load passive mobs TODO: find generic alternative to this - pluginManager.registerEvents(new ChickenHandler(), plugin); - pluginManager.registerEvents(new CowHandler(), plugin); - pluginManager.registerEvents(new MushroomCowHandler(), plugin); - pluginManager.registerEvents(new PassiveEliteMobDeathHandler(), plugin); - pluginManager.registerEvents(new PigHandler(), plugin); - pluginManager.registerEvents(new SheepHandler(), plugin); - pluginManager.registerEvents(new FindSuperMobs(), plugin); + register(new ChickenHandler()); + register(new CowHandler()); + register(new MushroomCowHandler()); + register(new PassiveEliteMobDeathHandler()); + register(new PigHandler()); + register(new SheepHandler()); + register(new FindSuperMobs()); + if (ItemSettingsConfig.isPreventEliteItemEnchantment()) + register(new ItemEnchantmentPrevention()); + if (!VersionChecker.serverVersionOlderThan(15, 2)) + if (ItemSettingsConfig.isPreventEliteItemDiamondToNetheriteUpgrade()) + register(new PreventUpgradeDiamondToNetherite()); //Mob damage - pluginManager.registerEvents(new CombatSystem(), plugin); - if (ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.ENABLE_DEATH_MESSAGES)) - pluginManager.registerEvents(new PlayerDeathMessageByEliteMob(), plugin); + register(new PlayerDamagedByEliteMobHandler()); + register(new EliteCreeperExplosionHandler()); + register(new EliteMobGenericDamagedHandler()); + register(new EliteMobDamagedByEliteMobHandler()); + if (MobCombatSettingsConfig.isEnableDeathMessages()) + register(new PlayerDeathMessageByEliteMob()); + + //explosion regenerator + if (DefaultConfig.isDoExplosionRegen()) + register(new Explosion.ExplosionEvent()); //Mob loot - pluginManager.registerEvents(new DefaultDropsHandler(), plugin); + register(new DefaultDropsHandler()); + register(new ItemLootShower.ItemLootShowerEvents()); + + //potion effects - also initializes the task + register(new PlayerPotionEffects()); + + //getloot AdventurersGuildMenu + register(new GetLootMenu.GetLootMenuListener()); - //potion effects - pluginManager.registerEvents(new PotionEffectApplier(), plugin); + /* + Register API events + */ + register(new EliteMobDeathEvent.EliteMobDeathEventFilter()); + register(new EliteMobTargetPlayerEvent.EliteMobTargetPlayerEventFilter()); + register(new EliteMobDamagedEvent.EliteMobDamageEventFilter()); + register(new PlayerDamagedByEliteMobEvent.PlayerDamagedByEliteMobEventFilter()); + register(new EliteMobDamagedByEliteMobEvent.EliteMobDamagedByEliteMobFilter()); + register(new EliteMobEnterCombatEvent.EliteMobEnterCombatEventFilter()); + register(new PlayerPreTeleportEvent.PlayerPreTeleportEventEvents()); + register(new PlayerTeleportEvent.PlayerTeleportEventExecutor()); + register(new SuperMobDamageEvent.SuperMobDamageEventFilter()); + register(new EliteMobDamagedByPlayerEvent.EliteMobDamagedByPlayerEventFilter()); + register(new EliteExplosionEvent.EliteExplosionEvents()); + + //Wormholes + register(new WormholeEntry.WormholeEntryEvent()); - //getloot AdventurersGuildGUI - pluginManager.registerEvents(new LootGUI(), plugin); /* While these powers could be registered in a more automated way, I realized that it's also a bad way of getting silent errors without ever noticing, and ultimately the amount of manual input required is pretty minimal */ //Minor mob powers - pluginManager.registerEvents(new InvulnerabilityArrow(), plugin); - pluginManager.registerEvents(new InvulnerabilityFallDamage(), plugin); - pluginManager.registerEvents(new InvulnerabilityFire(), plugin); - pluginManager.registerEvents(new InvulnerabilityKnockback(), plugin); - pluginManager.registerEvents(new BonusLoot(), plugin); - pluginManager.registerEvents(new Taunt(), plugin); - pluginManager.registerEvents(new AttackArrow(), plugin); - pluginManager.registerEvents(new AttackBlinding(), plugin); - pluginManager.registerEvents(new AttackFire(), plugin); - pluginManager.registerEvents(new AttackFireball(), plugin); - pluginManager.registerEvents(new AttackFreeze(), plugin); - pluginManager.registerEvents(new AttackGravity(), plugin); - pluginManager.registerEvents(new AttackPoison(), plugin); - pluginManager.registerEvents(new AttackPush(), plugin); - pluginManager.registerEvents(new AttackWeakness(), plugin); - pluginManager.registerEvents(new AttackWeb(), plugin); - pluginManager.registerEvents(new AttackWither(), plugin); + register(new InvulnerabilityArrow()); + register(new InvulnerabilityFallDamage()); + register(new InvulnerabilityKnockback()); + register(new BonusLoot()); + register(new Taunt()); + register(new Corpse()); + register(new Implosion()); + register(new AttackArrow()); + register(new ArrowFireworks()); + register(new AttackBlinding()); + register(new AttackFire()); + register(new AttackFireball()); + register(new TrackingFireball.TrackingFireballEvents()); + register(new AttackFreeze()); + register(new AttackGravity()); + register(new AttackLightning()); + register(new AttackPoison()); + register(new AttackPush()); + register(new AttackWeakness()); + register(new AttackWeb()); + register(new AttackWither()); + register(new AttackVacuum()); + register(new ArrowRain()); + register(new GroundPound()); + register(new LightningBolts()); + register(new FrostCone()); + register(new Thunderstorm()); + register(new Firestorm()); + register(new Bombardment.BombardmentEvents()); + register(new ShieldWall.ShieldWallEvents()); //Major mob powers - pluginManager.registerEvents(new SkeletonPillar(), plugin); - pluginManager.registerEvents(new SkeletonTrackingArrow(), plugin); - pluginManager.registerEvents(new ZombieBloat(), plugin); - pluginManager.registerEvents(new ZombieFriends(), plugin); - pluginManager.registerEvents(new ZombieNecronomicon(), plugin); - pluginManager.registerEvents(new ZombieParents(), plugin); - pluginManager.registerEvents(new ZombieTeamRocket(), plugin); + register(new SkeletonPillar()); + register(new SkeletonTrackingArrow()); + register(new ZombieBloat()); + register(new ZombieFriends()); + register(new ZombieNecronomicon()); + register(new ZombieParents()); + + //boss powers + register(new SpiritWalk()); + register(new GoldShotgun()); + register(new GoldExplosion()); + register(new Flamethrower()); + register(new PlasmaBootsEnchantment.PlasmaBootsEnchantmentEvents()); + if (EnchantmentsConfig.getEnchantment(SoulbindEnchantment.key + ".yml").isEnabled()) + register(new SoulbindEnchantment.SoulbindEnchantmentEvents()); + register(new FlamePyre()); + register(new SummonTheReturned()); + register(new HyperLoot()); + register(new SummonTheReturned()); + register(new SummonEmbers()); + register(new MeteorShower()); + register(new BulletHell()); + register(new DeathSlice()); + register(new FireworksBarrage.FireworksBarrageEvents()); + register(new CustomSummonPower.CustomSummonPowerEvent()); + register(new EnderDragonEmpoweredLightning.EnderDragonEmpoweredLightningEvents()); + register(new CombatEnterScanPower.MajorCombatEnterScanningPowerEvents()); + register(new LightningEnchantment.LightningEnchantmentEvents()); + register(new BonusCoins.BonusCoinsEvents()); + + //special powers + register(new EnderCrystalLightningRod.EnderCrystalLightningRodEvents()); + + //Custom bosses + register(new CustomBossEntity.CustomBossEntityEvents()); + register(new CustomBossDeath()); + register(new SimplePersistentEntity.PersistentEntityEvent()); + register(new CustomBossTaunts()); + register(new PhaseBossEntity.PhaseBossEntityListener()); + register(new RegionalBossEntity.RegionalBossEntityEvents()); + register(new AdvancedAggroManager()); + register(new TransitiveBossBlock()); + register(new TransitiveBlockCommand.TemporaryBossBlockCommandEvents()); + register(new CustomModel.ModelEntityEvents()); //Metadata (player purger) - pluginManager.registerEvents(new MetadataHandler(), plugin); + register(new MetadataHandler()); - //Mob merger TODO: maybe add a config scan here? - pluginManager.registerEvents(new MergeHandler(), plugin); + //Mob merger + register(new MergeHandler()); //Natural EliteMobs Spawning - if (ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.NATURAL_MOB_SPAWNING)) { - pluginManager.registerEvents(new NaturalEliteMobSpawnEventHandler(), plugin); - pluginManager.registerEvents(new EntityTracker(), plugin); - } + register(new EntityTracker()); + //Fix lingering entity after crashes + register(new CrashFix()); //Natural Mob Metadata Assigner - pluginManager.registerEvents(new NaturalMobSpawnEventHandler(), plugin); + register(new NaturalMobSpawnEventHandler()); //Visual effects - pluginManager.registerEvents(new EffectEventHandlers(), plugin); - if (ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.OBFUSCATE_MOB_POWERS)) - pluginManager.registerEvents(new VisualEffectObfuscator(), plugin); + register(new EffectEventHandlers()); + if (MobCombatSettingsConfig.isObfuscateMobPowers()) + register(new VisualEffectObfuscator()); //Loot - if (ConfigValues.itemsDropSettingsConfig.getBoolean(ItemsDropSettingsConfig.ENABLE_PLUGIN_LOOT)) { - pluginManager.registerEvents(new LootTables(), plugin); - pluginManager.registerEvents(new PlaceEventPrevent(), plugin); + if (ItemSettingsConfig.isDoEliteMobsLoot()) { + register(new LootTables()); + register(new PlaceEventPrevent()); } + //player status menu + register(new CoverPage.CoverPageEvents()); + register(new StatsPage.StatsPageEvents()); + register(new GearPage.GearPageEvents()); + register(new TeleportsPage.TeleportsPageEvents()); + register(new CommandsPage.CommandsPageEvents()); + register(new BossTrackingPage.BossTrackingPageEvents()); + //Shops - pluginManager.registerEvents(new ShopHandler(), plugin); - pluginManager.registerEvents(new CustomShopHandler(), plugin); - pluginManager.registerEvents(new ItemSaleEvent(), plugin); + register(new ProceduralShopMenu()); + register(new CustomShopMenu()); + register(new BuyOrSellMenu()); + register(new SellMenu()); + register(new SetupMenu.SetupMenuListeners()); + register(new ScrapperMenu.ScrapperMenuEvents()); + register(new SmeltMenu.SmeltMenuEvents()); + register(new RepairMenu.RepairMenuEvents()); + register(new RefinerMenu.RefinerMenuEvents()); + register(new EnhancementMenu.EnhancementMenuEvents()); + register(new UnbindMenu.UnbinderMenuEvents()); //Minecraft behavior canceller - pluginManager.registerEvents(new ChunkUnloadMetadataPurge(), plugin); - pluginManager.registerEvents(new EntityDeathDataFlusher(), plugin); - if (ConfigValues.defaultConfig.getBoolean(DefaultConfig.CREEPER_PASSIVE_DAMAGE_PREVENTER)) - pluginManager.registerEvents(new PreventCreeperPassiveEntityDamage(), plugin); - //Prevent exploits - //Prevent mount exploit - if (ConfigValues.defaultConfig.getBoolean(DefaultConfig.PREVENT_MOUNT_EXPLOIT)) - pluginManager.registerEvents(new PreventMountExploit(), plugin); - //Prevent darkroom exploit - if (ConfigValues.defaultConfig.getBoolean(DefaultConfig.PREVENT_DARKROOM_EXPLOIT)) - pluginManager.registerEvents(new PreventDarkroomExploit(), plugin); - //Prevent tower exploit - if (ConfigValues.defaultConfig.getBoolean(DefaultConfig.PREVENT_TOWER_EXPLOIT)) - pluginManager.registerEvents(new PreventTowerExploit(), plugin); - - - if (!VersionChecker.currentVersionIsUnder(11, 0)) { - //Initialize custom events - pluginManager.registerEvents(new SmallTreasureGoblin(), plugin); - pluginManager.registerEvents(new TreasureGoblin(), plugin); - pluginManager.registerEvents(new DeadMoon(), plugin); - pluginManager.registerEvents(new TheReturned(), plugin); - pluginManager.registerEvents(new ZombieKing(), plugin); - pluginManager.registerEvents(new SpiritWalk(), plugin); - - if (ConfigValues.eventsConfig.getBoolean(EventsConfig.KRAKEN_ENABLED)) { - pluginManager.registerEvents(new Kraken(), plugin); - pluginManager.registerEvents(new KrakenEvent(), plugin); - } - if (ConfigValues.eventsConfig.getBoolean(EventsConfig.BALROG_ENABLED)) { - pluginManager.registerEvents(new Balrog(), plugin); - pluginManager.registerEvents(new BalrogEvent(), plugin); - } - if (ConfigValues.eventsConfig.getBoolean(EventsConfig.FAE_ENABLED)) { - pluginManager.registerEvents(new FaeEvent(), plugin); - pluginManager.registerEvents(new Fae(), plugin); - } + if (DefaultConfig.isPreventCreeperDamageToPassiveMobs()) + register(new PreventCreeperPassiveEntityDamage()); + if (!VersionChecker.serverVersionOlderThan(16, 0)) + register(new PreventEliteBeeHiveEnter()); + register(new EnderDragonUnstuck()); + if (DefaultConfig.isPreventVanillaReinforcementsForEliteEntities()) + register(new VanillaReinforcementsCanceller()); + register(new LightningSpawnBypass()); + if (ItemSettingsConfig.isEliteDurability()) + register(new AlternativeDurabilityLoss()); + register(new EnderCrystalDamageProtectionBypass()); + + + //Antiexploits + register(new PreventMountExploit()); + register(new PreventDarkroomExploit()); + register(new PreventLargeDarkroomExploit()); + register(new PreventTowerExploit()); + register(new PreventEndermanHeightExploit()); + if (AntiExploitConfig.isNoItemPickup()) + register(new PreventItemPickupByMobs()); + if (AntiExploitConfig.isAmbientDamageExploit()) + register(new AmbientDamageExploit()); + if (!VersionChecker.serverVersionOlderThan(14, 0)) { + register(new HoneyBlockJumpExploit()); } + register(new EliteMobDamagedByPlayerAntiExploitListener()); + register(new ActionEvent.ActionEventEvents()); //Set up health and damage displays - if (ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.DISPLAY_HEALTH_ON_HIT)) - pluginManager.registerEvents(new HealthDisplay(), plugin); - if (ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.DISPLAY_DAMAGE_ON_HIT)) - pluginManager.registerEvents(new DamageDisplay(), plugin); + if (MobCombatSettingsConfig.isDisplayHealthOnHit()) + register(new HealthDisplay()); + if (MobCombatSettingsConfig.isDisplayDamageOnHit()) + register(new PopupDisplay()); //Initialize items from custom events - pluginManager.registerEvents(new FlamethrowerEnchantment(), plugin); + register(new FlamethrowerEnchantment.FlamethrowerEnchantmentEvents()); + register(new SummonMerchantEnchantment.SummonMerchantEvents()); + register(new SummonWolfEnchantment.SummonWolfEnchantmentEvent()); + register(new MeteorShowerEnchantment.MeteorShowerEvents()); + register(new DrillingEnchantment.DrillingEnchantmentEvents()); + register(new IceBreakerEnchantment.IceBreakerEnchantmentEvent()); + register(new GrapplingHookEnchantment.GrapplingHookEnchantmentEvents()); + register(new EarthquakeEnchantment.EarthquakeEnchantmentEvents()); + //register(new UnbindEnchantment.UnbindEvents()); //Initialize adventurer's guild - pluginManager.registerEvents(new AdventurersGuildGUI(), plugin); + register(new GuildRankMenuHandler()); + register(new WorldSwitchBehavior()); + //register quests + register(new KillObjective.KillObjectiveEvents()); + register(new CustomFetchObjective.CustomFetchObjectiveEvents()); + register(new DialogObjective.DialogObjectiveEvents()); + register(new QuestAcceptEvent.QuestAcceptEventHandler()); + register(new QuestCompleteEvent.QuestCompleteEventHandler()); + register(new QuestLeaveEvent.QuestLeaveEventHandler()); + register(new QuestProgressionEvent.QuestProgressionEventHandler()); + register(new QuestTracking.QuestTrackingEvents()); + register(new CustomQuest.CustomQuestEvents()); + register(new QuestInventoryMenu.QuestInventoryMenuEvents()); + + //Arenas + register(new ArenaMenu.ArenaMenuEvents()); + register(new ArenaInstance.ArenaInstanceEvents()); + register(new MatchInstance.MatchInstanceEvents()); //Combat tag - if (ConfigValues.combatTagConfig.getBoolean(CombatTagConfig.ENABLE_COMBAT_TAG)) - pluginManager.registerEvents(new CombatTag(), plugin); + if (CombatTagConfig.isEnableCombatTag()) + register(new CombatTag()); - //Prevent elitemob on elitemob aggro - pluginManager.registerEvents(new AggroPrevention(), plugin); - //Refresh display case Elite Mobs - pluginManager.registerEvents(new DisplayMob(), plugin); + //Prevent elitemob on elitemob aggro + register(new EnderDragonUnstuck.AggroPrevention()); //Player effect when a rare item is on the ground - if (ConfigValues.itemsDropSettingsConfig.getBoolean(ItemsDropSettingsConfig.ENABLE_RARE_DROP_EFFECT)) - pluginManager.registerEvents(new RareDropEffect(), plugin); + register(new RareDropEffect()); + + //NPCs + register(new NPCDamageEvent()); + register(new NPCInteractions()); + register(new NPCProximitySensor()); + register(new FindNewWorlds()); + register(new WorldGuardSpawnEventBypasser()); + register(new WorldGuardEliteMobOnlySpawnFlag()); + register(new WorldGuardDungeonFlag()); + + register(new EntityTransformHandler()); + register(new EliteBlazeWaterDamagePrevention()); + register(new PreventEliteEquipmentDrop()); + register(new CombustionPrevention()); + + register(new TreasureChest.TreasureChestEvents()); + + //Zone based spawning + register(new ZoneWarner()); + register(new DaylightWatchdog()); + + //On death commands + register(new OnDeathCommands()); + + //Player stuff + register(new GuildRank.GuildRankEvents()); + + //Commands + register(new RemoveCommand.RemoveCommandEvents()); + + } + private static void register(Listener listener) { + pluginManager.registerEvents(listener, plugin); } } diff --git a/src/main/java/com/magmaguy/elitemobs/MetadataHandler.java b/src/main/java/com/magmaguy/elitemobs/MetadataHandler.java index c6ca774fa..1030bfde6 100644 --- a/src/main/java/com/magmaguy/elitemobs/MetadataHandler.java +++ b/src/main/java/com/magmaguy/elitemobs/MetadataHandler.java @@ -1,18 +1,3 @@ -/* - * 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 . - */ - package com.magmaguy.elitemobs; import org.bukkit.Bukkit; @@ -32,13 +17,10 @@ public class MetadataHandler implements Listener { //plugin name public final static String ELITE_MOBS = "EliteMobs"; - - //plugin getter - public final static Plugin PLUGIN = Bukkit.getPluginManager().getPlugin(MetadataHandler.ELITE_MOBS); - //third party compatibility public final static String BETTERDROPS_COMPATIBILITY_MD = "betterdrops_ignore"; - public final static String VANISH_NO_PACKET = "vanished"; + //plugin getter + public static Plugin PLUGIN = Bukkit.getPluginManager().getPlugin(MetadataHandler.ELITE_MOBS); } diff --git a/src/main/java/com/magmaguy/elitemobs/adventurersguild/AdventurersGuildGUI.java b/src/main/java/com/magmaguy/elitemobs/adventurersguild/AdventurersGuildGUI.java deleted file mode 100644 index d0c65720c..000000000 --- a/src/main/java/com/magmaguy/elitemobs/adventurersguild/AdventurersGuildGUI.java +++ /dev/null @@ -1,382 +0,0 @@ -package com.magmaguy.elitemobs.adventurersguild; - -import com.magmaguy.elitemobs.ChatColorConverter; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.EconomySettingsConfig; -import com.magmaguy.elitemobs.economy.EconomyHandler; -import com.magmaguy.elitemobs.playerdata.PlayerData; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemFlag; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.inventory.meta.SkullMeta; - -import java.util.Arrays; -import java.util.List; - -public class AdventurersGuildGUI implements Listener { - - private static ItemStack difficulty = new ItemStack(Material.DIAMOND_SWORD); - private static ItemStack quest = skullItemInitializer("MHF_Question", "Quests", Arrays.asList("Coming soon!")); - - public static void mainMenu(Player player) { - - Inventory mainMenu = Bukkit.createInventory(player, 27, "Adventurer's guild"); - - difficulty = new ItemStack(Material.DIAMOND_SWORD); - ItemMeta difficultyMeta = difficulty.getItemMeta(); - difficultyMeta.setDisplayName("Difficulty"); - difficultyMeta.setLore(Arrays.asList("Press me to select a difficulty!")); - difficultyMeta.addItemFlags(ItemFlag.HIDE_ATTRIBUTES); - difficulty.setItemMeta(difficultyMeta); - - quest = skullItemInitializer("MHF_Question", "Quests", Arrays.asList("Coming soon!")); - - mainMenu.setItem(11, difficulty); - mainMenu.setItem(15, quest); - - player.openInventory(mainMenu); - - } - - public static void difficultyMenu(Player player) { - - Inventory difficultyMenu = Bukkit.createInventory(player, 27, "Guild rank selector"); - - if (!PlayerData.playerMaxGuildRank.containsKey(player.getUniqueId())) { - PlayerData.playerMaxGuildRank.put(player.getUniqueId(), 10); - PlayerData.playerMaxGuildRankChanged = true; - } - - if (!PlayerData.playerSelectedGuildRank.containsKey(player.getUniqueId())) { - PlayerData.playerSelectedGuildRank.put(player.getUniqueId(), 10); - PlayerData.playerSelectedGuildRankChanged = true; - } - - for (int i = 1; i < 21; i++) { - - ItemStack itemStack = null; - - if (i <= PlayerData.playerMaxGuildRank.get(player.getUniqueId())) - itemStack = difficultyItemStackConstructor(guildRankStatus.UNLOCKED, i, player); - if (i > PlayerData.playerMaxGuildRank.get(player.getUniqueId())) - itemStack = difficultyItemStackConstructor(guildRankStatus.LOCKED, i, player); - if (i == PlayerData.playerSelectedGuildRank.get(player.getUniqueId())) - itemStack = difficultyItemStackConstructor(guildRankStatus.SELECTED, i, player); - if (i == PlayerData.playerMaxGuildRank.get(player.getUniqueId()) + 1) { - itemStack = difficultyItemStackConstructor(guildRankStatus.NEXT_UNLOCK, i, player); - - } - - difficultyMenu.addItem(itemStack); - - } - - player.openInventory(difficultyMenu); - - } - - private static ItemStack difficultyItemStackConstructor(guildRankStatus guildRankStatus, int rank, Player player) { - - ItemStack itemStack = null; - - switch (guildRankStatus) { - - case UNLOCKED: - itemStack = new ItemStack(Material.STAINED_GLASS_PANE, 1, (byte) 7); - ItemMeta unlockedMeta = itemStack.getItemMeta(); - String lowTierWarning = ""; - if (rank < 10) lowTierWarning = ChatColorConverter.convert("&cElites can't drop better loot!"); - else lowTierWarning = ChatColorConverter.convert("&aElites can drop better loot!"); - unlockedMeta.setLore(Arrays.asList( - ChatColorConverter.convert("&f&m-------------------------------"), - ChatColorConverter.convert( "&aThis rank is unlocked!"), - ChatColorConverter.convert("&fYou can select it."), - lowTierWarning, - ChatColorConverter.convert("&f&m-------------------------------"), - lootBonus(rank), - mobSpawning(rank), - difficultyBonus(rank))); - itemStack.setItemMeta(unlockedMeta); - break; - case LOCKED: - itemStack = new ItemStack(Material.STAINED_GLASS_PANE, 1, (byte) 14); - ItemMeta lockedMeta = itemStack.getItemMeta(); - lockedMeta.setLore(Arrays.asList( - ChatColorConverter.convert("&f&m-------------------------------"), - ChatColorConverter.convert("&cThis rank is locked!"), - ChatColorConverter.convert("&cYou need rank " + (PlayerData.playerMaxGuildRank.get(player.getUniqueId()) + 1) + " first!"), - ChatColorConverter.convert("&f&m-------------------------------"), - lootBonus(rank), - mobSpawning(rank), - difficultyBonus(rank))); - itemStack.setItemMeta(lockedMeta); - break; - case SELECTED: - itemStack = new ItemStack(Material.STAINED_GLASS_PANE, 1, (byte) 5); - ItemMeta selectedMeta = itemStack.getItemMeta(); - String tierWarning = ""; - if (rank < 10) tierWarning = ChatColorConverter.convert("&cElites can't drop better loot!"); - else tierWarning = ChatColorConverter.convert("&aElites can drop better loot!"); - selectedMeta.setLore(Arrays.asList( - ChatColorConverter.convert("&f&m-------------------------------"), - ChatColorConverter.convert("&aThis is your current rank!"), - tierWarning, - ChatColorConverter.convert("&f&m-------------------------------"), - lootBonus(rank), - mobSpawning(rank), - difficultyBonus(rank))); - itemStack.setItemMeta(selectedMeta); - PlayerData.playerSelectedGuildRankChanged = true; - break; - case NEXT_UNLOCK: - itemStack = new ItemStack(Material.STAINED_GLASS_PANE, 1, (byte) 1); - ItemMeta nextMeta = itemStack.getItemMeta(); - String priceString = ""; - if (!PlayerData.playerCurrency.containsKey(player.getUniqueId())) PlayerData.playerCurrency.put(player.getUniqueId(), 0.0); - if (tierPriceCalculator(rank) > PlayerData.playerCurrency.get(player.getUniqueId())) - priceString = "&c" + tierPriceCalculator(rank); - else - priceString = "&a" + tierPriceCalculator(rank); - nextMeta.setLore(Arrays.asList( - ChatColorConverter.convert("&f&m-------------------------------"), - ChatColorConverter.convert("&6This is the next rank you can unlock"), - ChatColorConverter.convert("&aSelect it when you're ready!"), - ChatColorConverter.convert("&6Costs " + priceString + " &6" + ConfigValues.economyConfig.getString(EconomySettingsConfig.CURRENCY_NAME)), - ChatColorConverter.convert("&fYou have &a" + PlayerData.playerCurrency.get(player.getUniqueId()) + " &f" + ConfigValues.economyConfig.getString(EconomySettingsConfig.CURRENCY_NAME)), - ChatColorConverter.convert("&f&m-------------------------------"), - lootBonus(rank), - mobSpawning(rank), - difficultyBonus(rank))); - itemStack.setItemMeta(nextMeta); - PlayerData.playerMaxGuildRankChanged = true; - break; - } - - ItemMeta itemMeta = itemStack.getItemMeta(); - itemMeta.setDisplayName(rankNamer(rank) + " rank"); - itemStack.setItemMeta(itemMeta); - - return itemStack; - - } - - private static String rankNamer(int rank) { - - String name = ""; - - if (rank == 1) name = "&8Peaceful Villager"; - if (rank == 2) name = "&8Commoner"; - if (rank == 3) name = "&8Farmer"; - if (rank == 4) name = "&8Bard"; - if (rank == 5) name = "&8Barkeep"; - if (rank == 6) name = "&8Blacksmith"; - if (rank == 7) name = "&8Merchant"; - if (rank == 8) name = "&8Wanderer"; - if (rank == 9) name = "&8Ranger"; - if (rank == 10) name = "&fCasual Adventurer"; - if (rank == 11) name = "&fAdventurer"; - if (rank == 12) name = "&fProfessional Adventurer"; - if (rank == 13) name = "&2Elite Adventurer"; - if (rank == 14) name = "&2Master Adventurer"; - if (rank == 15) name = "&2Raider"; - if (rank == 16) name = "&1Slayer"; - if (rank == 17) name = "&1Exterminator"; - if (rank == 18) name = "&5&lElite HunterEnchantment"; - if (rank == 19) name = "&5Hero"; - if (rank == 20) name = "&6&l&oLegend"; - - return ChatColorConverter.convert(name); - - } - - private static String mobSpawning(int rank) { - - int mobSpawning = 0; - - if (rank == 1) mobSpawning = 10; - if (rank == 2) mobSpawning = 20; - if (rank == 3) mobSpawning = 30; - if (rank == 4) mobSpawning = 40; - if (rank == 5) mobSpawning = 50; - if (rank == 6) mobSpawning = 60; - if (rank == 7) mobSpawning = 70; - if (rank == 8) mobSpawning = 80; - if (rank == 9) mobSpawning = 90; - if (rank == 10) mobSpawning = 100; - if (rank == 11) mobSpawning = 120; - if (rank == 12) mobSpawning = 140; - if (rank == 13) mobSpawning = 160; - if (rank == 14) mobSpawning = 180; - if (rank == 15) mobSpawning = 200; - if (rank == 16) mobSpawning = 220; - if (rank == 17) mobSpawning = 240; - if (rank == 18) mobSpawning = 260; - if (rank == 19) mobSpawning = 280; - if (rank == 20) mobSpawning = 300; - - return ChatColorConverter.convert("&fElite Mob spawn rate modifier: &c" + mobSpawning + "%"); - - } - - private static String lootBonus(int rank) { - - int lootBonus = 0; - - if (rank == 1) lootBonus = 10; - if (rank == 2) lootBonus = 20; - if (rank == 3) lootBonus = 30; - if (rank == 4) lootBonus = 40; - if (rank == 5) lootBonus = 50; - if (rank == 6) lootBonus = 60; - if (rank == 7) lootBonus = 70; - if (rank == 8) lootBonus = 80; - if (rank == 9) lootBonus = 90; - if (rank == 10) lootBonus = 100; - if (rank == 11) lootBonus = 120; - if (rank == 12) lootBonus = 140; - if (rank == 13) lootBonus = 160; - if (rank == 14) lootBonus = 180; - if (rank == 15) lootBonus = 200; - if (rank == 16) lootBonus = 220; - if (rank == 17) lootBonus = 240; - if (rank == 18) lootBonus = 260; - if (rank == 19) lootBonus = 280; - if (rank == 20) lootBonus = 300; - - return ChatColorConverter.convert("&fElite Mob loot modifier: &a" + lootBonus + "%"); - - } - - private static String difficultyBonus(int rank) { - - int difficultyBonus = 0; - - if (rank == 1) difficultyBonus = 10; - if (rank == 2) difficultyBonus = 20; - if (rank == 3) difficultyBonus = 30; - if (rank == 4) difficultyBonus = 40; - if (rank == 5) difficultyBonus = 50; - if (rank == 6) difficultyBonus = 60; - if (rank == 7) difficultyBonus = 70; - if (rank == 8) difficultyBonus = 80; - if (rank == 9) difficultyBonus = 90; - if (rank == 10) difficultyBonus = 100; - if (rank == 11) difficultyBonus = 110; - if (rank == 12) difficultyBonus = 120; - if (rank == 13) difficultyBonus = 130; - if (rank == 14) difficultyBonus = 140; - if (rank == 15) difficultyBonus = 150; - if (rank == 16) difficultyBonus = 160; - if (rank == 17) difficultyBonus = 170; - if (rank == 18) difficultyBonus = 180; - if (rank == 19) difficultyBonus = 190; - if (rank == 20) difficultyBonus = 200; - - return ChatColorConverter.convert("&fElite Mob difficulty modifier: &4" + difficultyBonus + "%"); - - } - - private enum guildRankStatus { - UNLOCKED, - SELECTED, - NEXT_UNLOCK, - LOCKED - } - - private static void questMenu(Player player) { - - player.closeInventory(); - player.sendMessage("Coming soon!"); - - } - - private static ItemStack skullItemInitializer(String mhfValue, String title, List lore) { - - ItemStack item = new ItemStack(Material.SKULL_ITEM, 1, (short) 3); - ItemMeta itemMeta = item.getItemMeta(); - SkullMeta skullMeta = (SkullMeta) itemMeta; - skullMeta.setOwner(mhfValue); - item.setItemMeta(skullMeta); - itemMeta.setDisplayName(title); - itemMeta.setLore(lore); - item.setItemMeta(itemMeta); - - return item; - - } - - private static int tierPriceCalculator(int tier) { - - return (tier - 10) * (tier - 10) * 1000; - - } - - @EventHandler - public void onMainMenuClick(InventoryClickEvent event) { - - if (!(event.getWhoClicked() instanceof Player)) return; - if (!event.getInventory().getName().equalsIgnoreCase("Adventurer's guild")) return; - if (event.getCurrentItem() == null || event.getCurrentItem().getType().equals(Material.AIR)) return; - if (event.getCurrentItem().equals(difficulty)) - difficultyMenu((Player) event.getWhoClicked()); - if (event.getCurrentItem().equals(quest)) { - event.getWhoClicked().closeInventory(); - event.getWhoClicked().sendMessage("Coming soon!"); - } - - event.setCancelled(true); - - } - - @EventHandler - public void onRankSelectorClick(InventoryClickEvent event) { - - if (!(event.getWhoClicked() instanceof Player)) return; - if (!event.getInventory().getName().equalsIgnoreCase("Guild rank selector")) return; - if (event.getCurrentItem() == null || event.getCurrentItem().getType().equals(Material.AIR)) return; - - event.setCancelled(true); - - if (!event.getClickedInventory().getName().equals("Guild rank selector")){ - event.setCancelled(true); - return; - } - - int maxTier = PlayerData.playerMaxGuildRank.get(event.getWhoClicked().getUniqueId()); - int selectedTier = event.getSlot() + 1; - - if (selectedTier < maxTier + 1) { - PlayerData.playerSelectedGuildRank.put(event.getWhoClicked().getUniqueId(), selectedTier); - difficultyMenu((Player) event.getWhoClicked()); - } - - if (selectedTier == maxTier + 1) { - if (EconomyHandler.checkCurrency(event.getWhoClicked().getUniqueId()) < tierPriceCalculator(selectedTier)) - event.getWhoClicked().sendMessage("[EliteMobs] You don't have enough Elite Coins! Sell some Elite Mob loot to [/em shop]!"); - else { - EconomyHandler.subtractCurrency(event.getWhoClicked().getUniqueId(), tierPriceCalculator(selectedTier)); - PlayerData.playerMaxGuildRank.put(event.getWhoClicked().getUniqueId(), selectedTier); - event.getWhoClicked().sendMessage(ChatColorConverter.convert("&aYou have unlocked the " + rankNamer(selectedTier) + " &arank for " + - tierPriceCalculator(selectedTier) + " " + ConfigValues.economyConfig.getString(EconomySettingsConfig.CURRENCY_NAME) + ". \n&6Happy hunting!")); - difficultyMenu((Player) event.getWhoClicked()); - Bukkit.broadcastMessage(ChatColorConverter.convert( - ((Player) event.getWhoClicked()).getDisplayName() + " has reached the " + rankNamer(selectedTier) + " &fguild rank!")); - } - } - - if (selectedTier > maxTier + 1) { - event.getWhoClicked().sendMessage("[EliteMobs] You need to unlock other ranks first!"); - } - - - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/adventurersguild/GuildRank.java b/src/main/java/com/magmaguy/elitemobs/adventurersguild/GuildRank.java index c477230b3..ee129bc38 100644 --- a/src/main/java/com/magmaguy/elitemobs/adventurersguild/GuildRank.java +++ b/src/main/java/com/magmaguy/elitemobs/adventurersguild/GuildRank.java @@ -1,20 +1,248 @@ package com.magmaguy.elitemobs.adventurersguild; -import com.magmaguy.elitemobs.playerdata.PlayerData; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.config.AdventurersGuildConfig; +import com.magmaguy.elitemobs.playerdata.ElitePlayerInventory; +import com.magmaguy.elitemobs.playerdata.database.PlayerData; +import com.magmaguy.elitemobs.utils.Round; +import org.bukkit.attribute.Attribute; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.scheduler.BukkitRunnable; import java.util.UUID; public class GuildRank { - public static int getGuildRank (UUID uuid) { + private GuildRank() { + } + + public static void setGuildPrestigeRank(Player player, int prestigeRank) { + PlayerData.setGuildPrestigeLevel(player.getUniqueId(), prestigeRank); + ElitePlayerInventory.playerInventories.get(player.getUniqueId()).getFullPlayerTier(true); + } + + public static int getGuildPrestigeRank(Player player) { + return getGuildPrestigeRank(player.getUniqueId()); + } + + public static int getGuildPrestigeRank(UUID player) { + return PlayerData.getGuildPrestigeLevel(player); + } + + public static int getGuildPrestigeRank(Player player, boolean databaseAccess) { + return PlayerData.getGuildPrestigeLevel(player.getUniqueId(), databaseAccess); + } - if (PlayerData.playerSelectedGuildRank.containsKey(uuid)) - return PlayerData.playerSelectedGuildRank.get(uuid); + public static void setMaxGuildRank(Player player, int maxGuildRank) { + PlayerData.setMaxGuildLevel(player.getUniqueId(), maxGuildRank); + } + + public static int getMaxGuildRank(Player player) { + return PlayerData.getMaxGuildLevel(player.getUniqueId()); + } - PlayerData.playerSelectedGuildRank.put(uuid, 10); + public static int getMaxGuildRank(Player player, boolean databaseAccess) { + return PlayerData.getMaxGuildLevel(player.getUniqueId(), databaseAccess); + } + + public static void setActiveGuildRank(Player player, int activeGuildRank) { + PlayerData.setActiveGuildLevel(player.getUniqueId(), activeGuildRank); + setMaxHealth(player, activeGuildRank, getGuildPrestigeRank(player)); + } + + public static int getActiveGuildRank(Player player) { + return PlayerData.getActiveGuildLevel(player.getUniqueId()); + } + + public static int getActiveGuildRank(Player player, boolean databaseAccess) { + return PlayerData.getActiveGuildLevel(player.getUniqueId(), databaseAccess); + } + + /** + * Returns whether the player's maximum guild rank is below or equal to the rank to be compared. + * + * @param player Player whose maximum rank will be checked + * @param maxGuildLevel Target guild rank + * @return Whether the player's guild rank is below or equal to the target + */ + public static boolean isWithinMaxGuildRank(Player player, int prestigeLevel, int maxGuildLevel) { + return getGuildPrestigeRank(player) >= prestigeLevel && + getMaxGuildRank(player) >= maxGuildLevel; + } + + public static boolean isWithinMaxGuildRankIgnorePrestige(Player player, int maxGuildLevel) { + return getMaxGuildRank(player) >= maxGuildLevel; + } - return PlayerData.playerSelectedGuildRank.get(uuid); + /** + * Checks if the player's active guild rank is below or equal to the target rank. + * + * @param player Player whose active guild rank will be checked + * @param activeGuildLevel Target rank to check + * @return Whether the target rank is equal to or higher than the player's active guild rank + */ + public static boolean isWithinActiveGuildRank(Player player, int prestigeLevel, int activeGuildLevel) { + return getGuildPrestigeRank(player) >= prestigeLevel && + getActiveGuildRank(player) >= activeGuildLevel; + } + + public static boolean isWithinActiveGuildRankIgnorePrestige(Player player, int activeGuildLevel) { + return getActiveGuildRank(player) >= activeGuildLevel; + } + + /** + * Returns the name of the rank as set by the configuration + * + * @return Name of the rank + */ + public static String getRankName(int prestige, int rank) { + return AdventurersGuildConfig.getRankName(prestige, rank); + } + + public static void setMaxHealth(Player player, int activeGuildRank, int prestigeRank) { + if (!AdventurersGuildConfig.isAddMaxHealth()) return; + double guildRankBonus = healthBonusValue(prestigeRank, activeGuildRank); + double newMaxHealth = 20 + guildRankBonus; + player.getAttribute(Attribute.GENERIC_MAX_HEALTH).setBaseValue(newMaxHealth); + } + + public static void setMaxHealth(Player player) { + setMaxHealth(player, PlayerData.getActiveGuildLevel(player.getUniqueId()), PlayerData.getGuildPrestigeLevel(player.getUniqueId())); + } + + public static double lootTierValue(int activeGuildRank) { + return activeGuildRank * 10; + } + + public static double currencyBonusMultiplier(int prestigeLevel) { + return 1D + prestigeLevel * 5; + } + + public static double currencyBonusMultiplier(UUID player) { + return currencyBonusMultiplier(getGuildPrestigeRank(player)); + } + + /** + * Returns the per-tier max health, taking prestige ranks into account + * + * @param prestigeLevel + * @param guildRank + * @return + */ + public static double healthBonusValue(int prestigeLevel, int guildRank) { + if (!AdventurersGuildConfig.isAddMaxHealth()) return 0; + double prestigeBonus = 0; + switch (prestigeLevel) { + case 0: + prestigeBonus = 0; + break; + case 1: + case 2: + case 3: + prestigeBonus = AdventurersGuildConfig.getHealth1(); + break; + case 4: + case 5: + case 6: + prestigeBonus = AdventurersGuildConfig.getHealth2(); + break; + case 7: + case 8: + case 9: + prestigeBonus = AdventurersGuildConfig.getHealth3(); + break; + case 10: + prestigeBonus = AdventurersGuildConfig.getHealth4(); + break; + } + return prestigeBonus * guildRank; + } + + /** + * Returns the per-tier dodge multiplier, taking prestige ranks into account + * + * @param prestigeLevel + * @param guildRank + * @return + */ + public static double dodgeBonusValue(int prestigeLevel, int guildRank) { + if (!AdventurersGuildConfig.isAddDodge()) return 0; + double prestigeBonus = 0; + switch (prestigeLevel) { + case 0: + case 1: + case 2: + prestigeBonus = 0; + break; + case 3: + case 4: + case 5: + prestigeBonus = AdventurersGuildConfig.getDodge1(); + break; + case 6: + case 7: + case 8: + prestigeBonus = AdventurersGuildConfig.getDodge2(); + break; + case 9: + case 10: + prestigeBonus = AdventurersGuildConfig.getDodge3(); + break; + } + return Round.twoDecimalPlaces(guildRank / (10D + prestigeLevel) * prestigeBonus); + } + + /** + * Returns the per-tier crit multiplier, taking prestige ranks into account + * + * @param prestigeLevel + * @param guildRank + * @return + */ + public static double critBonusValue(int prestigeLevel, int guildRank) { + if (!AdventurersGuildConfig.isAddCrit()) return 0; + double prestigeBonus = 0; + switch (prestigeLevel) { + case 0: + case 1: + prestigeBonus = 0; + break; + case 2: + case 3: + case 4: + prestigeBonus = AdventurersGuildConfig.getCrit1(); + break; + case 5: + case 6: + case 7: + prestigeBonus = AdventurersGuildConfig.getCrit2(); + break; + case 8: + case 9: + case 10: + prestigeBonus = AdventurersGuildConfig.getCrit3(); + break; + } + return Round.twoDecimalPlaces(guildRank / (10D + prestigeLevel) * prestigeBonus); + } + + public static class GuildRankEvents implements Listener { + @EventHandler + public void onPlayerJoin(PlayerJoinEvent event) { + new BukkitRunnable() { + @Override + public void run() { + if (event.getPlayer().isOnline()) + setMaxHealth(event.getPlayer(), + GuildRank.getActiveGuildRank(event.getPlayer(), true), + GuildRank.getGuildPrestigeRank(event.getPlayer(), true)); + } + }.runTaskLater(MetadataHandler.PLUGIN, 20 * 3); + } } } diff --git a/src/main/java/com/magmaguy/elitemobs/adventurersguild/GuildRankMenuHandler.java b/src/main/java/com/magmaguy/elitemobs/adventurersguild/GuildRankMenuHandler.java new file mode 100644 index 000000000..5ed9459e1 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/adventurersguild/GuildRankMenuHandler.java @@ -0,0 +1,350 @@ +package com.magmaguy.elitemobs.adventurersguild; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.config.AdventurersGuildConfig; +import com.magmaguy.elitemobs.config.EconomySettingsConfig; +import com.magmaguy.elitemobs.config.menus.premade.GuildRankMenuConfig; +import com.magmaguy.elitemobs.economy.EconomyHandler; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; + +public class GuildRankMenuHandler implements Listener { + + private static final HashSet inventories = new HashSet<>(); + private static final ArrayList rankSlots = new ArrayList<>(Arrays.asList( + 4, 11, 12, 13, 14, 15, 20, 21, 22, 23, 24, 29, 30, 31, 32, 33, 38, 39, 40, 41, 42)); + private static final int prestigeRankSlot = 49; + + private static void selectUnlockedRank(Player player, int guildRank) { + GuildRank.setActiveGuildRank(player, guildRank); + } + + private static void selectRankToUnlock(Player player, int guildRank) { + double price = tierPriceCalculator(guildRank, GuildRank.getGuildPrestigeRank(player)); + if (EconomyHandler.checkCurrency(player.getUniqueId()) < price) { + player.sendMessage(GuildRankMenuConfig.getNotEnoughCurrencyMessage() + .replace("$neededAmount", tierPriceCalculator(guildRank, GuildRank.getGuildPrestigeRank(player)) + "") + .replace("$currentAmount", EconomyHandler.checkCurrency(player.getUniqueId()) + "") + .replace("$currencyName", EconomySettingsConfig.getCurrencyName())); + return; + } + EconomyHandler.subtractCurrency(player.getUniqueId(), price); + GuildRank.setActiveGuildRank(player, guildRank); + GuildRank.setMaxGuildRank(player, guildRank); + player.sendMessage(GuildRankMenuConfig.getUnlockMessage() + .replace("$rankName", GuildRank.getRankName(GuildRank.getGuildPrestigeRank(player), guildRank)) + .replace("$price", tierPriceCalculator(guildRank, GuildRank.getGuildPrestigeRank(player)) + "") + .replace("$currencyName", EconomySettingsConfig.getCurrencyName())); + + Bukkit.broadcastMessage(GuildRankMenuConfig.getBroadcastMessage() + .replace("$player", player.getDisplayName()) + .replace("$rankName", GuildRank.getRankName(GuildRank.getGuildPrestigeRank(player), guildRank))); + if (!AdventurersGuildConfig.getOnRankUpCommand().isEmpty()) + for (String command : AdventurersGuildConfig.getOnRankUpCommand()) + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), + command.replace("$player", player.getName()) + .replace("$prestigeRank", GuildRank.getActiveGuildRank(player) + "") + .replace("$activeRank", GuildRank.getGuildPrestigeRank(player) + "")); + } + + private static void selectPrestigeUnlock(Player player) { + if (GuildRank.getGuildPrestigeRank(player) >= 10) return; + if (GuildRank.getActiveGuildRank(player) != 10 + GuildRank.getGuildPrestigeRank(player)) + return; + if (EconomyHandler.checkCurrency(player.getUniqueId()) < tierPriceCalculator(GuildRank.getGuildPrestigeRank(player) + 12, GuildRank.getGuildPrestigeRank(player))) { + player.sendMessage(GuildRankMenuConfig.getNotEnoughCurrencyMessage() + .replace("$neededAmount", tierPriceCalculator(GuildRank.getGuildPrestigeRank(player) + 12, GuildRank.getGuildPrestigeRank(player)) + "") + .replace("$currentAmount", EconomyHandler.checkCurrency(player.getUniqueId()) + "") + .replace("$currencyName", EconomySettingsConfig.getCurrencyName())); + return; + } + EconomyHandler.setCurrency(player.getUniqueId(), 0); + GuildRank.setMaxGuildRank(player, 1); + GuildRank.setActiveGuildRank(player, 1); + GuildRank.setGuildPrestigeRank(player, GuildRank.getGuildPrestigeRank(player) + 1); + + for (Player iteratedPlayer : Bukkit.getOnlinePlayers()) { + iteratedPlayer.sendTitle( + ChatColorConverter.convert(AdventurersGuildConfig.getPrestigeUnlockMessageSubtitle().replace("$player", player.getDisplayName()) + .replace("$tier", GuildRank.getGuildPrestigeRank(player) + "")), + ChatColorConverter.convert(AdventurersGuildConfig.getPrestigeUnlockMessageSubtitle().replace("$player", player.getDisplayName()) + .replace("$tier", GuildRank.getGuildPrestigeRank(player) + ""))); + } + player.closeInventory(); + if (!AdventurersGuildConfig.getOnPrestigeUpCommand().isEmpty()) + for (String command : AdventurersGuildConfig.getOnPrestigeUpCommand()) + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), + command.replace("$player", player.getName()) + .replace("$prestigeRank", GuildRank.getActiveGuildRank(player) + "") + .replace("$activeRank", GuildRank.getGuildPrestigeRank(player) + "")); + } + + /** + * Using the following slots for the menu: + * 4 - Commoner rank + * Normal ranks: + * 11, 12, 13, 14, 15 + * 20, 21, 22, 23, 24 + * 39, 30, 31, 32, 34 + * 38, 39, 40, 41, 42 + * 49 - Prestige button + * + * @param player Player for whom the menu will be generated + * @return Returns the inventory generated + */ + public static Inventory initializeGuildRankMenu(Player player) { + Inventory difficultyMenu = Bukkit.createInventory(player, 54, GuildRankMenuConfig.getMenuName()); + difficultyMenu = populateInventory(difficultyMenu, player); + inventories.add(difficultyMenu); + player.openInventory(difficultyMenu); + return difficultyMenu; + } + + public static Inventory populateInventory(Inventory difficultyMenu, Player player) { + for (int i = 0; i < 11 + GuildRank.getGuildPrestigeRank(player); i++) { + ItemStack itemStack = null; + if (GuildRank.isWithinActiveGuildRankIgnorePrestige(player, i)) { + itemStack = difficultyItemStackConstructor(guildRankStatus.UNLOCKED, i, player, false); + } + if (GuildRank.getActiveGuildRank(player) < i && GuildRank.getMaxGuildRank(player) >= i) { + itemStack = difficultyItemStackConstructor(guildRankStatus.UNLOCKED, i, player, false); + } + if (GuildRank.getActiveGuildRank(player) == i) { + itemStack = difficultyItemStackConstructor(guildRankStatus.SELECTED, i, player, false); + } + if (GuildRank.getMaxGuildRank(player) < i) { + itemStack = difficultyItemStackConstructor(guildRankStatus.LOCKED, i, player, false); + } + if (GuildRank.getMaxGuildRank(player) + 1 == i) { + itemStack = difficultyItemStackConstructor(guildRankStatus.NEXT_UNLOCK, i, player, false); + } + difficultyMenu.setItem(rankSlots.get(i), itemStack); + } + + if (GuildRank.getGuildPrestigeRank(player) < 10) { + if (GuildRank.getActiveGuildRank(player) < 10 + GuildRank.getGuildPrestigeRank(player)) + difficultyMenu.setItem(prestigeRankSlot, difficultyItemStackConstructor + (guildRankStatus.PRESTIGE_LOCKED, GuildRank.getGuildPrestigeRank(player) + 1, player, true)); + else + difficultyMenu.setItem(prestigeRankSlot, difficultyItemStackConstructor + (guildRankStatus.PRESTIGE_NEXT_UNLOCK, GuildRank.getGuildPrestigeRank(player) + 1, player, true)); + } + + return difficultyMenu; + } + + private static ItemStack difficultyItemStackConstructor(guildRankStatus guildRankStatus, int activeGuildRank, Player player, boolean isPrestigeSlot) { + + ItemStack itemStack = null; + + String priceString = ""; + if (!isPrestigeSlot) + if (tierPriceCalculator(activeGuildRank, GuildRank.getGuildPrestigeRank(player)) > EconomyHandler.checkCurrency(player.getUniqueId())) + priceString = "&c" + tierPriceCalculator(activeGuildRank, GuildRank.getGuildPrestigeRank(player)); + else + priceString = "&a" + tierPriceCalculator(activeGuildRank, GuildRank.getGuildPrestigeRank(player)); + else { + if (tierPriceCalculator(GuildRank.getGuildPrestigeRank(player) + 12, GuildRank.getGuildPrestigeRank(player)) > EconomyHandler.checkCurrency(player.getUniqueId())) + priceString = "&c" + tierPriceCalculator(GuildRank.getGuildPrestigeRank(player) + 12, GuildRank.getGuildPrestigeRank(player)); + else + priceString = "&a" + tierPriceCalculator(GuildRank.getGuildPrestigeRank(player) + 12, GuildRank.getGuildPrestigeRank(player)); + } + switch (guildRankStatus) { + case UNLOCKED: + itemStack = constructButtonItemStack(activeGuildRank, GuildRankMenuConfig.getUnlockedButton().clone(), player, priceString); + break; + case LOCKED: + itemStack = constructButtonItemStack(activeGuildRank, GuildRankMenuConfig.getLockedButton().clone(), player, priceString); + break; + case SELECTED: + itemStack = constructButtonItemStack(activeGuildRank, GuildRankMenuConfig.getCurrentButton().clone(), player, priceString); + break; + case NEXT_UNLOCK: + itemStack = constructButtonItemStack(activeGuildRank, GuildRankMenuConfig.getNextButton().clone(), player, priceString); + break; + case PRESTIGE_LOCKED: + itemStack = constructButtonItemStack(activeGuildRank, GuildRankMenuConfig.getPrestigeLockedButton().clone(), player, priceString); + break; + case PRESTIGE_NEXT_UNLOCK: + itemStack = constructButtonItemStack(activeGuildRank, GuildRankMenuConfig.getPrestigeNextUnlockButton().clone(), player, priceString); + break; + } + + ItemMeta itemMeta = itemStack.getItemMeta(); + if (guildRankStatus.equals(GuildRankMenuHandler.guildRankStatus.UNLOCKED) || + guildRankStatus.equals(GuildRankMenuHandler.guildRankStatus.LOCKED) || + guildRankStatus.equals(GuildRankMenuHandler.guildRankStatus.SELECTED) || + guildRankStatus.equals(GuildRankMenuHandler.guildRankStatus.NEXT_UNLOCK)) + itemMeta.setDisplayName(GuildRank.getRankName(GuildRank.getGuildPrestigeRank(player), activeGuildRank)); + else + itemMeta.setDisplayName(itemMeta.getDisplayName().replace("$rank", GuildRank.getGuildPrestigeRank(player) + 1 + "")); + itemStack.setItemMeta(itemMeta); + + return itemStack; + + } + + private static ItemStack constructButtonItemStack(int activeGuildRank, ItemStack itemStack, Player player, String priceString) { + ItemMeta itemMeta = itemStack.getItemMeta(); + List newLore = new ArrayList<>(); + for (String string : itemMeta.getLore()) { + switch (string) { + case "$lootTier": + if (lootTierString(activeGuildRank) != null) + newLore.add(lootTierString(activeGuildRank)); + break; + case "$maxHealthIncrease": + if (healthBonusString(GuildRank.getGuildPrestigeRank(player), activeGuildRank) != null) + newLore.add(healthBonusString(GuildRank.getGuildPrestigeRank(player), activeGuildRank)); + break; + case "$chanceToCrit": + if (critBonusString(GuildRank.getGuildPrestigeRank(player), activeGuildRank) != null) + newLore.add(critBonusString(GuildRank.getGuildPrestigeRank(player), activeGuildRank)); + break; + case "$chanceToDodge": + if (dodgeBonusString(GuildRank.getGuildPrestigeRank(player), activeGuildRank) != null) + newLore.add(dodgeBonusString(GuildRank.getGuildPrestigeRank(player), activeGuildRank)); + break; + case "$currencyBonusMessage": + if (GuildRank.getGuildPrestigeRank(player) > 0) + newLore.add(currencyBonusString(GuildRank.getGuildPrestigeRank(player))); + break; + default: + if (string.contains("$previousRank")) { + newLore.add(string.replace("$previousRank", + (GuildRank.getRankName(GuildRank.getGuildPrestigeRank(player), GuildRank.getMaxGuildRank(player) + 1) + ""))); + continue; + } + if (string.contains("$price")) { + newLore.add( + ChatColorConverter.convert( + string.replace("$price", priceString) + .replace("$currencyName", EconomySettingsConfig.getCurrencyName()))); + continue; + } + if (string.contains("$currentCurrency")) { + newLore.add(string + .replace("$currentCurrency", EconomyHandler.checkCurrency(player.getUniqueId()) + "") + .replace("$currencyName", EconomySettingsConfig.getCurrencyName())); + continue; + } + newLore.add(string); + break; + } + } + itemMeta.setLore(newLore); + itemStack.setItemMeta(itemMeta); + return itemStack; + } + + private static String lootTierString(int activeGuildRank) { + if (!AdventurersGuildConfig.isGuildLootLimiter()) return null; + return GuildRankMenuConfig.getLootTierMessage().replace("$tier", GuildRank.lootTierValue(activeGuildRank) + ""); + } + + private static String currencyBonusString(int activeGuildRank) { + return GuildRankMenuConfig.getCurrencyBonusMessage().replace("$amount", GuildRank.currencyBonusMultiplier(activeGuildRank) + ""); + } + + private static String healthBonusString(int prestigeLevel, int guildRank) { + if (!AdventurersGuildConfig.isAddMaxHealth()) return null; + if (prestigeLevel < 1) + return null; + return GuildRankMenuConfig.getHealthBonusMessage().replace("$amount", GuildRank.healthBonusValue(prestigeLevel, guildRank) + ""); + } + + private static String critBonusString(int prestigeLevel, int guildRank) { + if (!AdventurersGuildConfig.isAddMaxHealth()) return null; + if (prestigeLevel < 3) + return null; + return GuildRankMenuConfig.getCritBonusMessage().replace("$amount", GuildRank.critBonusValue(prestigeLevel, guildRank) + ""); + } + + private static String dodgeBonusString(int prestigeLevel, int guildRank) { + if (!AdventurersGuildConfig.isAddMaxHealth()) return null; + if (prestigeLevel < 4) + return null; + return GuildRankMenuConfig.getDodgeBonusMessage().replace("$amount", GuildRank.dodgeBonusValue(prestigeLevel, guildRank) + ""); + } + + private static int tierPriceCalculator(int tier, int prestigeLevel) { + /*Logic: + tier * 10 = max mob tier + max mob tier / 2 = loot shower payout for killing 1 em at max level for that player + payout * 1000 = amount of elite mobs to kill before going up a rank + */ + double eliteMobsToKillBeforeGuildRankUp = AdventurersGuildConfig.getBaseKillsForRankUp() + AdventurersGuildConfig.getAdditionalKillsForRankUpPerTier() * (tier - 1); + return (int) ((tier - 1) * 10D / 2D * eliteMobsToKillBeforeGuildRankUp * (GuildRank.currencyBonusMultiplier(prestigeLevel))); + } + + @EventHandler + public void onRankSelectorClick(InventoryClickEvent event) { + if (!(event.getWhoClicked() instanceof Player)) return; + if (!inventories.contains(event.getInventory())) return; + event.setCancelled(true); + Player player = (Player) event.getWhoClicked(); + + if (event.getSlot() == prestigeRankSlot) { + selectPrestigeUnlock(player); + return; + } + Integer selectedRank = null; + + for (int i = 0; i < rankSlots.size(); i++) { + if (rankSlots.get(i) == event.getSlot()) { + selectedRank = i; + break; + } + } + + //Clicked nothing + if (selectedRank == null) return; + + if (GuildRank.getMaxGuildRank(player) >= selectedRank) { + selectUnlockedRank(player, selectedRank); + GuildRankMenuHandler.populateInventory(event.getInventory(), player); + return; + } + + if (GuildRank.getMaxGuildRank(player) + 1 == selectedRank) { + selectRankToUnlock(player, selectedRank); + GuildRankMenuHandler.populateInventory(event.getInventory(), player); + return; + } + + if (GuildRank.getMaxGuildRank(player) < selectedRank) { + selectPrestigeUnlock(player); + GuildRankMenuHandler.populateInventory(event.getInventory(), player); + return; + } + + } + + @EventHandler + public void onInventoryClose(InventoryCloseEvent event) { + if (!inventories.contains(event.getInventory())) return; + inventories.remove(event.getInventory()); + } + + private enum guildRankStatus { + UNLOCKED, + SELECTED, + NEXT_UNLOCK, + LOCKED, + PRESTIGE_LOCKED, + PRESTIGE_NEXT_UNLOCK, + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/adventurersguild/WorldSwitchBehavior.java b/src/main/java/com/magmaguy/elitemobs/adventurersguild/WorldSwitchBehavior.java new file mode 100644 index 000000000..142b98a5e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/adventurersguild/WorldSwitchBehavior.java @@ -0,0 +1,22 @@ +package com.magmaguy.elitemobs.adventurersguild; + +import com.magmaguy.elitemobs.config.AdventurersGuildConfig; +import org.bukkit.attribute.Attribute; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerChangedWorldEvent; + +public class WorldSwitchBehavior implements Listener { + @EventHandler(ignoreCancelled = true) + public void onPlayerTeleport(PlayerChangedWorldEvent event) { + if (AdventurersGuildConfig.getWorldsWithoutAGBonuses().isEmpty()) return; + //to a world without bonuses + if (AdventurersGuildConfig.getWorldsWithoutAGBonuses().contains(event.getPlayer().getWorld().getName()) && + !AdventurersGuildConfig.getWorldsWithoutAGBonuses().contains(event.getFrom().getName())) + event.getPlayer().getAttribute(Attribute.GENERIC_MAX_HEALTH).setBaseValue(event.getPlayer().getAttribute(Attribute.GENERIC_MAX_HEALTH).getDefaultValue()); + //to a world with bonuses + else if (!AdventurersGuildConfig.getWorldsWithoutAGBonuses().contains(event.getPlayer().getWorld().getName()) && + AdventurersGuildConfig.getWorldsWithoutAGBonuses().contains(event.getFrom().getName())) + GuildRank.setMaxHealth(event.getPlayer()); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/announcements/AnnouncementPriority.java b/src/main/java/com/magmaguy/elitemobs/announcements/AnnouncementPriority.java new file mode 100644 index 000000000..f998b6b59 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/announcements/AnnouncementPriority.java @@ -0,0 +1,23 @@ +package com.magmaguy.elitemobs.announcements; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.config.EventsConfig; +import com.magmaguy.elitemobs.thirdparty.discordsrv.DiscordSRVAnnouncement; +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.entity.Player; + +public class AnnouncementPriority { + private AnnouncementPriority() { + } + + public static void announce(String message, World world, int announcementPriority) { + if (announcementPriority == 1 && !EventsConfig.isAnnouncementBroadcastWorldOnly()) + Bukkit.broadcastMessage(ChatColorConverter.convert(message)); + else + for (Player player : world.getPlayers()) + player.sendMessage(ChatColorConverter.convert(message)); + if (announcementPriority < 3) return; + new DiscordSRVAnnouncement(ChatColorConverter.convert(message)); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/api/CustomEventStartEvent.java b/src/main/java/com/magmaguy/elitemobs/api/CustomEventStartEvent.java new file mode 100644 index 000000000..43b1bfb30 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/api/CustomEventStartEvent.java @@ -0,0 +1,49 @@ +package com.magmaguy.elitemobs.api; + +import com.magmaguy.elitemobs.events.CustomEvent; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +/** + * To clear up the weird naming system here, this event is called when custom event (the type created by users for the + * customizable in-game event system) is called, i.e. for treasure goblins, meteors and the dead moon event. + */ +public class CustomEventStartEvent extends Event implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + private CustomEvent customEvent; + private boolean cancelled = false; + + public CustomEventStartEvent(CustomEvent customEvent) { + this.customEvent = customEvent; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public CustomEvent getCustomEvent() { + return customEvent; + } + + public void setCustomEvent(CustomEvent customEvent) { + this.customEvent = customEvent; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean cancelled) { + this.cancelled = cancelled; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/api/DamageEliteMob.java b/src/main/java/com/magmaguy/elitemobs/api/DamageEliteMob.java new file mode 100644 index 000000000..e3542dd52 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/api/DamageEliteMob.java @@ -0,0 +1,63 @@ +package com.magmaguy.elitemobs.api; + +import com.magmaguy.elitemobs.events.BossCustomAttackDamage; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import org.bukkit.entity.Player; + +public class DamageEliteMob { + + public static double lowDamage(EliteEntity eliteEntity) { + return damageFormula(eliteEntity, DamageAmount.LOW); + } + + public static double mediumDamage(EliteEntity eliteEntity) { + return damageFormula(eliteEntity, DamageAmount.MEDIUM); + } + + public static double highDamage(EliteEntity eliteEntity) { + return damageFormula(eliteEntity, DamageAmount.HIGH); + } + + public static double lowDamage(Player player, EliteEntity eliteEntity) { + return damageFormula(player, eliteEntity, DamageAmount.LOW); + } + + public static double mediumDamage(Player player, EliteEntity eliteEntity) { + return damageFormula(player, eliteEntity, DamageAmount.MEDIUM); + } + + public static double highDamage(Player player, EliteEntity eliteEntity) { + return damageFormula(player, eliteEntity, DamageAmount.HIGH); + } + + private static double damageFormula(EliteEntity eliteEntity, DamageAmount damageAmount) { + return eliteEntity.damage(tierCalc(eliteEntity, damageAmount)); + } + + private static double damageFormula(Player player, EliteEntity eliteEntity, DamageAmount damageAmount) { + return BossCustomAttackDamage.dealCustomDamage(player, eliteEntity.getLivingEntity(), tierCalc(eliteEntity, damageAmount)); + } + + public static double getDamageValue(EliteEntity eliteEntity, DamageAmount damageAmount) { + return tierCalc(eliteEntity, damageAmount); + } + + private static double tierCalc(EliteEntity eliteEntity, DamageAmount damageAmount) { + switch (damageAmount) { + case LOW: + return Math.max(eliteEntity.getLevel() - 3, 0); + case MEDIUM: + default: + return eliteEntity.getLevel(); + case HIGH: + return eliteEntity.getLevel() + 3; + } + } + + public enum DamageAmount { + LOW, + MEDIUM, + HIGH + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/api/EliteExplosionEvent.java b/src/main/java/com/magmaguy/elitemobs/api/EliteExplosionEvent.java new file mode 100644 index 000000000..bdac1756b --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/api/EliteExplosionEvent.java @@ -0,0 +1,153 @@ +package com.magmaguy.elitemobs.api; + +import com.magmaguy.elitemobs.CrashFix; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.majorpowers.enderdragon.EnderDragonEmpoweredLightning; +import com.magmaguy.elitemobs.powers.majorpowers.enderdragon.EnderDragonTornado; +import com.magmaguy.elitemobs.powers.meta.ElitePower; +import org.bukkit.Location; +import org.bukkit.block.BlockState; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.FallingBlock; +import org.bukkit.event.*; +import org.bukkit.event.entity.EntityChangeBlockEvent; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +public class EliteExplosionEvent extends Event implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + public static List fallingBlocks = new ArrayList<>(); + private final EliteEntity eliteEntity; + private final List blockStates; + private final ElitePower elitePower; + private Location explosionSourceLocation; + private boolean isCancelled = false; + + public EliteExplosionEvent(EliteEntity eliteEntity, + ElitePower elitePower, + Location explosionSourceLocation, + List blockStates) { + this.eliteEntity = eliteEntity; + this.explosionSourceLocation = explosionSourceLocation; + this.elitePower = elitePower; + this.blockStates = blockStates; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public EliteEntity getEliteMobEntity() { + return eliteEntity; + } + + public Location getExplosionSourceLocation() { + return explosionSourceLocation; + } + + public void setExplosionSourceLocation(Location explosionSourceLocation) { + this.explosionSourceLocation = explosionSourceLocation; + } + + public ElitePower getElitePower() { + return elitePower; + } + + public List getBlockStates() { + return blockStates; + } + + @Override + public boolean isCancelled() { + return this.isCancelled; + } + + @Override + public void setCancelled(boolean b) { + this.isCancelled = b; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public void visualExplosionEffect(ElitePower elitePower) { + VisualExplosionEffectType visualExplosionEffectType; + + if (elitePower == null) + visualExplosionEffectType = VisualExplosionEffectType.NORMAL; + else if (elitePower.getFileName().equals(new EnderDragonEmpoweredLightning().getFileName())) + visualExplosionEffectType = VisualExplosionEffectType.ASCEND; + else if (elitePower instanceof EnderDragonTornado) { + visualExplosionEffectType = VisualExplosionEffectType.HIGH_POWER; + } else + visualExplosionEffectType = VisualExplosionEffectType.NORMAL; + + for (BlockState blockState : blockStates) { + FallingBlock fallingBlock = blockState.getBlock().getWorld().spawnFallingBlock(blockState.getLocation().add(new Vector(0, 0.2, 0)), blockState.getBlockData()); + fallingBlock.setDropItem(false); + fallingBlock.setHurtEntities(true); + + switch (visualExplosionEffectType) { + case ASCEND: + fallingBlock.setVelocity(fallingBlock.getLocation().clone().subtract(explosionSourceLocation) + .toVector().normalize().setY(1).normalize().multiply(ThreadLocalRandom.current().nextDouble())); + fallingBlock.setGravity(false); + fallingBlock.setGlowing(true); + break; + case HIGH_POWER: + fallingBlock.setVelocity(fallingBlock.getLocation().clone().subtract(explosionSourceLocation).toVector().normalize().setY(2).multiply(0.9)); + break; + case NORMAL: + default: + fallingBlock.setVelocity(fallingBlock.getLocation().clone().subtract(explosionSourceLocation).toVector().normalize().setY(1).multiply(0.5)); + } + + new BukkitRunnable() { + @Override + public void run() { + if (fallingBlock.isValid()) + fallingBlock.remove(); + } + }.runTaskLater(MetadataHandler.PLUGIN, 20 * 4); + + CrashFix.persistentTracker(fallingBlock); + fallingBlocks.add(fallingBlock); + } + } + + public enum VisualExplosionEffectType { + NORMAL, + HIGH_POWER, + ASCEND + } + + public static class EliteExplosionEvents implements Listener { + @EventHandler(ignoreCancelled = true) + public void onBlockDrop(EntityChangeBlockEvent event) { + + if (fallingBlocks.isEmpty()) return; + if (!event.getEntity().getType().equals(EntityType.FALLING_BLOCK)) return; + + boolean wasFallingBlock = false; + for (FallingBlock fallingBlock : fallingBlocks) + if (fallingBlock.equals(event.getEntity())) { + event.setCancelled(true); + wasFallingBlock = true; + break; + } + + if (!wasFallingBlock) return; + event.getEntity().remove(); + fallingBlocks.remove((FallingBlock) event.getEntity()); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/api/EliteMobDamagedByEliteMobEvent.java b/src/main/java/com/magmaguy/elitemobs/api/EliteMobDamagedByEliteMobEvent.java new file mode 100644 index 000000000..1ecf73a98 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/api/EliteMobDamagedByEliteMobEvent.java @@ -0,0 +1,84 @@ +package com.magmaguy.elitemobs.api; + +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs.EliteMobProperties; +import com.magmaguy.elitemobs.utils.EntityFinder; +import com.magmaguy.elitemobs.utils.EventCaller; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.*; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class EliteMobDamagedByEliteMobEvent extends Event implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + private final EliteEntity damager; + private final EliteEntity damagee; + private final EntityDamageByEntityEvent entityDamageByEntityEvent; + private final double damage; + private boolean isCancelled = false; + + public EliteMobDamagedByEliteMobEvent(EliteEntity damager, EliteEntity damagee, EntityDamageByEntityEvent event, double damage) { + this.damager = damager; + this.damagee = damagee; + this.entityDamageByEntityEvent = event; + this.damage = damage; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public EliteEntity getDamager() { + return damager; + } + + public EliteEntity getDamagee() { + return damagee; + } + + public EntityDamageByEntityEvent getEntityDamageByEntityEvent() { + return entityDamageByEntityEvent; + } + + public double getDamage() { + return damage; + } + + @Override + public boolean isCancelled() { + return this.isCancelled; + } + + @Override + public void setCancelled(boolean b) { + this.isCancelled = b; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static class EliteMobDamagedByEliteMobFilter implements Listener { + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void onEntityDamageByEntityEvent(EntityDamageByEntityEvent event) { + EliteEntity damagee = EntityTracker.getEliteMobEntity(event.getEntity()); + if (damagee == null) return; + LivingEntity livingEntity = EntityFinder.filterRangedDamagers(event.getDamager()); + EliteEntity damager = EntityTracker.getEliteMobEntity(livingEntity); + if (damager == null) return; + if (damager.getLivingEntity() == null) return; + if (EliteMobProperties.getPluginData(damager.getLivingEntity().getType()) == null) return; + double damage = EliteMobProperties.getBaselineDamage(damager.getLivingEntity().getType(), damager) + damager.getLevel(); + EliteMobDamagedByEliteMobEvent eliteMobDamagedByEliteMobEvent = new EliteMobDamagedByEliteMobEvent(damager, damagee, event, damage); + new EventCaller(eliteMobDamagedByEliteMobEvent); + if (eliteMobDamagedByEliteMobEvent.isCancelled) return; + event.setDamage(damage); + } + + } + + +} diff --git a/src/main/java/com/magmaguy/elitemobs/api/EliteMobDamagedByPlayerAntiExploitEvent.java b/src/main/java/com/magmaguy/elitemobs/api/EliteMobDamagedByPlayerAntiExploitEvent.java new file mode 100644 index 000000000..eb013d635 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/api/EliteMobDamagedByPlayerAntiExploitEvent.java @@ -0,0 +1,64 @@ +package com.magmaguy.elitemobs.api; + +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import org.bukkit.entity.Entity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +public class EliteMobDamagedByPlayerAntiExploitEvent extends Event implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + private final Entity entity; + private final EliteEntity eliteEntity; + private final EliteMobDamagedByPlayerEvent eliteMobDamagedByPlayerEvent; + private boolean isCancelled = false; + private boolean isTriggered = false; + + public EliteMobDamagedByPlayerAntiExploitEvent(EliteEntity eliteEntity, EliteMobDamagedByPlayerEvent event) { + this.entity = eliteEntity.getLivingEntity(); + this.eliteEntity = eliteEntity; + this.eliteMobDamagedByPlayerEvent = event; + if (!eliteEntity.getLivingEntity().hasAI()) + setCancelled(true); + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public Entity getEntity() { + return entity; + } + + public EliteEntity getEliteMobEntity() { + return eliteEntity; + } + + public EliteMobDamagedByPlayerEvent getEliteMobDamagedByPlayerEvent() { + return eliteMobDamagedByPlayerEvent; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + @Override + public boolean isCancelled() { + return this.isCancelled; + } + + @Override + public void setCancelled(boolean b) { + this.isCancelled = b; + } + + public boolean isTriggered() { + return isTriggered; + } + + public void setTriggered(boolean triggered) { + isTriggered = triggered; + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/api/EliteMobDamagedByPlayerEvent.java b/src/main/java/com/magmaguy/elitemobs/api/EliteMobDamagedByPlayerEvent.java new file mode 100644 index 000000000..4d473e9a2 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/api/EliteMobDamagedByPlayerEvent.java @@ -0,0 +1,341 @@ +package com.magmaguy.elitemobs.api; + +import com.magmaguy.elitemobs.EliteMobs; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.adventurersguild.GuildRank; +import com.magmaguy.elitemobs.combatsystem.CombatSystem; +import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import com.magmaguy.elitemobs.playerdata.ElitePlayerInventory; +import com.magmaguy.elitemobs.thirdparty.worldguard.WorldGuardCompatibility; +import com.magmaguy.elitemobs.thirdparty.worldguard.WorldGuardFlagChecker; +import com.magmaguy.elitemobs.utils.EntityFinder; +import com.magmaguy.elitemobs.utils.EventCaller; +import com.magmaguy.elitemobs.utils.Round; +import lombok.Getter; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.attribute.Attribute; +import org.bukkit.entity.*; +import org.bukkit.event.*; +import org.bukkit.event.block.Action; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.HashMap; +import java.util.concurrent.ThreadLocalRandom; + +public class EliteMobDamagedByPlayerEvent extends Event implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + @Getter + private final Entity entity; + @Getter + private final EliteEntity eliteMobEntity; + @Getter + private final Player player; + @Getter + private final EntityDamageByEntityEvent entityDamageByEntityEvent; + @Getter + private final double damage; + @Getter + private final boolean criticalStrike; + @Getter + private final boolean isCustomDamage; + @Getter + private final double damageModifier; + @Getter + public boolean rangedAttack; + @Getter + private boolean isCancelled = false; + + public EliteMobDamagedByPlayerEvent(EliteEntity eliteEntity, + Player player, + EntityDamageByEntityEvent event, + double damage, + boolean criticalStrike, + boolean isCustomDamage, + double damageModifier) { + this.damage = damage; + this.entity = eliteEntity.getLivingEntity(); + this.eliteMobEntity = eliteEntity; + this.player = player; + this.entityDamageByEntityEvent = event; + this.rangedAttack = event.getDamager() instanceof Projectile; + this.criticalStrike = criticalStrike; + this.isCustomDamage = isCustomDamage; + this.damageModifier = damageModifier; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + @Override + public void setCancelled(boolean b) { + this.isCancelled = b; + entityDamageByEntityEvent.setCancelled(b); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static class EliteMobDamagedByPlayerEventFilter implements Listener { + private static final HashMap playerHitCooldownHashMap = new HashMap<>(); + private static int clock = 0; + + public static void execute(EliteMobDamagedByPlayerEvent event) { + event.getEliteMobEntity().addDamager(event.getPlayer(), event.getDamage()); + } + + /** + * Calculates Player -> EliteMobs damage. + * + * @param player Player object + * @return + */ + private static double finalDamageCalculator(double playerWeaponTier, Player player, EliteEntity eliteEntity, boolean ranged, double damageModifier) { + double finalDamage; + if (!ranged) + finalDamage = getCooledAttackStrength(player) * + (playerWeaponTier + secondaryEnchantmentDamageIncrease(player, eliteEntity.getLivingEntity())) * + MobCombatSettingsConfig.getDamageToEliteMultiplier(); + else + finalDamage = (playerWeaponTier + secondaryEnchantmentDamageIncrease(player, eliteEntity.getLivingEntity())) * + MobCombatSettingsConfig.getDamageToEliteMultiplier(); + + finalDamage *= damageModifier; + + return Math.max(finalDamage, 1D); + } + + /** + * Calculates the cooldown debuff following vanilla Minecraft rules and then linearly applies a debuff to attacks + * + * @param player Player in cooldown + * @return Debuff multiplier + */ + private static float getCooledAttackStrength(Player player) { + if (!playerHitCooldownHashMap.containsKey(player)) { + playerHitCooldownHashMap.put(player, clock); + return 1; + } + float swingDelay = clock - playerHitCooldownHashMap.get(player); + float cooldownPeriod = getCooldownPeriod(player); + if (swingDelay > cooldownPeriod) return 1; + return swingDelay / cooldownPeriod; + } + + /** + * Calculates the cooldown following vanilla rules + * + * @param player + * @return + */ + private static float getCooldownPeriod(Player player) { + return (float) (1.0D / player.getAttribute(Attribute.GENERIC_ATTACK_SPEED).getValue() * 20.0D); + } + + public static void launchInternalClock() { + new BukkitRunnable() { + + @Override + public void run() { + if (clock == Integer.MAX_VALUE) clock = 0; + clock++; + } + + }.runTaskTimer(MetadataHandler.PLUGIN, 1, 1); + } + + private static double secondaryEnchantmentDamageIncrease(Player player, LivingEntity eliteMob) { + + if (eliteMob instanceof Spider || eliteMob instanceof Silverfish) + return ElitePlayerInventory.playerInventories.get(player.getUniqueId()).mainhand.getDamageArthropodsLevel(player.getInventory().getItemInMainHand(), false); + if (eliteMob instanceof Zombie || eliteMob instanceof Skeleton) + return ElitePlayerInventory.playerInventories.get(player.getUniqueId()).mainhand.getDamageUndeadLevel(player.getInventory().getItemInMainHand(), false); + + return 0; + + } + + private static boolean isCriticalHit(Player player) { + double criticalStrike = ElitePlayerInventory.playerInventories.get(player.getUniqueId()).getCritChance(false); + criticalStrike += (GuildRank.critBonusValue(GuildRank.getGuildPrestigeRank(player), GuildRank.getActiveGuildRank(player)) / 100); + return ThreadLocalRandom.current().nextDouble() < criticalStrike; + } + + @EventHandler(ignoreCancelled = true) + public void onEliteMobAttack(EntityDamageByEntityEvent event) { + if (event.getEntity().getType().equals(EntityType.ENDER_DRAGON) && + ((EnderDragon) event.getEntity()).getPhase().equals(EnderDragon.Phase.DYING)) + return; + LivingEntity livingEntity = EntityFinder.filterRangedDamagers(event.getDamager()); + if (livingEntity == null) return; + if (!livingEntity.getType().equals(EntityType.PLAYER)) return; + Player player = (Player) livingEntity; + EliteEntity eliteEntity = EntityTracker.getEliteMobEntity(event.getEntity()); + //Living entity is sometimes null when the damage is dealt to an already dead entity - might happen with mcmmo due to DOTs and stuff + if (eliteEntity == null || !eliteEntity.isValid()) return; + //If the damage wasn't caused by an elite item, just allow the event to go as raw + EliteMobDamagedByPlayerEvent eliteMobDamagedByPlayerEvent; + double damage; + //Thorns overrides all other possible damage + if (event.getCause().equals(EntityDamageEvent.DamageCause.THORNS)) { + int thornsLevel = ElitePlayerInventory.playerInventories.get(player.getUniqueId()).getThornsLevel(); + Strike strike = new Strike(thornsLevel, false, true, 1); + eliteMobDamagedByPlayerEvent = new EliteMobDamagedByPlayerEvent(eliteEntity, + player, + event, + strike.damage, + strike.criticalStrike, + strike.customDamage, + strike.damageModifier); + damage = strike.damage; + } else if ((event.getCause().equals(EntityDamageEvent.DamageCause.ENTITY_ATTACK) || + event.getCause().equals(EntityDamageEvent.DamageCause.ENTITY_SWEEP_ATTACK) || + event.getCause().equals(EntityDamageEvent.DamageCause.PROJECTILE)) && + EliteMobsItemDetector.isEliteMobsItem(player.getInventory().getItemInMainHand())) { + Strike strike = getDamage(player, eliteEntity, event); + eliteMobDamagedByPlayerEvent = new EliteMobDamagedByPlayerEvent(eliteEntity, + player, + event, + strike.damage, + strike.criticalStrike, + strike.customDamage, + strike.damageModifier); + damage = strike.damage; + } else { + //Runs if the damage was not dealt by an elite item, important for other plugins + eliteMobDamagedByPlayerEvent = new EliteMobDamagedByPlayerEvent(eliteEntity, + player, + event, + event.getFinalDamage(), + false, + false, + 1); + damage = event.getDamage(); + } + + damage = Round.twoDecimalPlaces(damage); + + new EventCaller(eliteMobDamagedByPlayerEvent); + if (eliteMobDamagedByPlayerEvent.isCancelled) { + event.setCancelled(true); + return; + } + execute(eliteMobDamagedByPlayerEvent); + + //nullify vanilla reductions + for (EntityDamageEvent.DamageModifier modifier : EntityDamageByEntityEvent.DamageModifier.values()) + if (event.isApplicable(modifier)) + event.setDamage(modifier, 0); + + if (eliteEntity.getLivingEntity() != null) + if (eliteEntity.getLivingEntity().getType().equals(EntityType.ENDER_DRAGON)) { + if (eliteEntity.getLivingEntity().getHealth() - damage < 1) { + if (eliteEntity.isDying()) + return; + damage = 0; + event.setCancelled(true); + ((EnderDragon) eliteEntity.getLivingEntity()).setPhase(EnderDragon.Phase.DYING); + eliteEntity.setDying(true); + //remove the dragon after it is done with the light show, this death doesn't show up on events + Bukkit.getScheduler().runTaskLater(MetadataHandler.PLUGIN, () -> new EventCaller(new EliteMobDeathEvent(eliteEntity)), 200); + } + } + + event.setDamage(EntityDamageEvent.DamageModifier.BASE, damage); + eliteEntity.syncPluginHealth(((LivingEntity) event.getEntity()).getHealth()); + + //No antiexploit checks for dungeons + if (!(EliteMobs.worldGuardIsEnabled && + !WorldGuardFlagChecker.checkFlag( + eliteEntity.getLivingEntity().getLocation(), + WorldGuardCompatibility.getEliteMobsAntiExploitFlag()))) + if (event.getCause().equals(EntityDamageEvent.DamageCause.ENTITY_ATTACK)) + if (!eliteEntity.isInAntiExploitCooldown()) + Bukkit.getServer().getPluginManager().callEvent( + new EliteMobDamagedByPlayerAntiExploitEvent(eliteEntity, eliteMobDamagedByPlayerEvent)); + } + + public Strike getDamage(Player player, EliteEntity eliteEntity, EntityDamageByEntityEvent event) { + //citizens + if (player.hasMetadata("NPC")) { + return new Strike(DamageEliteMob.getDamageValue(eliteEntity, DamageEliteMob.DamageAmount.LOW), false, true, 1); + } + + //if the damage source is custom , the damage is final + if (CombatSystem.bypass) { + double rawDamage = event.getDamage(); + CombatSystem.bypass = false; + return new Strike(rawDamage, false, true, 1); + } + + double playerWeaponTier; + //Melee attacks dealt with ranged weapons should have a tier of 0 + if (!(event.getDamager() instanceof Arrow) && + (player.getInventory().getItemInMainHand().getType().equals(Material.BOW) || + player.getInventory().getItemInMainHand().getType().equals(Material.CROSSBOW))) + playerWeaponTier = 0; + else + playerWeaponTier = ElitePlayerInventory.playerInventories.get(player.getUniqueId()).getWeaponTier(true); + + double damageModifier = 1; + if (eliteEntity instanceof CustomBossEntity) + damageModifier = ((CustomBossEntity) eliteEntity).getDamageModifier(player.getInventory().getItemInMainHand().getType()); + + double newDamage = finalDamageCalculator(playerWeaponTier, player, eliteEntity, event.getDamager() instanceof Arrow, damageModifier); + + if (event.getDamager() instanceof Arrow) { + //note: the arrow velocity amplitude at full load is about 2.8 + double arrowSpeedMultiplier = Math.sqrt(Math.pow(event.getDamager().getVelocity().getX(), 2D) + + Math.pow(event.getDamager().getVelocity().getY(), 2D) + + Math.pow(event.getDamager().getVelocity().getZ(), 2D)); + arrowSpeedMultiplier = Math.min(arrowSpeedMultiplier, 2.8D); + arrowSpeedMultiplier = arrowSpeedMultiplier / 2.8D; + newDamage *= arrowSpeedMultiplier; + } + + boolean criticalHit = isCriticalHit(player); + + if (criticalHit) newDamage += newDamage * 0.5; + + return new Strike(newDamage, criticalHit, false, damageModifier); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onPlayerInteract(PlayerInteractEvent event) { + if (!(event.getAction().equals(Action.LEFT_CLICK_AIR) || event.getAction().equals(Action.LEFT_CLICK_BLOCK) || + event.getAction().equals(Action.PHYSICAL))) return; + playerHitCooldownHashMap.put(event.getPlayer(), clock); + + } + + private static class Strike { + @Getter + private final double damage; + @Getter + private final boolean criticalStrike; + @Getter + private final boolean customDamage; + @Getter + private final double damageModifier; + + public Strike(double damage, boolean criticalStrike, boolean customDamage, double damageModifier) { + this.damage = damage; + this.criticalStrike = criticalStrike; + this.customDamage = customDamage; + this.damageModifier = damageModifier; + } + } + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/api/EliteMobDamagedEvent.java b/src/main/java/com/magmaguy/elitemobs/api/EliteMobDamagedEvent.java new file mode 100644 index 000000000..bd4a4f8a2 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/api/EliteMobDamagedEvent.java @@ -0,0 +1,89 @@ +package com.magmaguy.elitemobs.api; + +import com.magmaguy.elitemobs.EliteMobs; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.thirdparty.worldguard.WorldGuardCompatibility; +import com.magmaguy.elitemobs.thirdparty.worldguard.WorldGuardFlagChecker; +import com.magmaguy.elitemobs.utils.EventCaller; +import org.bukkit.Bukkit; +import org.bukkit.entity.Entity; +import org.bukkit.event.*; +import org.bukkit.event.entity.EntityDamageEvent; + +public class EliteMobDamagedEvent extends Event implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + private final Entity entity; + private final EliteEntity eliteEntity; + private final EntityDamageEvent entityDamageEvent; + private boolean isCancelled = false; + + public EliteMobDamagedEvent(EliteEntity eliteEntity, EntityDamageEvent event) { + this.entity = eliteEntity.getLivingEntity(); + this.eliteEntity = eliteEntity; + this.entityDamageEvent = event; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public Entity getEntity() { + return entity; + } + + public EliteEntity getEliteMobEntity() { + return eliteEntity; + } + + public EntityDamageEvent getEntityDamageEvent() { + return entityDamageEvent; + } + + @Override + public boolean isCancelled() { + return this.isCancelled; + } + + @Override + public void setCancelled(boolean b) { + this.isCancelled = b; + entityDamageEvent.setCancelled(b); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static class EliteMobDamageEventFilter implements Listener { + + @EventHandler(priority = EventPriority.HIGH) + public void onEntityDamageByEntityEvent(EntityDamageEvent event) { + + if (event.isCancelled()) return; + EliteEntity eliteEntity = EntityTracker.getEliteMobEntity(event.getEntity()); + if (eliteEntity == null) return; + + EliteMobDamagedEvent eliteMobDamagedEvent = new EliteMobDamagedEvent(eliteEntity, event); + new EventCaller(eliteMobDamagedEvent); + if (eliteMobDamagedEvent.isCancelled) { + eliteMobDamagedEvent.setCancelled(true); + return; + } + + //happens if it dies + if (!eliteEntity.isValid()) return; + + if (EliteMobs.worldGuardIsEnabled && !WorldGuardFlagChecker.checkFlag(eliteEntity.getLivingEntity().getLocation(), + WorldGuardCompatibility.getEliteMobsAntiExploitFlag())) + return; + + Bukkit.getServer().getPluginManager().callEvent(new GenericAntiExploitEvent(eliteEntity, event)); + + } + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/api/EliteMobDeathEvent.java b/src/main/java/com/magmaguy/elitemobs/api/EliteMobDeathEvent.java new file mode 100644 index 000000000..7ed9ca552 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/api/EliteMobDeathEvent.java @@ -0,0 +1,70 @@ +package com.magmaguy.elitemobs.api; + +import com.magmaguy.elitemobs.api.internal.RemovalReason; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.utils.EventCaller; +import org.bukkit.entity.Entity; +import org.bukkit.event.Event; +import org.bukkit.event.EventHandler; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDeathEvent; + +public class EliteMobDeathEvent extends Event { + + private static final HandlerList handlers = new HandlerList(); + private final Entity entity; + private final EliteEntity eliteEntity; + private EntityDeathEvent entityDeathEvent = null; + + public EliteMobDeathEvent(EliteEntity eliteEntity, EntityDeathEvent entityDeathEvent) { + this.entity = eliteEntity.getUnsyncedLivingEntity(); + this.eliteEntity = eliteEntity; + this.entityDeathEvent = entityDeathEvent; + eliteEntity.remove(RemovalReason.DEATH); + } + + /** + * This is necessary for End Dragons + * + * @param eliteEntity + */ + public EliteMobDeathEvent(EliteEntity eliteEntity) { + this.entity = eliteEntity.getUnsyncedLivingEntity(); + this.eliteEntity = eliteEntity; + new EventCaller(new EliteMobRemoveEvent(eliteEntity, RemovalReason.DEATH)); + } + + + public static HandlerList getHandlerList() { + return handlers; + } + + public Entity getEntity() { + return this.entity; + } + + public EliteEntity getEliteEntity() { + return this.eliteEntity; + } + + public EntityDeathEvent getEntityDeathEvent() { + return this.entityDeathEvent; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static class EliteMobDeathEventFilter implements Listener { + @EventHandler + public void onMobDeath(EntityDeathEvent event) { + EliteEntity eliteEntity = EntityTracker.getEliteMobEntity(event.getEntity()); + if (eliteEntity == null) return; + new EventCaller(new EliteMobDeathEvent(eliteEntity, event)); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/api/EliteMobEnterCombatEvent.java b/src/main/java/com/magmaguy/elitemobs/api/EliteMobEnterCombatEvent.java new file mode 100644 index 000000000..1cb1eae8d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/api/EliteMobEnterCombatEvent.java @@ -0,0 +1,100 @@ +package com.magmaguy.elitemobs.api; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.config.DefaultConfig; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import com.magmaguy.elitemobs.utils.CommandRunner; +import com.magmaguy.elitemobs.utils.EventCaller; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.attribute.Attribute; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Mob; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.EventHandler; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; + +import java.util.ArrayList; + +public class EliteMobEnterCombatEvent extends Event { + + private static final HandlerList handlers = new HandlerList(); + private final Player targetEntity; + private final EliteEntity eliteEntity; + + public EliteMobEnterCombatEvent(EliteEntity eliteEntity, Player targetEntity) { + this.targetEntity = targetEntity; + this.eliteEntity = eliteEntity; + eliteEntity.setInCombat(true); + if (!DefaultConfig.isAlwaysShowNametags()) + eliteEntity.setNameVisible(true); + if (eliteEntity instanceof CustomBossEntity) + CommandRunner.runCommandFromList(((CustomBossEntity) eliteEntity).getCustomBossesConfigFields().getOnCombatEnterCommands(), new ArrayList<>()); + Bukkit.getScheduler().runTaskTimer(MetadataHandler.PLUGIN, (task) -> { + if (!eliteEntity.isValid()) { + task.cancel(); + new EventCaller(new EliteMobExitCombatEvent(eliteEntity, EliteMobExitCombatEvent.EliteMobExitCombatReason.ELITE_NOT_VALID)); + return; + } + if (!eliteEntity.isInCombatGracePeriod()) + if (((Mob) eliteEntity.getLivingEntity()).getTarget() == null) { + double followRange = eliteEntity.getLivingEntity().getAttribute(Attribute.GENERIC_FOLLOW_RANGE).getValue(); + if (eliteEntity.getLivingEntity().getType().equals(EntityType.ENDER_DRAGON)) + followRange = 200; + for (Entity entity : eliteEntity.getLivingEntity().getNearbyEntities(followRange,followRange,followRange)) { + if (entity instanceof Player) { + if (((Player) entity).getGameMode().equals(GameMode.SPECTATOR)) + continue; + return; + } + } + task.cancel(); + new EventCaller(new EliteMobExitCombatEvent(eliteEntity, EliteMobExitCombatEvent.EliteMobExitCombatReason.NO_NEARBY_PLAYERS)); + } + }, 20L, 20L); + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public Player getTargetEntity() { + return this.targetEntity; + } + + public EliteEntity getEliteMobEntity() { + return this.eliteEntity; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static class EliteMobEnterCombatEventFilter implements Listener { + @EventHandler(ignoreCancelled = true) + public void onEliteMobDamaged(EliteMobDamagedByPlayerEvent event) { + if (event.getEliteMobEntity().isInCombat()) return; + if (!(event.getEliteMobEntity().getLivingEntity() instanceof Mob)) return; + Bukkit.getServer().getPluginManager().callEvent(new EliteMobEnterCombatEvent(event.getEliteMobEntity(), event.getPlayer())); + } + + @EventHandler(ignoreCancelled = true) + public void onEliteMobDamage(PlayerDamagedByEliteMobEvent event) { + if (event.getEliteMobEntity().isInCombat()) return; + if (!(event.getEliteMobEntity().getLivingEntity() instanceof Mob)) return; + Bukkit.getServer().getPluginManager().callEvent(new EliteMobEnterCombatEvent(event.getEliteMobEntity(), event.getPlayer())); + } + + @EventHandler(ignoreCancelled = true) + public void onEliteMobTarget(EliteMobTargetPlayerEvent event) { + if (event.getEliteMobEntity().isInCombat()) return; + if (!(event.getEliteMobEntity().getLivingEntity() instanceof Mob)) return; + Bukkit.getServer().getPluginManager().callEvent(new EliteMobEnterCombatEvent(event.getEliteMobEntity(), event.getPlayer())); + } + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/api/EliteMobExitCombatEvent.java b/src/main/java/com/magmaguy/elitemobs/api/EliteMobExitCombatEvent.java new file mode 100644 index 000000000..70b4409d7 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/api/EliteMobExitCombatEvent.java @@ -0,0 +1,62 @@ +package com.magmaguy.elitemobs.api; + +import com.magmaguy.elitemobs.config.DefaultConfig; +import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import com.magmaguy.elitemobs.utils.CommandRunner; +import org.bukkit.entity.EntityType; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +import java.util.ArrayList; + +public class EliteMobExitCombatEvent extends Event { + + private static final HandlerList handlers = new HandlerList(); + private final EliteEntity eliteEntity; + private final EliteMobExitCombatReason eliteMobExitCombatReason; + + + public EliteMobExitCombatEvent(EliteEntity eliteEntity, EliteMobExitCombatReason reason) { + this.eliteEntity = eliteEntity; + this.eliteMobExitCombatReason = reason; + eliteEntity.setInCombat(false); + if (eliteEntity.getUnsyncedLivingEntity().isDead()) return; + //only run commands if the reason for leaving combat isn't death, onDeath commands exist for that case + if (eliteEntity instanceof CustomBossEntity) + CommandRunner.runCommandFromList(((CustomBossEntity) eliteEntity).getCustomBossesConfigFields().getOnCombatLeaveCommands(), new ArrayList<>()); + if (eliteEntity.isValid() && + MobCombatSettingsConfig.isRegenerateCustomBossHealthOnCombatEnd() && + !reason.equals(EliteMobExitCombatReason.PHASE_SWITCH) && + !eliteEntity.getUnsyncedLivingEntity().getType().equals(EntityType.PHANTOM)) + eliteEntity.fullHeal(); + if (!DefaultConfig.isAlwaysShowNametags()) + eliteEntity.setNameVisible(false); + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public EliteEntity getEliteMobEntity() { + return this.eliteEntity; + } + + public EliteMobExitCombatReason getEliteMobExitCombatReason() { + return eliteMobExitCombatReason; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public enum EliteMobExitCombatReason { + NO_NEARBY_PLAYERS, + SPIRIT_WALK, + ELITE_NOT_VALID, + PHASE_SWITCH + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/api/EliteMobHealEvent.java b/src/main/java/com/magmaguy/elitemobs/api/EliteMobHealEvent.java new file mode 100644 index 000000000..e80d6e71c --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/api/EliteMobHealEvent.java @@ -0,0 +1,49 @@ +package com.magmaguy.elitemobs.api; + +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import lombok.Getter; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +public class EliteMobHealEvent extends Event implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + @Getter + private final EliteEntity eliteEntity; + @Getter + private double healAmount = 0; + private boolean isCancelled = false; + @Getter + private boolean fullHeal = false; + + public EliteMobHealEvent(EliteEntity eliteEntity, double healAmount) { + this.eliteEntity = eliteEntity; + this.healAmount = healAmount; + } + + public EliteMobHealEvent(EliteEntity eliteEntity, boolean fullHeal) { + this.eliteEntity = eliteEntity; + this.fullHeal = fullHeal; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + @Override + public boolean isCancelled() { + return this.isCancelled; + } + + @Override + public void setCancelled(boolean b) { + this.isCancelled = b; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/api/EliteMobRemoveEvent.java b/src/main/java/com/magmaguy/elitemobs/api/EliteMobRemoveEvent.java new file mode 100644 index 000000000..452486484 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/api/EliteMobRemoveEvent.java @@ -0,0 +1,49 @@ +package com.magmaguy.elitemobs.api; + +import com.magmaguy.elitemobs.api.internal.RemovalReason; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import org.bukkit.entity.Entity; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +public class EliteMobRemoveEvent extends Event { + + private static final HandlerList handlers = new HandlerList(); + private final Entity entity; + private final EliteEntity eliteEntity; + private final RemovalReason removalReason; + + /** + * This is always the last event to be called when an Elite Mob dies, and is used to clean up references to it in memory. + * + * @param eliteEntity Elite Mob removed + * @param removalReason Reason for removal + */ + public EliteMobRemoveEvent(EliteEntity eliteEntity, RemovalReason removalReason) { + this.entity = eliteEntity.getUnsyncedLivingEntity(); + this.eliteEntity = eliteEntity; + this.removalReason = removalReason; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public Entity getEntity() { + return this.entity; + } + + public EliteEntity getEliteMobEntity() { + return this.eliteEntity; + } + + public RemovalReason getRemovalReason() { + return removalReason; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/api/EliteMobSpawnEvent.java b/src/main/java/com/magmaguy/elitemobs/api/EliteMobSpawnEvent.java new file mode 100644 index 000000000..3e95484b6 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/api/EliteMobSpawnEvent.java @@ -0,0 +1,90 @@ +package com.magmaguy.elitemobs.api; + +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.bukkit.event.entity.CreatureSpawnEvent; + +public class EliteMobSpawnEvent extends Event implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + private final LivingEntity livingEntity; + private final EliteEntity eliteEntity; + private final CreatureSpawnEvent.SpawnReason spawnReason; + private boolean isCancelled = false; + + /** + * Cancelling this event will prevent the Elite Mob from being constructed by removing it and the entity it would've converted + * + * @param eliteEntity EliteMobEntity being formed + */ + public EliteMobSpawnEvent(EliteEntity eliteEntity) { + this.livingEntity = eliteEntity.getLivingEntity(); + this.eliteEntity = eliteEntity; + this.spawnReason = eliteEntity.getSpawnReason(); + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * Returns the entity being converted to an EliteMobEntity + * + * @return Entity being converted into an Elite Mob + */ + public LivingEntity getEntity() { + return this.livingEntity; + } + + /** + * Returns the EliteMobEntity currently being formed + * + * @return EliteMobEntity currently being formed + */ + public EliteEntity getEliteMobEntity() { + return this.eliteEntity; + } + + /** + * Gets the reason for the Entity getting spawned + * + * @return Reason for the Entity getting spawned + */ + public CreatureSpawnEvent.SpawnReason getReason() { + return this.spawnReason; + } + + /** + * Returns if the event is cancelled + * + * @return If the event is cancelled + */ + @Override + public boolean isCancelled() { + return this.isCancelled; + } + + /** + * Cancels the event. This will cancel the formation of the Elite Mob and remove the living entity. Once cancelled it can't be uncancelled. + * + * @param cancel Cancels the event + */ + @Override + public void setCancelled(boolean cancel) { + this.isCancelled = cancel; + } + + /** + * Returns a list of handlers + * + * @return List of handlers + */ + @Override + public HandlerList getHandlers() { + return handlers; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/api/EliteMobTargetPlayerEvent.java b/src/main/java/com/magmaguy/elitemobs/api/EliteMobTargetPlayerEvent.java new file mode 100644 index 000000000..220fc5fa4 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/api/EliteMobTargetPlayerEvent.java @@ -0,0 +1,68 @@ +package com.magmaguy.elitemobs.api; + +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.EventHandler; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityTargetLivingEntityEvent; + +public class EliteMobTargetPlayerEvent extends Event { + + private static final HandlerList handlers = new HandlerList(); + private final Entity entity; + private final EliteEntity eliteEntity; + private final Player player; + private final EntityTargetLivingEntityEvent entityTargetLivingEntityEvent; + + public EliteMobTargetPlayerEvent(EliteEntity eliteEntity, Player player, EntityTargetLivingEntityEvent event) { + this.entity = event.getEntity(); + this.eliteEntity = eliteEntity; + this.player = player; + this.entityTargetLivingEntityEvent = event; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public Entity getEntity() { + return this.entity; + } + + public EliteEntity getEliteMobEntity() { + return this.eliteEntity; + } + + public Player getPlayer() { + return this.player; + } + + public EntityTargetLivingEntityEvent entityTargetLivingEntityEvent() { + return this.entityTargetLivingEntityEvent; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static class EliteMobTargetPlayerEventFilter implements Listener { + @EventHandler + public void onMobTarget(EntityTargetLivingEntityEvent event) { + if (!(event.getTarget() instanceof Player)) return; + Player player = (Player) event.getTarget(); + EliteEntity eliteEntity = EntityTracker.getEliteMobEntity(event.getEntity()); + if (eliteEntity == null) return; + + if (player.getGameMode().equals(GameMode.ADVENTURE) || player.getGameMode().equals(GameMode.SURVIVAL)) + Bukkit.getServer().getPluginManager().callEvent(new EliteMobTargetPlayerEvent(eliteEntity, player, event)); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/api/EliteMobsItemDetector.java b/src/main/java/com/magmaguy/elitemobs/api/EliteMobsItemDetector.java new file mode 100644 index 000000000..384cb6a41 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/api/EliteMobsItemDetector.java @@ -0,0 +1,40 @@ +package com.magmaguy.elitemobs.api; + +import com.magmaguy.elitemobs.items.ItemTagger; +import com.magmaguy.elitemobs.items.customenchantments.SoulbindEnchantment; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.jetbrains.annotations.NotNull; + +import javax.annotation.Nullable; + +public class EliteMobsItemDetector { + + public static boolean isEliteMobsItem(ItemStack itemStack) { + return ItemTagger.isEliteItem(itemStack); + } + + /** + * Returns whether an item meta has the soulbind enchantment + * + * @param itemMeta Item meta to be evaluated + * @return Whether the item has the soulbind meta + */ + @Nullable + public static boolean hasSoulbindEnchantment(@NotNull ItemMeta itemMeta) { + return SoulbindEnchantment.itemHasSoulbindEnchantment(itemMeta); + } + + /** + * Gets the {@link Player} to whom the item meta is linked. + * + * @param itemMeta Item meta to be evaluated. + * @return Player to whom the meta is linked. Returns null if no player is linked, or if the player linked is not online. + */ + @Nullable + public static Player getSoulboundPlayer(@NotNull ItemMeta itemMeta) { + return SoulbindEnchantment.getSoulboundPlayer(itemMeta); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/api/GenericAntiExploitEvent.java b/src/main/java/com/magmaguy/elitemobs/api/GenericAntiExploitEvent.java new file mode 100644 index 000000000..30723f7ad --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/api/GenericAntiExploitEvent.java @@ -0,0 +1,132 @@ +package com.magmaguy.elitemobs.api; + +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import org.bukkit.Location; +import org.bukkit.block.Block; +import org.bukkit.entity.Entity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.util.Vector; + +public class GenericAntiExploitEvent extends Event implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + private final Entity entity; + private final EliteEntity eliteEntity; + private final EntityDamageEvent entityDamageEvent; + public Block + block000, block001, block002, + block010, block011, block012, + block020, block021, block022, + block030, block031, block032, + block100, blockBelow, block102, + block110, ground, block112, + block120, headMaterial, block122, + block130, ceilingMaterial, block132, + block200, block201, block202, + block210, block211, block212, + block220, block221, block222, + block230, block231, block232; + private boolean isCancelled = false; + private boolean isTriggered = false; + + public GenericAntiExploitEvent(EliteEntity eliteEntity, EntityDamageEvent event) { + this.entity = eliteEntity.getLivingEntity(); + this.eliteEntity = eliteEntity; + this.entityDamageEvent = event; + this.isCancelled = event.isCancelled(); + if (event.isCancelled()) return; + if (!eliteEntity.getLivingEntity().hasAI()) + setCancelled(true); + block000 = defineMaterial(new Vector(-1, -1, -1)); + block001 = defineMaterial(new Vector(-1, -1, 0)); + block002 = defineMaterial(new Vector(-1, -1, 1)); + block010 = defineMaterial(new Vector(-1, 0, -1)); + block011 = defineMaterial(new Vector(-1, 0, 0)); + block012 = defineMaterial(new Vector(-1, 0, 1)); + block020 = defineMaterial(new Vector(-1, 1, -1)); + block021 = defineMaterial(new Vector(-1, 1, 0)); + block022 = defineMaterial(new Vector(-1, 1, 1)); + block030 = defineMaterial(new Vector(-1, 2, -1)); + block031 = defineMaterial(new Vector(-1, 2, 0)); + block032 = defineMaterial(new Vector(-1, 2, 1)); + block100 = defineMaterial(new Vector(0, -1, -1)); + //mob floor location + blockBelow = defineMaterial(new Vector(0, -1, 0)); + block102 = defineMaterial(new Vector(0, -1, 1)); + block110 = defineMaterial(new Vector(0, 0, -1)); + //mob ground location + ground = defineMaterial(new Vector(0, 0, 0)); + block112 = defineMaterial(new Vector(0, 0, 1)); + block120 = defineMaterial(new Vector(0, 1, -1)); + //mob head location + headMaterial = defineMaterial(new Vector(0, 1, 0)); + block122 = defineMaterial(new Vector(0, 1, 1)); + block130 = defineMaterial(new Vector(0, 2, -1)); + //ceiling block + ceilingMaterial = defineMaterial(new Vector(0, 2, 0)); + block132 = defineMaterial(new Vector(0, 2, 1)); + block200 = defineMaterial(new Vector(1, -1, -1)); + block201 = defineMaterial(new Vector(1, -1, 0)); + block202 = defineMaterial(new Vector(1, -1, 1)); + block210 = defineMaterial(new Vector(1, 0, -1)); + block211 = defineMaterial(new Vector(1, 0, 0)); + block212 = defineMaterial(new Vector(1, 0, 1)); + block220 = defineMaterial(new Vector(1, 1, -1)); + block221 = defineMaterial(new Vector(1, 1, 0)); + block222 = defineMaterial(new Vector(1, 1, 1)); + block230 = defineMaterial(new Vector(1, 2, -1)); + block231 = defineMaterial(new Vector(1, 2, 0)); + block232 = defineMaterial(new Vector(1, 2, 1)); + + } + + public static HandlerList getHandlerList() { + return handlers; + } + + private Block defineMaterial(Vector offset) { + Location clonedLocation = entity.getLocation().getBlock().getLocation().add(new Vector(0.5, 0.5, 0.5)).clone(); + //Location templocation = clonedLocation.clone().add(offset); + //new DebugBlockLocation(templocation); + return clonedLocation.add(offset).getBlock(); + } + + public Entity getEntity() { + return entity; + } + + public EliteEntity getEliteMobEntity() { + return eliteEntity; + } + + public EntityDamageEvent getEntityDamageEvent() { + return entityDamageEvent; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + @Override + public boolean isCancelled() { + return this.isCancelled; + } + + @Override + public void setCancelled(boolean b) { + this.isCancelled = b; + } + + public boolean isTriggered() { + return isTriggered; + } + + public void setTriggered(boolean triggered) { + isTriggered = triggered; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/api/NPCEntityRemoveEvent.java b/src/main/java/com/magmaguy/elitemobs/api/NPCEntityRemoveEvent.java new file mode 100644 index 000000000..2d8ed2b0b --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/api/NPCEntityRemoveEvent.java @@ -0,0 +1,4 @@ +package com.magmaguy.elitemobs.api; + +public class NPCEntityRemoveEvent { +} diff --git a/src/main/java/com/magmaguy/elitemobs/api/NPCEntitySpawnEvent.java b/src/main/java/com/magmaguy/elitemobs/api/NPCEntitySpawnEvent.java new file mode 100644 index 000000000..dd29d735f --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/api/NPCEntitySpawnEvent.java @@ -0,0 +1,77 @@ +package com.magmaguy.elitemobs.api; + +import com.magmaguy.elitemobs.npcs.NPCEntity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +public class NPCEntitySpawnEvent extends Event implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + private final LivingEntity livingEntity; + private final NPCEntity npcEntity; + private boolean isCancelled = false; + + /** + * Cancelling this event will prevent the NPC from being constructed by removing it and the entity it would've converted + */ + public NPCEntitySpawnEvent(LivingEntity livingEntity, NPCEntity npcEntity) { + this.livingEntity = livingEntity; + this.npcEntity = npcEntity; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * Returns the entity being converted to an EliteMobEntity + * + * @return Entity being converted into an Elite Mob + */ + public LivingEntity getLivingEntity() { + return this.livingEntity; + } + + /** + * Returns the EliteMobEntity currently being formed + * + * @return EliteMobEntity currently being formed + */ + public NPCEntity getNPCEntity() { + return this.npcEntity; + } + + + /** + * Returns if the event is cancelled + * + * @return If the event is cancelled + */ + @Override + public boolean isCancelled() { + return this.isCancelled; + } + + /** + * Cancels the event. This will cancel the formation of the Elite Mob and remove the living entity. Once cancelled it can't be uncancelled. + * + * @param cancel Cancels the event + */ + @Override + public void setCancelled(boolean cancel) { + this.isCancelled = cancel; + if (isCancelled) + livingEntity.remove(); + } + + /** + * Returns a list of handlers + * + * @return List of handlers + */ + @Override + public HandlerList getHandlers() { + return handlers; + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/api/PlayerDamagedByEliteMobEvent.java b/src/main/java/com/magmaguy/elitemobs/api/PlayerDamagedByEliteMobEvent.java new file mode 100644 index 000000000..c7048852c --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/api/PlayerDamagedByEliteMobEvent.java @@ -0,0 +1,114 @@ +package com.magmaguy.elitemobs.api; + +import com.magmaguy.elitemobs.adventurersguild.GuildRank; +import com.magmaguy.elitemobs.combatsystem.PlayerDamagedByEliteMobHandler; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.utils.EventCaller; +import org.bukkit.entity.*; +import org.bukkit.event.*; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.concurrent.ThreadLocalRandom; + +public class PlayerDamagedByEliteMobEvent extends Event implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + private final Entity entity; + private final EliteEntity eliteEntity; + private final Player player; + private final EntityDamageByEntityEvent entityDamageByEntityEvent; + private final Projectile projectile; + private boolean isCancelled = false; + + public PlayerDamagedByEliteMobEvent(EliteEntity eliteEntity, Player player, EntityDamageByEntityEvent event, Projectile projectile) { + this.entity = event.getEntity(); + this.eliteEntity = eliteEntity; + this.player = player; + this.entityDamageByEntityEvent = event; + this.projectile = projectile; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public Entity getEntity() { + return this.entity; + } + + public EliteEntity getEliteMobEntity() { + return this.eliteEntity; + } + + public Player getPlayer() { + return this.player; + } + + public Projectile getProjectile() { + return projectile; + } + + public EntityDamageByEntityEvent getEntityDamageByEntityEvent() { + return this.entityDamageByEntityEvent; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + @Override + public boolean isCancelled() { + return this.isCancelled; + } + + @Override + public void setCancelled(boolean b) { + this.isCancelled = b; + entityDamageByEntityEvent.setCancelled(b); + } + + public static class PlayerDamagedByEliteMobEventFilter implements Listener { + + @EventHandler + public void onEliteMobAttack2(EntityDamageByEntityEvent event) { + if (event.isCancelled()) { + PlayerDamagedByEliteMobHandler.bypass = false; + return; + } + if (!(event.getEntity() instanceof Player)) return; + Player player = (Player) event.getEntity(); + + //citizens + if (player.hasMetadata("NPC")) + return; + + Projectile projectile = null; + + EliteEntity eliteEntity = null; + if (event.getDamager() instanceof LivingEntity) + eliteEntity = EntityTracker.getEliteMobEntity(event.getDamager()); + else if (event.getDamager() instanceof Projectile && ((Projectile) event.getDamager()).getShooter() instanceof LivingEntity) { + eliteEntity = EntityTracker.getEliteMobEntity((LivingEntity) ((Projectile) event.getDamager()).getShooter()); + projectile = (Projectile) event.getDamager(); + } else if (event.getDamager().getType().equals(EntityType.EVOKER_FANGS)) + if (((EvokerFangs) event.getDamager()).getOwner() != null) + eliteEntity = EntityTracker.getEliteMobEntity(((EvokerFangs) event.getDamager()).getOwner()); + + if (eliteEntity == null) return; + + //dodge chance + if (ThreadLocalRandom.current().nextDouble() < GuildRank.dodgeBonusValue(GuildRank.getGuildPrestigeRank(player), GuildRank.getActiveGuildRank(player)) / 100) { + player.sendTitle(" ", "Dodged!"); + event.setCancelled(true); + return; + } + + PlayerDamagedByEliteMobEvent playerDamagedByEliteMobEvent = new PlayerDamagedByEliteMobEvent(eliteEntity, player, event, projectile); + if (!playerDamagedByEliteMobEvent.isCancelled) + new EventCaller(playerDamagedByEliteMobEvent); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/api/PlayerPreTeleportEvent.java b/src/main/java/com/magmaguy/elitemobs/api/PlayerPreTeleportEvent.java new file mode 100644 index 000000000..263546b6d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/api/PlayerPreTeleportEvent.java @@ -0,0 +1,121 @@ +package com.magmaguy.elitemobs.api; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.config.CombatTagConfig; +import com.magmaguy.elitemobs.config.TranslationConfig; +import com.magmaguy.elitemobs.utils.EventCaller; +import net.md_5.bungee.api.ChatMessageType; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.event.*; +import org.bukkit.scheduler.BukkitRunnable; + +public class PlayerPreTeleportEvent extends Event implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + private final Location destination; + private final Location originalLocation; + private final Player player; + private boolean isCancelled = false; + + /** + * Called when a player initiates a teleport to a location. The teleport will go through 3 seconds after the event is + * launched, assuming it isn't cancelled by the player or via code. + * + * @param player Player that will teleport + * @param destination Teleport destination + */ + public PlayerPreTeleportEvent(Player player, Location destination) { + this.player = player; + this.destination = destination.clone(); + this.originalLocation = player.getLocation().clone(); + } + + public static void teleportPlayer(Player player, Location destination) { + if (destination.getWorld() == null) return; + if (CombatTagConfig.isEnableTeleportTimer()) + new EventCaller(new PlayerPreTeleportEvent(player, destination)); + else + PlayerTeleportEvent.teleportPlayer(player, destination); + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public void startTeleport() { + new BukkitRunnable() { + int timerLeft = 3; + + @Override + public void run() { + if (!player.isValid()) { + cancel(); + return; + } + + if (player.getLocation().getX() != originalLocation.getX() || + player.getLocation().getY() != originalLocation.getY() || + player.getLocation().getZ() != originalLocation.getZ()) + isCancelled = true; + + if (isCancelled) { + player.spigot().sendMessage(ChatMessageType.ACTION_BAR, + TextComponent.fromLegacyText(ChatColorConverter.convert(TranslationConfig.getTeleportCancelled()))); + cancel(); + return; + } + + player.spigot().sendMessage(ChatMessageType.ACTION_BAR, + TextComponent.fromLegacyText(ChatColorConverter.convert(TranslationConfig.getTeleportTimeLeft()) + .replace("$time", timerLeft + ""))); + + + if (timerLeft == 0) { + PlayerTeleportEvent.teleportPlayer(player, destination); + cancel(); + return; + } + + timerLeft--; + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 20); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + @Override + public boolean isCancelled() { + return this.isCancelled; + } + + @Override + public void setCancelled(boolean b) { + this.isCancelled = b; + } + + public Player getPlayer() { + return player; + } + + public Location getDestination() { + return destination; + } + + public Location getOriginalLocation() { + return originalLocation; + } + + public static class PlayerPreTeleportEventEvents implements Listener { + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + public void onTeleportEvent(PlayerPreTeleportEvent event) { + event.startTeleport(); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/api/PlayerTeleportEvent.java b/src/main/java/com/magmaguy/elitemobs/api/PlayerTeleportEvent.java new file mode 100644 index 000000000..2625d05ee --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/api/PlayerTeleportEvent.java @@ -0,0 +1,92 @@ +package com.magmaguy.elitemobs.api; + +import com.magmaguy.elitemobs.config.AdventurersGuildConfig; +import com.magmaguy.elitemobs.config.dungeonpackager.DungeonPackagerConfigFields; +import com.magmaguy.elitemobs.dungeons.Minidungeon; +import com.magmaguy.elitemobs.playerdata.database.PlayerData; +import com.magmaguy.elitemobs.utils.EventCaller; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.event.*; + +import java.util.Objects; + +public class PlayerTeleportEvent extends Event implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + private final Location destination; + private final Location originalLocation; + private final Player player; + private boolean isCancelled = false; + + /** + * Event fired when players teleport due to EliteMobs. This is used for teleporting to the Adventurer's Guild and to + * Dungeons. + * + * @param player Player to be teleported + * @param destination Teleport destination + */ + public PlayerTeleportEvent(Player player, Location destination) { + this.player = player; + this.destination = destination; + this.originalLocation = player.getLocation().clone(); + } + + public static void teleportPlayer(Player player, Location destination) { + new EventCaller(new PlayerTeleportEvent(player, destination)); + } + + public static HandlerList getHandlerList() { + return handlers; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + @Override + public boolean isCancelled() { + return this.isCancelled; + } + + @Override + public void setCancelled(boolean b) { + this.isCancelled = b; + } + + public Player getPlayer() { + return player; + } + + public Location getDestination() { + return destination; + } + + public Location getOriginalLocation() { + return originalLocation; + } + + public void executeTeleport() { + player.teleport(destination); + for (Minidungeon minidungeon : Minidungeon.getMinidungeons().values()) + if (minidungeon.isInstalled() && + minidungeon.getDungeonPackagerConfigFields().getDungeonLocationType().equals(DungeonPackagerConfigFields.DungeonLocationType.WORLD) && + minidungeon.getWorld() != null && + minidungeon.getWorld().equals(originalLocation.getWorld())) + return; + + if (AdventurersGuildConfig.getGuildWorldLocation() != null && + Objects.equals(AdventurersGuildConfig.getGuildWorldLocation().getWorld(), originalLocation.getWorld())) + return; + PlayerData.setBackTeleportLocation(player, originalLocation); + } + + public static class PlayerTeleportEventExecutor implements Listener { + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onPlayerTeleport(PlayerTeleportEvent event) { + event.executeTeleport(); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/api/QuestAcceptEvent.java b/src/main/java/com/magmaguy/elitemobs/api/QuestAcceptEvent.java new file mode 100644 index 000000000..f866b7788 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/api/QuestAcceptEvent.java @@ -0,0 +1,77 @@ +package com.magmaguy.elitemobs.api; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.config.QuestsConfig; +import com.magmaguy.elitemobs.playerdata.database.PlayerData; +import com.magmaguy.elitemobs.quests.CustomQuest; +import com.magmaguy.elitemobs.quests.Quest; +import lombok.Getter; +import org.bukkit.entity.Player; +import org.bukkit.event.*; + +public class QuestAcceptEvent extends Event implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + @Getter + private final Player player; + @Getter + private final Quest quest; + private boolean isCancelled = false; + + public QuestAcceptEvent(Player player, Quest quest) { + this.player = player; + this.quest = quest; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + @Override + public boolean isCancelled() { + return isCancelled; + } + + @Override + public void setCancelled(boolean cancel) { + isCancelled = cancel; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static class QuestAcceptEventHandler implements Listener { + @EventHandler(ignoreCancelled = true, priority = EventPriority.LOWEST) + public void questAcceptLimiter(QuestAcceptEvent event) { + if (PlayerData.getQuests(event.getPlayer().getUniqueId()).size() < QuestsConfig.getMaximumActiveQuests()) + return; + event.setCancelled(true); + event.getPlayer().sendMessage(ChatColorConverter.convert(QuestsConfig.getQuestCapMessage())); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + public void onQuestAccept(QuestAcceptEvent event) { + event.getPlayer().sendMessage(QuestsConfig.getQuestJoinMessage().replace("$questName", ChatColorConverter.convert(event.getQuest().getQuestName()))); + event.getQuest().setAccepted(true); + if (QuestsConfig.isUseQuestAcceptTitles()) + event.getPlayer().sendTitle( + ChatColorConverter.convert(QuestsConfig.getQuestStartTitle().replace("$questName", event.getQuest().getQuestName())), + ChatColorConverter.convert(QuestsConfig.getQuestStartSubtitle().replace("$questName", event.getQuest().getQuestName())), + 20, 60, 20); + + if (event.getQuest() instanceof CustomQuest) { + CustomQuest customQuest = (CustomQuest) event.getQuest(); + + customQuest.applyTemporaryPermissions(event.getPlayer()); + + if (!customQuest.getCustomQuestsConfigFields().getQuestAcceptDialog().isEmpty()) + for (String dialog : customQuest.getCustomQuestsConfigFields().getQuestAcceptDialog()) + event.getPlayer().sendMessage(dialog); + } + event.getQuest().getQuestObjectives().displayTemporaryObjectivesScoreboard(event.getPlayer()); + PlayerData.addQuest(event.getPlayer().getUniqueId(), event.getQuest()); + } + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/api/QuestCompleteEvent.java b/src/main/java/com/magmaguy/elitemobs/api/QuestCompleteEvent.java new file mode 100644 index 000000000..ecfcd1515 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/api/QuestCompleteEvent.java @@ -0,0 +1,47 @@ +package com.magmaguy.elitemobs.api; + +import com.magmaguy.elitemobs.quests.Quest; +import com.magmaguy.elitemobs.utils.EventCaller; +import lombok.Getter; +import org.bukkit.entity.Player; +import org.bukkit.event.*; + +public class QuestCompleteEvent extends Event implements Cancellable { + private static final HandlerList handlers = new HandlerList(); + @Getter + private final Player player; + @Getter + private final Quest quest; + private boolean cancelled; + + public QuestCompleteEvent(Player player, Quest quest) { + this.player = player; + this.quest = quest; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + @Override + public boolean isCancelled() { + return cancelled; + } + + @Override + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + public static class QuestCompleteEventHandler implements Listener { + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + public void onQuestComplete(QuestCompleteEvent event) { + new EventCaller(new QuestRewardEvent(event.getPlayer(), event.quest)); + } + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/api/QuestLeaveEvent.java b/src/main/java/com/magmaguy/elitemobs/api/QuestLeaveEvent.java new file mode 100644 index 000000000..d594dec48 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/api/QuestLeaveEvent.java @@ -0,0 +1,61 @@ +package com.magmaguy.elitemobs.api; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.config.QuestsConfig; +import com.magmaguy.elitemobs.playerdata.database.PlayerData; +import com.magmaguy.elitemobs.quests.CustomQuest; +import com.magmaguy.elitemobs.quests.Quest; +import com.magmaguy.elitemobs.quests.QuestTracking; +import lombok.Getter; +import org.bukkit.entity.Player; +import org.bukkit.event.*; +import org.bukkit.permissions.PermissionAttachment; + +public class QuestLeaveEvent extends Event { + private static final HandlerList handlers = new HandlerList(); + @Getter + private final Player player; + @Getter + private final Quest quest; + + public QuestLeaveEvent(Player player, Quest quest) { + this.player = player; + this.quest = quest; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static class QuestLeaveEventHandler implements Listener { + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + public void onQuestLeave(QuestLeaveEvent event) { + PlayerData.removeQuest(event.getPlayer().getUniqueId(), event.getQuest()); + event.getPlayer().sendMessage(QuestsConfig.getQuestLeaveMessage().replace("$questName", event.getQuest().getQuestName())); + if (QuestsConfig.isUseQuestLeaveTitles()) + event.getPlayer().sendTitle( + QuestsConfig.getQuestLeaveTitle().replace("$questName", event.getQuest().getQuestName()), + QuestsConfig.getQuestLeaveSubtitle().replace("$questName", event.getQuest().getQuestName()), + 20, 60, 20); + if (event.getQuest() instanceof CustomQuest) { + CustomQuest customQuest = (CustomQuest) event.getQuest(); + if (!customQuest.getCustomQuestsConfigFields().getTemporaryPermissions().isEmpty()) { + PermissionAttachment permissionAttachment = event.getPlayer().addAttachment(MetadataHandler.PLUGIN); + for (String permission : customQuest.getCustomQuestsConfigFields().getTemporaryPermissions()) + permissionAttachment.setPermission(permission, false); + } + + if (QuestTracking.getPlayerTrackingQuests().containsKey(event.getPlayer())) { + QuestTracking questTracking = QuestTracking.getPlayerTrackingQuests().get(event.getPlayer()); + if (questTracking.getCustomQuest().getCustomQuestsConfigFields().equals(customQuest.getCustomQuestsConfigFields())) + questTracking.stop(); + } + } + } + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/api/QuestObjectivesCompletedEvent.java b/src/main/java/com/magmaguy/elitemobs/api/QuestObjectivesCompletedEvent.java new file mode 100644 index 000000000..97e37bafb --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/api/QuestObjectivesCompletedEvent.java @@ -0,0 +1,40 @@ +package com.magmaguy.elitemobs.api; + +import com.magmaguy.elitemobs.config.QuestsConfig; +import com.magmaguy.elitemobs.quests.Quest; +import com.magmaguy.elitemobs.utils.EventCaller; +import lombok.Getter; +import org.bukkit.entity.Player; +import org.bukkit.event.*; + +public class QuestObjectivesCompletedEvent extends Event { + private static final HandlerList handlers = new HandlerList(); + @Getter + private final Player player; + @Getter + private final Quest quest; + + public QuestObjectivesCompletedEvent(Player player, Quest customQuest) { + this.player = player; + this.quest = customQuest; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static class QuestObjectivesCompletedEventHandler implements Listener { + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + public void onObjectivesCompleted(QuestObjectivesCompletedEvent event) { + if (!QuestsConfig.isRequireQuestTurnIn()) { + QuestCompleteEvent questCompleteEvent = new QuestCompleteEvent(event.getPlayer(), event.getQuest()); + new EventCaller(questCompleteEvent); + } + } + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/api/QuestProgressionEvent.java b/src/main/java/com/magmaguy/elitemobs/api/QuestProgressionEvent.java new file mode 100644 index 000000000..df2993bac --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/api/QuestProgressionEvent.java @@ -0,0 +1,47 @@ +package com.magmaguy.elitemobs.api; + +import com.magmaguy.elitemobs.config.QuestsConfig; +import com.magmaguy.elitemobs.playerdata.database.PlayerData; +import com.magmaguy.elitemobs.quests.Quest; +import com.magmaguy.elitemobs.quests.QuestTracking; +import com.magmaguy.elitemobs.quests.objectives.Objective; +import lombok.Getter; +import org.bukkit.entity.Player; +import org.bukkit.event.*; + +public class QuestProgressionEvent extends Event { + private static final HandlerList handlers = new HandlerList(); + @Getter + private final Player player; + @Getter + private final Quest quest; + @Getter + private final Objective objective; + + public QuestProgressionEvent(Player player, Quest quest, Objective objective) { + this.player = player; + this.quest = quest; + this.objective = objective; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static class QuestProgressionEventHandler implements Listener { + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + public void onQuestProgression(QuestProgressionEvent event) { + event.getQuest().getQuestObjectives().updateQuestStatus(event.getPlayer().getUniqueId()); + if (QuestsConfig.isDoQuestChatProgression()) + event.getPlayer().sendMessage(QuestsConfig.getQuestChatProgressionMessage(event.getObjective())); + if (!QuestTracking.isTracking(event.player)) + event.getQuest().getQuestObjectives().displayTemporaryObjectivesScoreboard(event.getPlayer()); + PlayerData.updateQuestStatus(event.getPlayer().getUniqueId(), event.getQuest()); + } + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/api/QuestRewardEvent.java b/src/main/java/com/magmaguy/elitemobs/api/QuestRewardEvent.java new file mode 100644 index 000000000..2bbb8da1f --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/api/QuestRewardEvent.java @@ -0,0 +1,59 @@ +package com.magmaguy.elitemobs.api; + +import com.magmaguy.elitemobs.config.QuestsConfig; +import com.magmaguy.elitemobs.playerdata.database.PlayerData; +import com.magmaguy.elitemobs.quests.Quest; +import lombok.Getter; +import org.bukkit.entity.Player; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +public class QuestRewardEvent extends Event { + + private static final HandlerList handlers = new HandlerList(); + @Getter + private final Player player; + @Getter + private final Quest quest; + + public QuestRewardEvent(Player player, Quest quest) { + this.player = player; + this.quest = quest; + + quest.getQuestObjectives().setTurnedIn(true); + + doMessages(); + doRewards(); + + completeQuestData(); + } + + public static HandlerList getHandlerList() { + return handlers; + } + + private void doMessages() { + player.sendMessage(QuestsConfig.getQuestCompleteMessage().replace("$questName", quest.getQuestName())); + if (QuestsConfig.isUseQuestCompleteTitles()) + player.sendTitle( + QuestsConfig.getQuestCompleteTitle().replace("$questName", quest.getQuestName()), + QuestsConfig.getQuestCompleteSubtitle().replace("$questName", quest.getQuestName()), + 20, 60, 20); + } + + private void doRewards() { + //todo: add quest reward text for loot obtained + quest.getQuestObjectives().getQuestReward().doRewards(); + } + + private void completeQuestData() { + PlayerData.removeQuest(player.getUniqueId(), quest); + PlayerData.incrementQuestsCompleted(player.getUniqueId()); + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/api/SuperMobDamageEvent.java b/src/main/java/com/magmaguy/elitemobs/api/SuperMobDamageEvent.java new file mode 100644 index 000000000..10c701992 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/api/SuperMobDamageEvent.java @@ -0,0 +1,72 @@ +package com.magmaguy.elitemobs.api; + +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.utils.EventCaller; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.*; +import org.bukkit.event.entity.EntityDamageEvent; + +public class SuperMobDamageEvent extends Event implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + private final LivingEntity livingEntity; + private final EntityDamageEvent entityDamageEvent; + private boolean cancelled = false; + + public SuperMobDamageEvent(LivingEntity livingEntity, EntityDamageEvent entityDamageEvent) { + this.livingEntity = livingEntity; + this.entityDamageEvent = entityDamageEvent; + } + + public static void callEvent(LivingEntity livingEntity, EntityDamageEvent entityDamageEvent) { + new EventCaller(new SuperMobDamageEvent(livingEntity, entityDamageEvent)); + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * Returns the entity being converted to an EliteMobEntity + * + * @return Entity being converted into an Elite Mob + */ + public LivingEntity getLivingEntity() { + return this.livingEntity; + } + + public EntityDamageEvent getEntityDamageEvent() { + return this.entityDamageEvent; + } + + /** + * Returns a list of handlers + * + * @return List of handlers + */ + @Override + public HandlerList getHandlers() { + return handlers; + } + + @Override + public boolean isCancelled() { + return this.cancelled; + } + + @Override + public void setCancelled(boolean cancel) { + this.cancelled = cancel; + } + + public static class SuperMobDamageEventFilter implements Listener { + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) + public void superMobDamageFilter(EntityDamageEvent event) { + if (!EntityTracker.isSuperMob(event.getEntity())) return; + SuperMobDamageEvent superMobDamageEvent = new SuperMobDamageEvent((LivingEntity) event.getEntity(), event); + new EventCaller(superMobDamageEvent); + if (superMobDamageEvent.isCancelled()) event.setCancelled(true); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/api/SuperMobDeathEvent.java b/src/main/java/com/magmaguy/elitemobs/api/SuperMobDeathEvent.java new file mode 100644 index 000000000..3dd5bda68 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/api/SuperMobDeathEvent.java @@ -0,0 +1,58 @@ +package com.magmaguy.elitemobs.api; + +import com.magmaguy.elitemobs.api.internal.RemovalReason; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.utils.EventCaller; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.Event; +import org.bukkit.event.EventHandler; +import org.bukkit.event.HandlerList; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDeathEvent; + +public class SuperMobDeathEvent extends Event { + + private static final HandlerList handlers = new HandlerList(); + private final LivingEntity livingEntity; + + public SuperMobDeathEvent(LivingEntity livingEntity) { + this.livingEntity = livingEntity; + new SuperMobRemoveEvent(livingEntity, RemovalReason.DEATH); + } + + public static void callEvent(LivingEntity livingEntity) { + new EventCaller(new SuperMobDeathEvent(livingEntity)); + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * Returns the entity being converted to an EliteMobEntity + * + * @return Entity being converted into an Elite Mob + */ + public LivingEntity getLivingEntity() { + return this.livingEntity; + } + + /** + * Returns a list of handlers + * + * @return List of handlers + */ + @Override + public HandlerList getHandlers() { + return handlers; + } + + public static class SuperMobDeathEventFilter implements Listener { + @EventHandler + public void onMobDeath(EntityDeathEvent event) { + if (!EntityTracker.isSuperMob(event.getEntity())) return; + new EventCaller(new SuperMobDeathEvent(event.getEntity())); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/api/SuperMobRemoveEvent.java b/src/main/java/com/magmaguy/elitemobs/api/SuperMobRemoveEvent.java new file mode 100644 index 000000000..fba138a9d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/api/SuperMobRemoveEvent.java @@ -0,0 +1,40 @@ +package com.magmaguy.elitemobs.api; + +import com.magmaguy.elitemobs.api.internal.RemovalReason; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.utils.EventCaller; +import lombok.Getter; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +public class SuperMobRemoveEvent extends Event { + + private static final HandlerList handlers = new HandlerList(); + @Getter + private final LivingEntity livingEntity; + + public SuperMobRemoveEvent(LivingEntity livingEntity, RemovalReason removalReason) { + this.livingEntity = livingEntity; + EntityTracker.unregister(livingEntity, removalReason); + } + + public static void callEvent(LivingEntity livingEntity, RemovalReason removalReason) { + new EventCaller(new SuperMobRemoveEvent(livingEntity, removalReason)); + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * Returns a list of handlers + * + * @return List of handlers + */ + @Override + public HandlerList getHandlers() { + return handlers; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/api/SuperMobSpawnEvent.java b/src/main/java/com/magmaguy/elitemobs/api/SuperMobSpawnEvent.java new file mode 100644 index 000000000..bbf6ab762 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/api/SuperMobSpawnEvent.java @@ -0,0 +1,61 @@ +package com.magmaguy.elitemobs.api; + +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + +public class SuperMobSpawnEvent extends Event implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + private final LivingEntity livingEntity; + private boolean isCancelled = false; + + public SuperMobSpawnEvent(LivingEntity livingEntity) { + this.livingEntity = livingEntity; + } + + public static HandlerList getHandlerList() { + return handlers; + } + + /** + * Returns the entity being converted to an EliteMobEntity + * + * @return Entity being converted into an Elite Mob + */ + public LivingEntity getLivingEntity() { + return this.livingEntity; + } + + /** + * Returns if the event is cancelled + * + * @return If the event is cancelled + */ + @Override + public boolean isCancelled() { + return this.isCancelled; + } + + /** + * Cancels the event. This will cancel the formation of the Elite Mob and remove the living entity. Once cancelled it can't be uncancelled. + * + * @param cancel Cancels the event + */ + @Override + public void setCancelled(boolean cancel) { + this.isCancelled = cancel; + } + + /** + * Returns a list of handlers + * + * @return List of handlers + */ + @Override + public HandlerList getHandlers() { + return handlers; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/api/internal/NewMinidungeonRelativeBossLocationEvent.java b/src/main/java/com/magmaguy/elitemobs/api/internal/NewMinidungeonRelativeBossLocationEvent.java new file mode 100644 index 000000000..71d9ad518 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/api/internal/NewMinidungeonRelativeBossLocationEvent.java @@ -0,0 +1,63 @@ +package com.magmaguy.elitemobs.api.internal; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import com.magmaguy.elitemobs.dungeons.Minidungeon; +import org.bukkit.Location; +import org.bukkit.event.Cancellable; +import org.bukkit.event.Event; +import org.bukkit.event.HandlerList; + + +public class NewMinidungeonRelativeBossLocationEvent extends Event implements Cancellable { + + private static final HandlerList handlers = new HandlerList(); + private final Minidungeon minidungeon; + private final Location relativeLocation; + private final Location realLocation; + private final CustomBossesConfigFields customBossesConfigFields; + private boolean isCancelled = false; + + public NewMinidungeonRelativeBossLocationEvent(Minidungeon minidungeon, Location relativeLocation, Location realLocation, CustomBossesConfigFields customBossesConfigFields) { + this.minidungeon = minidungeon; + this.relativeLocation = relativeLocation; + this.realLocation = realLocation; + this.customBossesConfigFields = customBossesConfigFields; + if (relativeLocation == null) setCancelled(true); + } + + public static HandlerList getHandlerList() { + return handlers; + } + + public Minidungeon getMinidungeon() { + return minidungeon; + } + + public Location getRelativeLocation() { + return relativeLocation; + } + + public Location getRealLocation() { + return realLocation; + } + + public CustomBossesConfigFields getCustomBossConfigFields() { + return customBossesConfigFields; + } + + @Override + public boolean isCancelled() { + return this.isCancelled; + } + + @Override + public void setCancelled(boolean b) { + this.isCancelled = b; + } + + @Override + public HandlerList getHandlers() { + return handlers; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/api/internal/RemovalReason.java b/src/main/java/com/magmaguy/elitemobs/api/internal/RemovalReason.java new file mode 100644 index 000000000..6caa686ed --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/api/internal/RemovalReason.java @@ -0,0 +1,28 @@ +package com.magmaguy.elitemobs.api.internal; + +/** + * DEATH is used for when Elites die in a way detected correctly by EliteMobs + * CHUNK_UNLOAD fires when an Elite is removed due to a chunk unload. This is a true removal, so persistent Elites won't have it. + * WORLD_UNLOAD fires when an Elite is removed due to a World unload. Persistent Elites can't survive this. + * SHUTDOWN fires when a server shuts down, reload or when EliteMobs reloads + * OTHER fires when the reason couldn't be determined, probably a #remove() API call by another plugin + * EFFECT_TIMEOUT fires when either a power has ended or when an effect is done being displayed for any reason + */ +public enum RemovalReason { + DEATH, + PHASE_BOSS_RESET, + PHASE_BOSS_PHASE_END, + CHUNK_UNLOAD, + WORLD_UNLOAD, + SHUTDOWN, + EFFECT_TIMEOUT, + BOSS_TIMEOUT, + NPC_TIMEOUT, + OTHER, + UNSPECIFIED_WATCHDOG_REMOVAL, + REMOVE_COMMAND, + KILL_COMMAND, + REINFORCEMENT_CULL, + ENTITY_REPLACEMENT, + ARENA_RESET +} diff --git a/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/AlternativeDurabilityLoss.java b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/AlternativeDurabilityLoss.java new file mode 100644 index 000000000..51ad19f68 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/AlternativeDurabilityLoss.java @@ -0,0 +1,111 @@ +package com.magmaguy.elitemobs.collateralminecraftchanges; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.api.EliteMobsItemDetector; +import com.magmaguy.elitemobs.config.ItemSettingsConfig; +import com.magmaguy.elitemobs.items.ItemTagger; +import com.magmaguy.elitemobs.items.ItemTierFinder; +import com.magmaguy.elitemobs.utils.EntityFinder; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.entity.PlayerDeathEvent; +import org.bukkit.event.player.PlayerItemDamageEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.Damageable; + +import java.util.ArrayList; +import java.util.Arrays; + +public class AlternativeDurabilityLoss implements Listener { + + //these values are percentual + private static double durabilityLoss(ItemStack itemStack) { + boolean isWeaponMaterial = ItemTierFinder.isWeaponMaterial(itemStack); + int maxDurability = itemStack.getType().getMaxDurability() > (isWeaponMaterial ? 2000 : 1000) ? (isWeaponMaterial ? 2000 : 1000) : itemStack.getType().getMaxDurability(); + double baseModifier = isWeaponMaterial ? 2000 : 1000; + double durabilityLoss = ((baseModifier - maxDurability) / baseModifier) * ItemSettingsConfig.getEliteDurabilityMultiplier(); + double durabilityLevel = 1 + (ItemTagger.getEnchantment(itemStack.getItemMeta(), Enchantment.DURABILITY.getKey()) / 4d); + double defaultMultiplier = 0.5; //just tweaking defaults + return durabilityLoss / durabilityLevel * defaultMultiplier; + } + + private static boolean isOnLastDamage(ItemStack itemStack) { + if (itemStack == null) return false; + if (!itemStack.hasItemMeta()) return false; + if (!ItemTagger.isEliteItem(itemStack)) return false; + if (!(itemStack.getItemMeta() instanceof Damageable)) return false; + if (itemStack.getType().getMaxDurability() == 0) return false; + if (((Damageable) itemStack.getItemMeta()).getDamage() + 1 < itemStack.getType().getMaxDurability()) + return false; + return true; + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) + public void onDurabilityLoss(PlayerItemDamageEvent event) { + if (!EliteMobsItemDetector.isEliteMobsItem(event.getItem())) return; + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOWEST) + public void onPlayerDeath(PlayerDeathEvent event) { + ArrayList itemsList = new ArrayList<>(Arrays.asList(event.getEntity().getInventory().getArmorContents())); + itemsList.add(event.getEntity().getInventory().getItemInMainHand()); + itemsList.add(event.getEntity().getInventory().getItemInOffHand()); + + for (ItemStack itemStack : itemsList) + if (itemStack != null && + itemStack.getType().getMaxDurability() != 0 && + EliteMobsItemDetector.isEliteMobsItem(itemStack) && + itemStack.getItemMeta() instanceof Damageable) { + Damageable damageable = (Damageable) itemStack.getItemMeta(); + int maxDurability = itemStack.getType().getMaxDurability(); + int durabilityLoss = (int) (maxDurability * durabilityLoss(itemStack)); + int currentDurability = damageable.getDamage(); + int newDurability = currentDurability + durabilityLoss; + damageable.setDamage(newDurability); + itemStack.setItemMeta(damageable); + if (newDurability >= maxDurability) + if (ItemSettingsConfig.isPreventEliteItemsFromBreaking()) { + damageable.setDamage(maxDurability - 1); + itemStack.setItemMeta(damageable); + } else + itemStack.setAmount(0); + } + } + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + public void onPlayerDamaged(EntityDamageEvent event) { + if (!event.getEntity().getType().equals(EntityType.PLAYER)) return; + //citizens spams this really hard for some reason + if (event.getEntity().hasMetadata("NPC")) return; + Player player = (Player) event.getEntity(); + for (ItemStack itemStack : player.getInventory().getArmorContents()) + if (isOnLastDamage(itemStack)) { + player.getWorld().dropItem(player.getLocation(), itemStack.clone()); + itemStack.setAmount(0); + player.sendMessage(ChatColorConverter.convert(ItemSettingsConfig.getLowArmorDurabilityItemDropMessage())); + } + } + + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + public void onPlayerDamage(EntityDamageByEntityEvent event) { + LivingEntity livingEntity = EntityFinder.filterRangedDamagers(event.getDamager()); + if (livingEntity == null) return; + if (!livingEntity.getType().equals(EntityType.PLAYER)) return; + Player player = (Player) livingEntity; + ItemStack itemStack = player.getInventory().getItemInMainHand(); + if (isOnLastDamage(itemStack)) { + player.getWorld().dropItem(player.getLocation(), itemStack.clone()); + itemStack.setAmount(0); + player.sendMessage(ChatColorConverter.convert(ItemSettingsConfig.getLowWeaponDurabilityItemDropMessage())); + event.setCancelled(true); + } + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/AntiExploitMessage.java b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/AntiExploitMessage.java deleted file mode 100644 index d77ec0b2d..000000000 --- a/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/AntiExploitMessage.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.magmaguy.elitemobs.collateralminecraftchanges; - -import com.magmaguy.elitemobs.ChatColorConverter; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; -import net.md_5.bungee.api.ChatMessageType; -import net.md_5.bungee.api.chat.TextComponent; -import org.bukkit.entity.Entity; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; - - -public class AntiExploitMessage { - - public static void sendWarning(LivingEntity livingEntity) { - - for (Entity entity : livingEntity.getNearbyEntities(15, 15, 15)) - if (entity instanceof Player) { - Player player = (Player) entity; - player.spigot().sendMessage(ChatMessageType.ACTION_BAR, - TextComponent.fromLegacyText(ChatColorConverter.convert(ConfigValues.mobCombatSettingsConfig.getString(MobCombatSettingsConfig.ANTI_EXPLOIT_MESSAGE)))); - } - - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/ChunkUnloadMetadataPurge.java b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/ChunkUnloadMetadataPurge.java deleted file mode 100644 index df545a6a9..000000000 --- a/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/ChunkUnloadMetadataPurge.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.collateralminecraftchanges; - -import com.magmaguy.elitemobs.EntityTracker; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.world.ChunkUnloadEvent; - - -/** - * Created by MagmaGuy on 20/12/2016. - */ -public class ChunkUnloadMetadataPurge implements Listener { - - @EventHandler - public void onUnload(ChunkUnloadEvent event) { - EntityTracker.chunkWiper(event); - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/CombustionPrevention.java b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/CombustionPrevention.java new file mode 100644 index 000000000..5491259a5 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/CombustionPrevention.java @@ -0,0 +1,16 @@ +package com.magmaguy.elitemobs.collateralminecraftchanges; + +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityCombustEvent; +import org.bukkit.potion.PotionEffectType; + +public class CombustionPrevention implements Listener { + @EventHandler + public void onCombust(EntityCombustEvent event) { + if (event.getEntity() instanceof LivingEntity && + ((LivingEntity) event.getEntity()).hasPotionEffect(PotionEffectType.FIRE_RESISTANCE)) + event.setCancelled(true); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/EliteBlazeWaterDamagePrevention.java b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/EliteBlazeWaterDamagePrevention.java new file mode 100644 index 000000000..4cd3e9b86 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/EliteBlazeWaterDamagePrevention.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.collateralminecraftchanges; + +import com.magmaguy.elitemobs.api.EliteMobDamagedEvent; +import org.bukkit.entity.EntityType; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageEvent; + +public class EliteBlazeWaterDamagePrevention implements Listener { + @EventHandler(priority = EventPriority.LOWEST) + public void onBlazeWaterDamage(EliteMobDamagedEvent event) { + if (event.getEntity() == null) return; + if (!event.getEntity().getType().equals(EntityType.BLAZE)) return; + if (!event.getEntityDamageEvent().getCause().equals(EntityDamageEvent.DamageCause.DROWNING)) return; + event.setCancelled(true); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/EnderCrystalDamageProtectionBypass.java b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/EnderCrystalDamageProtectionBypass.java new file mode 100644 index 000000000..cf0424d5d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/EnderCrystalDamageProtectionBypass.java @@ -0,0 +1,20 @@ +package com.magmaguy.elitemobs.collateralminecraftchanges; + +import com.magmaguy.elitemobs.utils.EntityFinder; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +public class EnderCrystalDamageProtectionBypass implements Listener { + @EventHandler(priority = EventPriority.HIGHEST) + public void onEntityDamageByEntityEvent(EntityDamageByEntityEvent event) { + if (!event.isCancelled()) return; + if (!event.getEntity().getType().equals(EntityType.ENDER_CRYSTAL)) return; + LivingEntity entity = EntityFinder.filterRangedDamagers(event.getDamager()); + if (entity == null || !entity.getType().equals(EntityType.PLAYER)) return; + event.setCancelled(false); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/EnderDragonUnstuck.java b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/EnderDragonUnstuck.java new file mode 100644 index 000000000..cf15fe3c8 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/EnderDragonUnstuck.java @@ -0,0 +1,37 @@ +package com.magmaguy.elitemobs.collateralminecraftchanges; + +import com.magmaguy.elitemobs.api.EliteMobEnterCombatEvent; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import org.bukkit.entity.EnderDragon; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Wolf; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityTargetLivingEntityEvent; + +public class EnderDragonUnstuck implements Listener { + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) + public void onDragonEnterCombat(EliteMobEnterCombatEvent event) { + if (event.getEliteMobEntity() == null) return; + if (event.getEliteMobEntity().getLivingEntity() == null) return; + if (!event.getEliteMobEntity().getLivingEntity().getType().equals(EntityType.ENDER_DRAGON)) return; + event.getEliteMobEntity().getLivingEntity().setAI(true); + ((EnderDragon) event.getEliteMobEntity().getLivingEntity()).setPhase(EnderDragon.Phase.LEAVE_PORTAL); + } + + public static class AggroPrevention implements Listener { + + @EventHandler(ignoreCancelled = true) + public void onTarget(EntityTargetLivingEntityEvent event) { + if (event.getEntity().getType().equals(EntityType.WOLF) && !((Wolf) event.getEntity()).isAngry() || + event.getTarget() != null && + event.getTarget().getType().equals(EntityType.WOLF) && !((Wolf) event.getTarget()).isAngry()) + return; + if (EntityTracker.isEliteMob(event.getEntity()) && event.getTarget() != null && EntityTracker.isEliteMob(event.getTarget()) || + EntityTracker.isEliteMob(event.getEntity()) && event.getTarget() != null && EntityTracker.isNPCEntity(event.getTarget())) + event.setCancelled(true); + } + + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/EntityDeathDataFlusher.java b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/EntityDeathDataFlusher.java deleted file mode 100644 index b402c859d..000000000 --- a/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/EntityDeathDataFlusher.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.collateralminecraftchanges; - -import com.magmaguy.elitemobs.EntityTracker; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDeathEvent; - -/** - * Created by MagmaGuy on 14/07/2017. - */ -public class EntityDeathDataFlusher implements Listener { - - @EventHandler(priority = EventPriority.MONITOR) - public void onEntityDeathFlushData(EntityDeathEvent event) { - - EntityTracker.deathWipe(event); - - } - - -} diff --git a/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/EntityTransformHandler.java b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/EntityTransformHandler.java new file mode 100644 index 000000000..880202157 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/EntityTransformHandler.java @@ -0,0 +1,24 @@ +package com.magmaguy.elitemobs.collateralminecraftchanges; + +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.CreatureSpawnEvent; +import org.bukkit.event.entity.EntityTransformEvent; + +public class EntityTransformHandler implements Listener { + + @EventHandler + public void onMobTransform(EntityTransformEvent event) { + EliteEntity eliteEntity = EntityTracker.getEliteMobEntity(event.getEntity()); + if (eliteEntity == null) return; + if (eliteEntity instanceof CustomBossEntity) + ((CustomBossEntity) eliteEntity).resetLivingEntity((LivingEntity) event.getTransformedEntity(), CreatureSpawnEvent.SpawnReason.CUSTOM); + else + eliteEntity.setLivingEntity((LivingEntity) event.getTransformedEntity(), CreatureSpawnEvent.SpawnReason.CUSTOM); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/FindNewWorlds.java b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/FindNewWorlds.java new file mode 100644 index 000000000..236a57873 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/FindNewWorlds.java @@ -0,0 +1,16 @@ +package com.magmaguy.elitemobs.collateralminecraftchanges; + +import com.magmaguy.elitemobs.config.ValidWorldsConfig; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.world.WorldLoadEvent; + +public class FindNewWorlds implements Listener { + + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) + public void onWorldLoad(WorldLoadEvent event) { + ValidWorldsConfig.addWorld(event.getWorld().getName()); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/FindSuperMobs.java b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/FindSuperMobs.java index 95ea00ed0..5e14a0ac8 100644 --- a/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/FindSuperMobs.java +++ b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/FindSuperMobs.java @@ -1,7 +1,10 @@ package com.magmaguy.elitemobs.collateralminecraftchanges; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; import com.magmaguy.elitemobs.mobconstructor.mobdata.passivemobs.SuperMobProperties; +import org.bukkit.attribute.Attribute; import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.world.ChunkLoadEvent; @@ -10,11 +13,12 @@ public class FindSuperMobs implements Listener { @EventHandler public void findSuperMob(ChunkLoadEvent event) { - for (Entity entity : event.getChunk().getEntities()) - if (SuperMobProperties.isValidSuperMobType(entity)) { - } - + if (SuperMobProperties.isValidSuperMobType(entity)) + if (((LivingEntity) entity).getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue() == + SuperMobProperties.getDataInstance(entity).getSuperMobMaxHealth()) + if (!EntityTracker.isSuperMob(entity)) + EntityTracker.registerSuperMob((LivingEntity) entity); } } diff --git a/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/ItemEnchantmentPrevention.java b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/ItemEnchantmentPrevention.java new file mode 100644 index 000000000..e7174e502 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/ItemEnchantmentPrevention.java @@ -0,0 +1,20 @@ +package com.magmaguy.elitemobs.collateralminecraftchanges; + +import com.magmaguy.elitemobs.items.ItemTagger; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import org.bukkit.Material; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.PrepareAnvilEvent; + +public class ItemEnchantmentPrevention implements Listener { + @EventHandler(priority = EventPriority.HIGHEST) + public void onResultGeneration(PrepareAnvilEvent event) { + if (!ItemTagger.isEliteItem(event.getInventory().getItem(0)) && + !ItemTagger.isEliteItem(event.getInventory().getItem(1))) + return; + event.setResult(ItemStackGenerator.generateItemStack(Material.AIR)); + event.getInventory().setRepairCost(300); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/KeepNeutralsAngry.java b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/KeepNeutralsAngry.java new file mode 100644 index 000000000..d1f4d4d5c --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/KeepNeutralsAngry.java @@ -0,0 +1,57 @@ +package com.magmaguy.elitemobs.collateralminecraftchanges; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.attribute.Attribute; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Mob; +import org.bukkit.entity.Player; +import org.bukkit.entity.Wolf; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.HashSet; +import java.util.Objects; + +public class KeepNeutralsAngry { + private static final HashSet angryMobs = new HashSet<>(); + + private KeepNeutralsAngry() { + } + + public static void showMeYouWarFace(EliteEntity eliteEntity) { + //might already contain + EntityType entityType = eliteEntity.getLivingEntity().getType(); + if (angryMobs.contains(eliteEntity)) return; + new BukkitRunnable() { + @Override + public void run() { + //It is possible for entities to change type during combat, in which case they need to be wiped + if (!eliteEntity.isValid() || + !entityType.equals(eliteEntity.getLivingEntity().getType()) || + entityType.equals(EntityType.WOLF) && ((Wolf) eliteEntity.getLivingEntity()).isTamed()) { + cancel(); + angryMobs.remove(eliteEntity); + return; + } + + if (!eliteEntity.getLivingEntity().getType().equals(EntityType.LLAMA) && + ((Mob) eliteEntity.getLivingEntity()).getTarget() != null) + return; + + for (Player player : Bukkit.getOnlinePlayers()) + if (!player.getGameMode().equals(GameMode.SPECTATOR) && !player.getGameMode().equals(GameMode.CREATIVE) && + Objects.equals(player.getLocation().getWorld(), eliteEntity.getLocation().getWorld()) && + player.getLocation().distance(eliteEntity.getLocation()) < + Objects.requireNonNull(eliteEntity.getLivingEntity().getAttribute(Attribute.GENERIC_FOLLOW_RANGE)).getBaseValue()) { + ((Mob) eliteEntity.getLivingEntity()).setTarget(player); + return; + } + + ((Mob) eliteEntity.getLivingEntity()).setTarget(null); + + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 20); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/LightningSpawnBypass.java b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/LightningSpawnBypass.java new file mode 100644 index 000000000..2799cd2bf --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/LightningSpawnBypass.java @@ -0,0 +1,24 @@ +package com.magmaguy.elitemobs.collateralminecraftchanges; + +import org.bukkit.entity.EntityType; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntitySpawnEvent; + +public class LightningSpawnBypass implements Listener { + private static boolean bypass = false; + + public static void bypass() { + bypass = true; + } + + //This overrides region protection plugins that would delete lightning - breaking powers and effects + @EventHandler(priority = EventPriority.HIGHEST) + public void onLightningSpawn(EntitySpawnEvent event) { + if (!bypass) return; + if (!event.getEntity().getType().equals(EntityType.LIGHTNING)) return; + bypass = true; + event.setCancelled(false); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/PlayerDeathMessageByEliteMob.java b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/PlayerDeathMessageByEliteMob.java index 5acac3794..d07445d93 100644 --- a/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/PlayerDeathMessageByEliteMob.java +++ b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/PlayerDeathMessageByEliteMob.java @@ -1,24 +1,9 @@ -/* - * 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 . - */ - package com.magmaguy.elitemobs.collateralminecraftchanges; import com.magmaguy.elitemobs.ChatColorConverter; -import com.magmaguy.elitemobs.EntityTracker; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.playerdata.PlayerStatsTracker; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -26,10 +11,11 @@ import org.bukkit.event.entity.PlayerDeathEvent; import java.util.HashMap; +import java.util.concurrent.ThreadLocalRandom; public class PlayerDeathMessageByEliteMob implements Listener { - private static HashMap deadPlayerList = new HashMap<>(); + private static final HashMap deadPlayerList = new HashMap<>(); public static void addDeadPlayer(Player player, String deathMessage) { deadPlayerList.put(player, deathMessage); @@ -43,85 +29,23 @@ private static void removeDeadPlayer(Player player) { deadPlayerList.remove(player); } - @EventHandler - public void onPlayerDeath(PlayerDeathEvent event) { + public static String initializeDeathMessage(Player player, LivingEntity livingEntity) { - if (isDeadPlayer(event.getEntity())) { - event.setDeathMessage(deadPlayerList.get(event.getEntity())); - removeDeadPlayer(event.getEntity()); - } + String deathMessage = ""; - } - - public static String intializeDeathMessage(Player player, LivingEntity livingEntity) { - - String deathMessage; - - /* - Deal with players dying from Elite Mobs - */ - - switch (livingEntity.getType()) { - - case BLAZE: - deathMessage = deathMessageSender(MobCombatSettingsConfig.BLAZE_DEATH_MESSAGE, player, livingEntity); - break; - case CREEPER: - deathMessage = deathMessageSender(MobCombatSettingsConfig.CREEPER_DEATH_MESSAGE, player, livingEntity); - break; - case ENDERMAN: - deathMessage = deathMessageSender(MobCombatSettingsConfig.ENDERMAN_DEATH_MESSAGE, player, livingEntity); - break; - case ENDERMITE: - deathMessage = deathMessageSender(MobCombatSettingsConfig.ENDERMITE_DEATH_MESSAGE, player, livingEntity); - break; - case IRON_GOLEM: - deathMessage = deathMessageSender(MobCombatSettingsConfig.IRONGOLEM_DEATH_MESSAGE, player, livingEntity); - break; - case POLAR_BEAR: - deathMessage = deathMessageSender(MobCombatSettingsConfig.POLARBEAR_DEATH_MESSAGE, player, livingEntity); - break; - case SILVERFISH: - deathMessage = deathMessageSender(MobCombatSettingsConfig.SILVERFISH_DEATH_MESSAGE, player, livingEntity); - break; - case SKELETON: - deathMessage = deathMessageSender(MobCombatSettingsConfig.SKELETON_DEATH_MESSAGE, player, livingEntity); - break; - case SPIDER: - deathMessage = deathMessageSender(MobCombatSettingsConfig.SPIDER_DEATH_MESSAGE, player, livingEntity); - break; - case WITCH: - deathMessage = deathMessageSender(MobCombatSettingsConfig.WITCH_DEATH_MESSAGE, player, livingEntity); - break; - case ZOMBIE: - deathMessage = deathMessageSender(MobCombatSettingsConfig.ZOMBIE_DEATH_MESSAGE, player, livingEntity); - break; - case HUSK: - deathMessage = deathMessageSender(MobCombatSettingsConfig.HUSK_DEATH_MESSAGE, player, livingEntity); - break; - case PIG_ZOMBIE: - deathMessage = deathMessageSender(MobCombatSettingsConfig.ZOMBIE_PIGMAN_DEATH_MESSAGE, player, livingEntity); - break; - case STRAY: - deathMessage = deathMessageSender(MobCombatSettingsConfig.STRAY_DEATH_MESSAGE, player, livingEntity); - break; - case WITHER_SKELETON: - deathMessage = deathMessageSender(MobCombatSettingsConfig.WITHER_SKELETON_DEATH_MESSAGE, player, livingEntity); - break; - default: - deathMessage = deathMessageSender(MobCombatSettingsConfig.DEFAULT_DEATH_MESSAGE, player, livingEntity); - break; - } + if (MobPropertiesConfig.getMobProperties().containsKey(livingEntity.getType())) + deathMessage = deathMessageSender + (MobPropertiesConfig.getMobProperties().get(livingEntity.getType()).getDeathMessages() + .get(ThreadLocalRandom.current().nextInt(MobPropertiesConfig.getMobProperties().get(livingEntity.getType()).getDeathMessages().size())) + , player, livingEntity); return deathMessage; } - private static String deathMessageSender(String configNode, Player player, LivingEntity livingEntity) { + private static String deathMessageSender(String deathMessage, Player player, LivingEntity livingEntity) { - String deathMessage = ConfigValues.mobCombatSettingsConfig.getString(configNode); deathMessage = deathMessagePlaceholderConversion(deathMessage, player, livingEntity); - return deathMessage; } @@ -132,10 +56,21 @@ private static String deathMessagePlaceholderConversion(String deathMessage, Pla deathMessage = deathMessage.replace("$player", player.getDisplayName()); deathMessage = deathMessage.replace("$entity", livingEntityName); - deathMessage = ChatColorConverter.convert(deathMessage); + deathMessage = ChatColorConverter.convert("&7" + deathMessage); return deathMessage; } + @EventHandler + public void onPlayerDeath(PlayerDeathEvent event) { + + if (isDeadPlayer(event.getEntity())) { + event.setDeathMessage(deadPlayerList.get(event.getEntity())); + PlayerStatsTracker.registerPlayerDeath(event.getEntity()); + removeDeadPlayer(event.getEntity()); + } + + } + } diff --git a/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/PreventDarkroomExploit.java b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/PreventDarkroomExploit.java deleted file mode 100644 index 650b6182f..000000000 --- a/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/PreventDarkroomExploit.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.magmaguy.elitemobs.collateralminecraftchanges; - -import com.magmaguy.elitemobs.EntityTracker; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.entity.Entity; -import org.bukkit.entity.LivingEntity; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageEvent; -import org.bukkit.util.Vector; - -public class PreventDarkroomExploit implements Listener { - - @EventHandler - public void onDamage(EntityDamageEvent event) { - - if (!EntityTracker.isNaturalEntity(event.getEntity())) return; - - int livingEntityCount = 1; - for (Entity entity : event.getEntity().getNearbyEntities(1, 1, 1)) - if (entity instanceof LivingEntity) - livingEntityCount++; - - - if (livingEntityCount < 2) return; - - Location entityLocation = event.getEntity().getLocation().getBlock().getLocation().add(0.5, 0, 0.5); - - Block block1 = entityLocation.clone().add(new Vector(0, 0, 1)).getBlock(); - Block block2 = entityLocation.clone().add(new Vector(0, 0, -1)).getBlock(); - Block block3 = entityLocation.clone().add(new Vector(0, 1, 1)).getBlock(); - Block block4 = entityLocation.clone().add(new Vector(0, 1, -1)).getBlock(); - Block block5 = entityLocation.clone().add(new Vector(1, 0, 0)).getBlock(); - Block block6 = entityLocation.clone().add(new Vector(-1, 0, 0)).getBlock(); - Block block7 = entityLocation.clone().add(new Vector(1, 1, 0)).getBlock(); - Block block8 = entityLocation.clone().add(new Vector(-1, 1, 0)).getBlock(); - - if (!block3.getType().equals(Material.AIR) && !block4.getType().equals(Material.AIR) && - !block7.getType().equals(Material.AIR) && !block8.getType().equals(Material.AIR)) { - EntityTracker.unregisterNaturalEntity((LivingEntity) event.getEntity()); - Bukkit.getLogger().warning("Running"); - AntiExploitMessage.sendWarning((LivingEntity) event.getEntity()); - return; - } - - int airCount = 0; - - if (block1.getType().equals(Material.AIR)) - airCount++; - if (block2.getType().equals(Material.AIR)) - airCount++; - if (block3.getType().equals(Material.AIR)) - airCount++; - if (block4.getType().equals(Material.AIR)) - airCount++; - if (block5.getType().equals(Material.AIR)) - airCount++; - if (block6.getType().equals(Material.AIR)) - airCount++; - if (block7.getType().equals(Material.AIR)) - airCount++; - if (block8.getType().equals(Material.AIR)) - airCount++; - - if (airCount >= 4) return; - - EntityTracker.unregisterNaturalEntity((LivingEntity) event.getEntity()); - AntiExploitMessage.sendWarning((LivingEntity) event.getEntity()); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/PreventEliteBeeHiveEnter.java b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/PreventEliteBeeHiveEnter.java new file mode 100644 index 000000000..1f257b4f5 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/PreventEliteBeeHiveEnter.java @@ -0,0 +1,14 @@ +package com.magmaguy.elitemobs.collateralminecraftchanges; + +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityEnterBlockEvent; + +public class PreventEliteBeeHiveEnter implements Listener { + @EventHandler + public void onBeeEnterHive(EntityEnterBlockEvent event) { + if (EntityTracker.isEliteMob(event.getEntity())) + event.setCancelled(true); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/PreventEliteEquipmentDrop.java b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/PreventEliteEquipmentDrop.java new file mode 100644 index 000000000..202e68edf --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/PreventEliteEquipmentDrop.java @@ -0,0 +1,24 @@ +package com.magmaguy.elitemobs.collateralminecraftchanges; + +import com.magmaguy.elitemobs.api.EliteMobDeathEvent; +import org.bukkit.Material; +import org.bukkit.entity.Mob; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.inventory.ItemStack; + +public class PreventEliteEquipmentDrop implements Listener { + + @EventHandler(priority = EventPriority.HIGHEST) + public void onEliteDeath(EliteMobDeathEvent event) { + if (event.getEntityDeathEvent() == null) return; + if (!(event.getEntity() instanceof Mob)) return; + if (((Mob) event.getEntity()).getEquipment() == null) return; + for (ItemStack drop : event.getEntityDeathEvent().getDrops()) + for (ItemStack equipment : ((Mob) event.getEntity()).getEquipment().getArmorContents()) + if (equipment != null && drop != null && drop.equals(equipment)) + drop.setType(Material.AIR); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/PreventEliteSilverfishBlockEnter.java b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/PreventEliteSilverfishBlockEnter.java new file mode 100644 index 000000000..ef8b4f30c --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/PreventEliteSilverfishBlockEnter.java @@ -0,0 +1,14 @@ +package com.magmaguy.elitemobs.collateralminecraftchanges; + +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityChangeBlockEvent; + +public class PreventEliteSilverfishBlockEnter implements Listener { + @EventHandler + public void onSilverfishBlockEnter(EntityChangeBlockEvent event) { + if (EntityTracker.isEliteMob(event.getEntity())) + event.setCancelled(true); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/PreventItemPickupByMobs.java b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/PreventItemPickupByMobs.java new file mode 100644 index 000000000..0b22b12c9 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/PreventItemPickupByMobs.java @@ -0,0 +1,16 @@ +package com.magmaguy.elitemobs.collateralminecraftchanges; + +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityPickupItemEvent; + +public class PreventItemPickupByMobs implements Listener { + + @EventHandler + public void onItemPickup(EntityPickupItemEvent event) { + if (EntityTracker.isEliteMob(event.getEntity())) + event.setCancelled(true); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/PreventMountExploit.java b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/PreventMountExploit.java deleted file mode 100644 index d5c2a5d11..000000000 --- a/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/PreventMountExploit.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.magmaguy.elitemobs.collateralminecraftchanges; - -import com.magmaguy.elitemobs.EntityTracker; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.spigotmc.event.entity.EntityMountEvent; - -public class PreventMountExploit implements Listener { - - @EventHandler - public void mountEvent(EntityMountEvent event) { - - if (EntityTracker.isEliteMob(event.getEntity())) event.setCancelled(true); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/PreventTowerExploit.java b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/PreventTowerExploit.java deleted file mode 100644 index 2fa68dd35..000000000 --- a/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/PreventTowerExploit.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.magmaguy.elitemobs.collateralminecraftchanges; - -import com.magmaguy.elitemobs.EntityTracker; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; -import org.bukkit.entity.Projectile; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.util.Vector; - -public class PreventTowerExploit implements Listener { - - @EventHandler - public void onHit(EntityDamageByEntityEvent event) { - - if (!(event instanceof LivingEntity)) return; - LivingEntity livingEntity = (LivingEntity) event.getEntity(); - if (!EntityTracker.isNaturalEntity(livingEntity)) return; - if (!(event.getDamager() instanceof Projectile && - ((Projectile) event.getDamager()).getShooter() instanceof Player || - event.getDamager() instanceof Player)) - return; - - Location mobLocation = event.getEntity().getLocation().add(new Vector(0.5, 0, 0.5)); - Location playerLocation; - if (event.getDamager() instanceof Player) - playerLocation = event.getDamager().getLocation(); - else - playerLocation = ((Player) ((Projectile) event.getDamager()).getShooter()).getLocation().getBlock().getLocation().add(new Vector(0.5, 0, 0.5)); - - if (playerLocation.getY() - mobLocation.getY() < 2) return; - - Block block1 = playerLocation.clone().add(new Vector(0, -1, 1)).getBlock(); - Block block2 = playerLocation.clone().add(new Vector(0, -1, -1)).getBlock(); - Block block3 = playerLocation.clone().add(new Vector(0, -2, 1)).getBlock(); - Block block4 = playerLocation.clone().add(new Vector(0, -2, -1)).getBlock(); - Block block5 = playerLocation.clone().add(new Vector(1, -1, 0)).getBlock(); - Block block6 = playerLocation.clone().add(new Vector(-1, -1, 0)).getBlock(); - Block block7 = playerLocation.clone().add(new Vector(1, -2, 0)).getBlock(); - Block block8 = playerLocation.clone().add(new Vector(-1, -2, 0)).getBlock(); - - if (!(block1.getType().equals(Material.AIR) && block2.getType().equals(Material.AIR) && - block3.getType().equals(Material.AIR) && block4.getType().equals(Material.AIR) && - block5.getType().equals(Material.AIR) && block6.getType().equals(Material.AIR) && - block7.getType().equals(Material.AIR) && block8.getType().equals(Material.AIR))) - return; - - EntityTracker.unregisterNaturalEntity(livingEntity); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/PreventUpgradeDiamondToNetherite.java b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/PreventUpgradeDiamondToNetherite.java new file mode 100644 index 000000000..737d72a89 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/PreventUpgradeDiamondToNetherite.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.collateralminecraftchanges; + +import com.magmaguy.elitemobs.items.ItemTagger; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import org.bukkit.Material; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.PrepareSmithingEvent; + +public class PreventUpgradeDiamondToNetherite implements Listener { + @EventHandler + public void UpgradeItemEvent(PrepareSmithingEvent event) { + if (!ItemTagger.isEliteItem(event.getInventory().getItem(0)) && + !ItemTagger.isEliteItem(event.getInventory().getItem(1))) + return; + event.setResult(ItemStackGenerator.generateItemStack(Material.AIR)); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/VanillaReinforcementsCanceller.java b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/VanillaReinforcementsCanceller.java new file mode 100644 index 000000000..94d0125ac --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/collateralminecraftchanges/VanillaReinforcementsCanceller.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.collateralminecraftchanges; + +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.CreatureSpawnEvent; + +public class VanillaReinforcementsCanceller implements Listener { + @EventHandler(priority = EventPriority.LOWEST, ignoreCancelled = true) + public void onSpawn(CreatureSpawnEvent event) { + if (!event.getSpawnReason().equals(CreatureSpawnEvent.SpawnReason.REINFORCEMENTS)) return; + EliteEntity eliteEntity = EntityTracker.getEliteMobEntity(event.getEntity()); + if (eliteEntity == null) return; + event.setCancelled(true); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/combatsystem/CombatSystem.java b/src/main/java/com/magmaguy/elitemobs/combatsystem/CombatSystem.java new file mode 100644 index 000000000..c1b543279 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/combatsystem/CombatSystem.java @@ -0,0 +1,24 @@ +package com.magmaguy.elitemobs.combatsystem; + +public class CombatSystem { + public static final double PER_LEVEL_POWER_INCREASE = 0.5; + /** + * This determines how many hits it takes to kill a boss. + * Unfortunately, since it's flat, at a scale, all bosses tend to end up having the same amount of life. + * It accomplishes this by adding this flat amount of health to bosses. + */ + public static final double TARGET_HITS_TO_KILL = 7D; //affects max health assignment on EliteMobEntity.java + //this sets the tier of various materials + public static final int TRIDENT_TIER_LEVEL = 9; + public static final int NETHERITE_TIER_LEVEL = 8; + public static final int DIAMOND_TIER_LEVEL = 7; + public static final int IRON_TIER_LEVEL = 6; + public static final int STONE_CHAIN_TIER_LEVEL = 5; + public static final int GOLD_WOOD_LEATHER_TIER_LEVEL = 3; + //this bypasses the damage system, outputting a raw damage value + public static boolean bypass = false; + + private CombatSystem() { + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/combatsystem/EliteCreeperExplosionHandler.java b/src/main/java/com/magmaguy/elitemobs/combatsystem/EliteCreeperExplosionHandler.java new file mode 100644 index 000000000..f59a8804e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/combatsystem/EliteCreeperExplosionHandler.java @@ -0,0 +1,69 @@ +package com.magmaguy.elitemobs.combatsystem; + +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.playerdata.ElitePlayerInventory; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.*; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.entity.ExplosionPrimeEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.potion.PotionEffect; + +import java.util.HashSet; + +public class EliteCreeperExplosionHandler implements Listener { + + private static final HashSet explosionPlayers = new HashSet<>(); + + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onEliteCreeperDetonation(ExplosionPrimeEvent event) { + + if (!(event.getEntity() instanceof Creeper && EntityTracker.isEliteMob(event.getEntity()))) + return; + + /* + This is necessary because the propagate the same duration as they have, which is nearly infinite + */ + for (PotionEffect potionEffect : ((Creeper) event.getEntity()).getActivePotionEffects()) + ((Creeper) event.getEntity()).removePotionEffect(potionEffect.getType()); + + EliteEntity eliteEntity = EntityTracker.getEliteMobEntity(event.getEntity()); + + for (Entity entity : event.getEntity().getNearbyEntities(event.getRadius(), event.getRadius(), event.getRadius())) + if (entity.getType().equals(EntityType.PLAYER)) { + Player player = (Player) entity; + explosionPlayers.add(player); + ElitePlayerInventory elitePlayerInventory = ElitePlayerInventory.playerInventories.get(player.getUniqueId()); + + if (elitePlayerInventory == null) continue; + double damageReduction = 0; + for (ItemStack itemStack : player.getInventory().getArmorContents()) { + if (itemStack == null) continue; + for (Enchantment enchantment : itemStack.getEnchantments().keySet()) + if (enchantment.getName().equals(Enchantment.PROTECTION_EXPLOSIONS.getName())) + damageReduction += PlayerDamagedByEliteMobHandler.getDamageIncreasePercentage(enchantment, itemStack); + } + damageReduction += elitePlayerInventory.baseDamageReduction(); + double finalDamage = eliteEntity.getLevel() - damageReduction; + finalDamage = finalDamage < 0 ? 0 : finalDamage; + player.damage(finalDamage, eliteEntity.getLivingEntity()); + } else if (entity instanceof LivingEntity) + ((LivingEntity) entity).damage(eliteEntity.getLevel()); + + } + + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) + public void playerDamagedByExplosionEvent(EntityDamageEvent event) { + if (!event.getEntity().getType().equals(EntityType.PLAYER)) return; + if (!event.getCause().equals(EntityDamageEvent.DamageCause.ENTITY_EXPLOSION)) return; + Player player = (Player) event.getEntity(); + if (!explosionPlayers.contains(player)) return; + explosionPlayers.remove(player); + event.setDamage(0); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/combatsystem/EliteMobDamagedByEliteMobHandler.java b/src/main/java/com/magmaguy/elitemobs/combatsystem/EliteMobDamagedByEliteMobHandler.java new file mode 100644 index 000000000..baec207fc --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/combatsystem/EliteMobDamagedByEliteMobHandler.java @@ -0,0 +1,29 @@ +package com.magmaguy.elitemobs.combatsystem; + +import com.magmaguy.elitemobs.api.EliteMobDamagedByEliteMobEvent; +import org.bukkit.entity.EntityType; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageEvent; + +public class EliteMobDamagedByEliteMobHandler implements Listener { + + @EventHandler + public void onIronGolemDamage(EliteMobDamagedByEliteMobEvent event) { + + if (event.isCancelled()) return; + + if (!(event.getDamager().getLivingEntity().getType().equals(EntityType.IRON_GOLEM) || + event.getDamagee().getLivingEntity().getType().equals(EntityType.IRON_GOLEM))) return; + + double damage = event.getEntityDamageByEntityEvent().getDamage() * event.getDamager().getLevel() * CombatSystem.PER_LEVEL_POWER_INCREASE; + + for (EntityDamageEvent.DamageModifier modifier : EntityDamageEvent.DamageModifier.values()) + if (event.getEntityDamageByEntityEvent().isApplicable(modifier)) + event.getEntityDamageByEntityEvent().setDamage(modifier, 0); + + event.getEntityDamageByEntityEvent().setDamage(damage); + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/combatsystem/EliteMobGenericDamagedHandler.java b/src/main/java/com/magmaguy/elitemobs/combatsystem/EliteMobGenericDamagedHandler.java new file mode 100644 index 000000000..ad7d38a75 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/combatsystem/EliteMobGenericDamagedHandler.java @@ -0,0 +1,21 @@ +package com.magmaguy.elitemobs.combatsystem; + +import com.magmaguy.elitemobs.api.EliteMobDamagedEvent; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageEvent; + +public class EliteMobGenericDamagedHandler implements Listener { + + @EventHandler(priority = EventPriority.HIGHEST) + public void eliteMobDamagedGeneric(EliteMobDamagedEvent event) { + + if (event.isCancelled()) return; + if (event.getEntityDamageEvent().getCause().equals(EntityDamageEvent.DamageCause.ENTITY_ATTACK)) return; + if (!event.getEntityDamageEvent().getCause().equals(EntityDamageEvent.DamageCause.CUSTOM)) + event.getEntityDamageEvent().setDamage(EntityDamageEvent.DamageModifier.BASE, event.getEntityDamageEvent().getDamage()); + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/combatsystem/EliteProjectile.java b/src/main/java/com/magmaguy/elitemobs/combatsystem/EliteProjectile.java new file mode 100644 index 000000000..a9f963907 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/combatsystem/EliteProjectile.java @@ -0,0 +1,61 @@ +package com.magmaguy.elitemobs.combatsystem; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import org.bukkit.Location; +import org.bukkit.NamespacedKey; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.entity.Projectile; +import org.bukkit.persistence.PersistentDataType; +import org.bukkit.projectiles.ProjectileSource; +import org.bukkit.util.Vector; + +public class EliteProjectile { + private EliteProjectile() { + } + + public static Projectile create(EntityType entityType, Entity shooter, Entity victim, Vector shotVector, boolean gravity) { + Location projectileLocation = generateLocation(shooter, victim); + Projectile projectile = (Projectile) projectileLocation.getWorld().spawnEntity(projectileLocation, entityType); + projectile.setShooter((ProjectileSource) shooter); + projectile.setVelocity(shotVector); + projectile.setGravity(gravity); + EntityTracker.registerProjectileEntity(projectile); + return projectile; + } + + public static Projectile create(EntityType entityType, Entity shooter, Player victim, boolean gravity) { + Vector targetterToTargetted = victim.getEyeLocation().clone().subtract(victim.getLocation()).toVector().normalize().multiply(2); + return create(entityType, shooter, victim, targetterToTargetted, gravity); + } + + public static Projectile create(EntityType entityType, Entity shooter, Vector targetterToTargetted, boolean gravity) { + Location projectileLocation = generateLocation(shooter, targetterToTargetted); + Projectile projectile = (Projectile) projectileLocation.getWorld().spawnEntity(projectileLocation, entityType); + projectile.setShooter((ProjectileSource) shooter); + projectile.setVelocity(targetterToTargetted); + projectile.setGravity(gravity); + EntityTracker.registerProjectileEntity(projectile); + return projectile; + } + + private static Location generateLocation(Entity shooter, Entity victim) { + Vector vector = victim.getLocation().clone().subtract(shooter.getLocation().clone()).toVector().normalize(); + return shooter.getLocation().clone().add(0, 1, 0).add(vector).setDirection(vector); + } + + private static Location generateLocation(Entity shooter, Vector targetterToTargetted) { + return shooter.getLocation().clone().add(targetterToTargetted).setDirection(targetterToTargetted).add(new Vector(0, 1, 0)); + } + + public static void signExplosiveWithPower(Projectile projectile, String powerName) { + projectile.getPersistentDataContainer().set(new NamespacedKey(MetadataHandler.PLUGIN, "detonationPower"), PersistentDataType.STRING, powerName); + } + + public static String readExplosivePower(Projectile projectile) { + return projectile.getPersistentDataContainer().get(new NamespacedKey(MetadataHandler.PLUGIN, "detonationPower"), PersistentDataType.STRING); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/combatsystem/PlayerDamagedByEliteMobHandler.java b/src/main/java/com/magmaguy/elitemobs/combatsystem/PlayerDamagedByEliteMobHandler.java new file mode 100644 index 000000000..90bffe438 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/combatsystem/PlayerDamagedByEliteMobHandler.java @@ -0,0 +1,169 @@ +package com.magmaguy.elitemobs.combatsystem; + +import com.magmaguy.elitemobs.api.PlayerDamagedByEliteMobEvent; +import com.magmaguy.elitemobs.collateralminecraftchanges.PlayerDeathMessageByEliteMob; +import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfig; +import com.magmaguy.elitemobs.items.ItemTagger; +import com.magmaguy.elitemobs.items.MobTierCalculator; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs.EliteMobProperties; +import com.magmaguy.elitemobs.playerdata.ElitePlayerInventory; +import com.magmaguy.elitemobs.powers.meta.ProjectileTagger; +import org.bukkit.Material; +import org.bukkit.attribute.Attribute; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.entity.Projectile; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.Damageable; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.concurrent.ThreadLocalRandom; + +public class PlayerDamagedByEliteMobHandler implements Listener { + + public static boolean bypass = false; + + public static double getDamageIncreasePercentage(Enchantment enchantment, ItemStack weapon) { + double maxEnchantmentLevel = EnchantmentsConfig.getEnchantment(enchantment).getMaxLevel(); + double currentEnchantmentLevel = weapon.getEnchantmentLevel(enchantment); + return currentEnchantmentLevel / maxEnchantmentLevel <= 1 ? currentEnchantmentLevel / maxEnchantmentLevel : 1; + } + + /** + * EliteMobs -> player damage handler. + * + * @param event + */ + @EventHandler(priority = EventPriority.HIGHEST) + public void eliteMobDamageHandler(PlayerDamagedByEliteMobEvent event) { + if (!event.getEliteMobEntity().isValid()) { + event.setCancelled(true); + return; + } + + if (event.getEntityDamageByEntityEvent().isCancelled()) { + if (bypass) + bypass = false; + return; + } + + //From this point on, the damage event is fully altered by Elite Mobs + + Player player = (Player) event.getEntity(); + if (ElitePlayerInventory.playerInventories.get(player.getUniqueId()) == null) return; + + if (player.isBlocking()) { + if (player.getInventory().getItemInOffHand().getType().equals(Material.SHIELD)) { + ItemMeta itemMeta = player.getInventory().getItemInOffHand().getItemMeta(); + Damageable damageable = (Damageable) itemMeta; + + if (player.getInventory().getItemInOffHand().getItemMeta().hasEnchant(Enchantment.DURABILITY)) + if (player.getInventory().getItemInOffHand().getItemMeta().getEnchantLevel(Enchantment.DURABILITY) / 20D > ThreadLocalRandom.current().nextDouble()) + damageable.setDamage(damageable.getDamage() + 5); + player.getInventory().getItemInOffHand().setItemMeta(itemMeta); + if (Material.SHIELD.getMaxDurability() < damageable.getDamage()) + player.getInventory().setItemInOffHand(null); + } + + if (event.getEntityDamageByEntityEvent().getDamager() instanceof Projectile) + event.getEntityDamageByEntityEvent().getDamager().remove(); + + return; + } + + //if the damage source is custom , the damage is final + if (bypass) { + bypass = false; + //Deal with the player getting killed + if (player.getHealth() - event.getEntityDamageByEntityEvent().getDamage() <= 0) + PlayerDeathMessageByEliteMob.addDeadPlayer(player, PlayerDeathMessageByEliteMob.initializeDeathMessage(player, event.getEliteMobEntity().getLivingEntity())); + return; + } + + //if the projectile deals custom damage + if (event.getProjectile() != null && ProjectileTagger.projectileHasCustomDamage(event.getProjectile())) { + double damage = ProjectileTagger.getProjectileCustomDamage(event.getProjectile()); + if (damage < 0) return; + //Set the final damage value + event.getEntityDamageByEntityEvent().setDamage(EntityDamageEvent.DamageModifier.BASE, damage); + + //Deal with the player getting killed + if (player.getHealth() - event.getEntityDamageByEntityEvent().getDamage() <= 0) + PlayerDeathMessageByEliteMob.addDeadPlayer(player, PlayerDeathMessageByEliteMob.initializeDeathMessage(player, event.getEliteMobEntity().getLivingEntity())); + return; + } + + //Determine tiers + double eliteTier = MobTierCalculator.findMobTier(event.getEliteMobEntity()); + double playerTier = ElitePlayerInventory.playerInventories.get(player.getUniqueId()).getArmorTier(true); + + double newDamage = eliteToPlayerDamageFormula(eliteTier, playerTier, player, event.getEliteMobEntity(), event.getEntityDamageByEntityEvent()); + + + //nullify vanilla reductions + for (EntityDamageEvent.DamageModifier modifier : EntityDamageByEntityEvent.DamageModifier.values()) + if (event.getEntityDamageByEntityEvent().isApplicable(modifier)) + event.getEntityDamageByEntityEvent().setDamage(modifier, 0); + + //Set the final damage value + event.getEntityDamageByEntityEvent().setDamage(EntityDamageEvent.DamageModifier.BASE, newDamage); + + //Deal with the player getting killed + if (player.getHealth() - event.getEntityDamageByEntityEvent().getDamage() <= 0) + PlayerDeathMessageByEliteMob.addDeadPlayer(player, PlayerDeathMessageByEliteMob.initializeDeathMessage(player, event.getEliteMobEntity().getLivingEntity())); + + } + + private double eliteToPlayerDamageFormula(double eliteTier, double playerTier, Player player, EliteEntity eliteEntity, EntityDamageByEntityEvent event) { + + /* + Note: all baseline damage gets divided by 2 because this damage level expects players to be wearing armor. + This method applies armor reduction and essentially nullifies any protection the armor gives. + This means that the baseline damage divided by 2 is the amount of damage a mob will deal to a player in a + balanced setting. + Regional bosses have normalized damage, so they use stats similar to a zombie's. Everything else uses their own + stats, which can make them vary pretty significantly in difficulty, which is pretty much intended as per Minecraft's + own system. + */ + double baseDamage = EliteMobProperties.getBaselineDamage(eliteEntity.getLivingEntity().getType(), eliteEntity) / 2D; + double bonusDamage = eliteTier; + double damageReduction = playerTier; + double secondaryDamageReduction = secondaryEnchantmentDamageReduction(player, event); + double customBossDamageMultiplier = eliteEntity.getDamageMultiplier(); + + double finalDamage = (baseDamage * customBossDamageMultiplier + bonusDamage - damageReduction - secondaryDamageReduction) * + MobCombatSettingsConfig.getDamageToPlayerMultiplier(); + + double playerMaxHealth = player.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue(); + + //Prevent 1-shots and players getting healed from hits + finalDamage = finalDamage < 1 ? 1 : finalDamage > playerMaxHealth ? playerMaxHealth - 1 : finalDamage; + + return finalDamage; + + } + + private double secondaryEnchantmentDamageReduction(Player player, EntityDamageByEntityEvent event) { + + double totalReductionLevel = 0; + + for (ItemStack itemStack : player.getInventory().getArmorContents()) { + if (itemStack == null || itemStack.getItemMeta() == null) continue; + if (event.getDamager() instanceof Projectile) + totalReductionLevel += ItemTagger.getEnchantment(itemStack.getItemMeta(), Enchantment.PROTECTION_ENVIRONMENTAL.getKey()); + } + + totalReductionLevel = totalReductionLevel / 4 / 10; + + return totalReductionLevel; + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/combatsystem/antiexploit/AmbientDamageExploit.java b/src/main/java/com/magmaguy/elitemobs/combatsystem/antiexploit/AmbientDamageExploit.java new file mode 100644 index 000000000..12e0da10c --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/combatsystem/antiexploit/AmbientDamageExploit.java @@ -0,0 +1,29 @@ +package com.magmaguy.elitemobs.combatsystem.antiexploit; + +import com.magmaguy.elitemobs.api.GenericAntiExploitEvent; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageEvent; + +public class AmbientDamageExploit implements Listener { + + @EventHandler + public void onDamage(GenericAntiExploitEvent event) { + if (event.isCancelled()) return; + if (!event.getEliteMobEntity().getLivingEntity().hasAI()) return; + if (!(event.getEntityDamageEvent().getCause().equals(EntityDamageEvent.DamageCause.HOT_FLOOR) || + event.getEntityDamageEvent().getCause().equals(EntityDamageEvent.DamageCause.CRAMMING) || + event.getEntityDamageEvent().getCause().equals(EntityDamageEvent.DamageCause.DROWNING) || + event.getEntityDamageEvent().getCause().equals(EntityDamageEvent.DamageCause.FALL) || + event.getEntityDamageEvent().getCause().equals(EntityDamageEvent.DamageCause.SUFFOCATION) || + event.getEntityDamageEvent().getCause().equals(EntityDamageEvent.DamageCause.CONTACT) || + event.getEntityDamageEvent().getCause().equals(EntityDamageEvent.DamageCause.LAVA) || + event.getEntityDamageEvent().getCause().equals(EntityDamageEvent.DamageCause.DRYOUT))) + return; + + event.getEliteMobEntity().incrementAntiExploit(1, "ambientdamageexploit"); + event.setTriggered(true); + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/combatsystem/antiexploit/AntiExploitMessage.java b/src/main/java/com/magmaguy/elitemobs/combatsystem/antiexploit/AntiExploitMessage.java new file mode 100644 index 000000000..ce76c9b79 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/combatsystem/antiexploit/AntiExploitMessage.java @@ -0,0 +1,28 @@ +package com.magmaguy.elitemobs.combatsystem.antiexploit; + +import com.magmaguy.elitemobs.config.AntiExploitConfig; +import net.md_5.bungee.api.ChatMessageType; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; + + +public class AntiExploitMessage { + + private AntiExploitMessage() { + } + + public static void sendWarning(LivingEntity livingEntity, String code) { + for (Entity entity : livingEntity.getNearbyEntities(15, 15, 15)) + if (entity instanceof Player) { + Player player = (Player) entity; + if (!player.isOp()) + player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(AntiExploitConfig.getAntiExploitMessage())); + else + player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(AntiExploitConfig.getAntiExploitMessage() + " OP-only:" + code)); + } + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/combatsystem/antiexploit/EliteMobDamagedByPlayerAntiExploitListener.java b/src/main/java/com/magmaguy/elitemobs/combatsystem/antiexploit/EliteMobDamagedByPlayerAntiExploitListener.java new file mode 100644 index 000000000..db8d3365a --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/combatsystem/antiexploit/EliteMobDamagedByPlayerAntiExploitListener.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.combatsystem.antiexploit; + +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerAntiExploitEvent; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; + +public class EliteMobDamagedByPlayerAntiExploitListener implements Listener { + @EventHandler(priority = EventPriority.MONITOR) + public void onDamage(EliteMobDamagedByPlayerAntiExploitEvent event) { + if (event.isTriggered()) return; + event.getEliteMobEntity().decrementAntiExploit(1); + event.getEliteMobEntity().setInAntiExploitCooldown(); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/combatsystem/antiexploit/HoneyBlockJumpExploit.java b/src/main/java/com/magmaguy/elitemobs/combatsystem/antiexploit/HoneyBlockJumpExploit.java new file mode 100644 index 000000000..6554f3af3 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/combatsystem/antiexploit/HoneyBlockJumpExploit.java @@ -0,0 +1,21 @@ +package com.magmaguy.elitemobs.combatsystem.antiexploit; + +import com.magmaguy.elitemobs.api.GenericAntiExploitEvent; +import com.magmaguy.elitemobs.config.AntiExploitConfig; +import com.magmaguy.elitemobs.utils.VersionChecker; +import org.bukkit.Material; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; + +public class HoneyBlockJumpExploit implements Listener { + + @EventHandler + public void onDamage(GenericAntiExploitEvent event) { + if (!AntiExploitConfig.isHoneyBlockExploit()) return; + if (VersionChecker.serverVersionOlderThan(15, 0)) return; + if (event.ground == null) return; + if (!event.ground.equals(Material.HONEY_BLOCK)) return; + event.getEliteMobEntity().incrementAntiExploit(5, "honeyexploit"); + event.setTriggered(true); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/combatsystem/antiexploit/PreventDarkroomExploit.java b/src/main/java/com/magmaguy/elitemobs/combatsystem/antiexploit/PreventDarkroomExploit.java new file mode 100644 index 000000000..a96ec515e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/combatsystem/antiexploit/PreventDarkroomExploit.java @@ -0,0 +1,55 @@ +package com.magmaguy.elitemobs.combatsystem.antiexploit; + +import com.magmaguy.elitemobs.api.GenericAntiExploitEvent; +import com.magmaguy.elitemobs.config.AntiExploitConfig; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; + +public class PreventDarkroomExploit implements Listener { + + @EventHandler + public void onDamage(GenericAntiExploitEvent event) { + + if (event.isCancelled()) return; + + //gets blocks at 1 height completely surrounding the entity + if (AntiExploitConfig.isDarkroomAntiExploit1() && !event.block021.isPassable() && + !event.block120.isPassable() && + !event.block122.isPassable() && + !event.block221.isPassable()) { + event.getEliteMobEntity().incrementAntiExploit(4, "darkroom coffin ring"); + return; + } + + //gets blocks at 0 height plus if there's a block on top + if (AntiExploitConfig.isDarkroomAntiExploit2() && + (!event.block011.isPassable() || !event.block021.isPassable()) && + (!event.block110.isPassable() || !event.block120.isPassable()) && + (!event.block112.isPassable() || !event.block122.isPassable()) && + (!event.block211.isPassable() || !event.block221.isPassable()) && + !event.ceilingMaterial.isPassable()) { + event.getEliteMobEntity().incrementAntiExploit(4, "darkroom mine"); + return; + } + + if (AntiExploitConfig.isDarkroomAntiExploit3()) + darkRoomAntiExploit3(event); + + } + + private void darkRoomAntiExploit3(GenericAntiExploitEvent event) { + int wallCount = 0; + if (!event.block011.isPassable() && !event.block021.isPassable()) + wallCount++; + if (!event.block110.isPassable() && !event.block120.isPassable()) + wallCount++; + if (!event.block112.isPassable() && !event.block122.isPassable()) + wallCount++; + if (!event.block211.isPassable() && !event.block221.isPassable()) + wallCount++; + + if (wallCount >= 3) + event.getEliteMobEntity().incrementAntiExploit(4, "darkroom walls"); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/combatsystem/antiexploit/PreventEndermanHeightExploit.java b/src/main/java/com/magmaguy/elitemobs/combatsystem/antiexploit/PreventEndermanHeightExploit.java new file mode 100644 index 000000000..0e5fea7e0 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/combatsystem/antiexploit/PreventEndermanHeightExploit.java @@ -0,0 +1,34 @@ +package com.magmaguy.elitemobs.combatsystem.antiexploit; + +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerAntiExploitEvent; +import com.magmaguy.elitemobs.config.AntiExploitConfig; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.EntityType; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.util.Vector; + +public class PreventEndermanHeightExploit implements Listener { + + @EventHandler(priority = EventPriority.HIGHEST) + public void onDamage(EliteMobDamagedByPlayerAntiExploitEvent event) { + + if (!AntiExploitConfig.isEndermanHeightAntiExploit()) return; + if (!event.getEntity().getType().equals(EntityType.ENDERMAN)) return; + + EliteEntity eliteEntity = EntityTracker.getEliteMobEntity(event.getEntity()); + if (eliteEntity == null) return; + + Block block = event.getEliteMobDamagedByPlayerEvent().getPlayer().getLocation().getBlock().getLocation().add(new Vector(0, 2, 0)).getBlock(); + if (block.getType().equals(Material.AIR) || block.getType().equals(Material.WATER)) return; + + eliteEntity.incrementAntiExploit(9, "enderman height"); + event.setTriggered(true); + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/combatsystem/antiexploit/PreventLargeDarkroomExploit.java b/src/main/java/com/magmaguy/elitemobs/combatsystem/antiexploit/PreventLargeDarkroomExploit.java new file mode 100644 index 000000000..6c8e6a546 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/combatsystem/antiexploit/PreventLargeDarkroomExploit.java @@ -0,0 +1,122 @@ +package com.magmaguy.elitemobs.combatsystem.antiexploit; + +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerAntiExploitEvent; +import com.magmaguy.elitemobs.config.AntiExploitConfig; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.utils.NonSolidBlockTypes; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.util.Vector; + +public class PreventLargeDarkroomExploit implements Listener { + + @EventHandler(priority = EventPriority.HIGHEST) + public void onEntityDamage(EliteMobDamagedByPlayerAntiExploitEvent event) { + if (event.isCancelled()) return; + antiHopper(event); + if (!event.getEliteMobEntity().getLivingEntity().getWorld().equals(event.getEliteMobDamagedByPlayerEvent().getPlayer().getWorld())) + return; + + Vector ray = event.getEliteMobDamagedByPlayerEvent().getPlayer().getLocation().clone().subtract(event.getEliteMobEntity().getLivingEntity().getLocation()).toVector(); + ray.normalize(); + boolean playerIsBelow = ray.getY() < 0; + boolean playerIsAbove = ray.getY() > 0; + ray.setY(0); + ray.multiply(0.5); + Location rayTraceLocation = event.getEliteMobEntity().getLivingEntity().getLocation().clone(); + Location eyeLevelBlockLocation, floorBlockLocation, previousFloorBlockLocation = null; + boolean isSlope = false; + + for (int i = 0; i < 35; i++) { + if (event.getEliteMobEntity().getLivingEntity().getLocation().distanceSquared(event.getEliteMobDamagedByPlayerEvent().getPlayer().getLocation()) < + event.getEliteMobEntity().getLivingEntity().getLocation().distanceSquared(rayTraceLocation)) + return; + rayTraceLocation.add(ray); + eyeLevelBlockLocation = rayTraceLocation.clone().add(new Vector(0, 1, 0)); + floorBlockLocation = rayTraceLocation.clone().subtract(new Vector(0, 1, 0)); + + if (!NonSolidBlockTypes.isPassthrough(rayTraceLocation.getBlock().getType()) || + !NonSolidBlockTypes.isPassthrough(eyeLevelBlockLocation.getBlock().getType())) { + + if (!isSlope) { + isSlope = checkSlope(rayTraceLocation.clone(), eyeLevelBlockLocation.clone(), floorBlockLocation.clone(), + event.getEliteMobDamagedByPlayerEvent().getPlayer().getLocation().getY() - event.getEntity().getLocation().getBlockY()); + if (!isSlope) + if (solidWall(rayTraceLocation, eyeLevelBlockLocation, event.getEliteMobEntity())) { + event.setTriggered(true); + return; + } + } + + if (playerIsBelow) + if (previousFloorBlockLocation != null) + if (antiShortStairs(rayTraceLocation, floorBlockLocation, previousFloorBlockLocation)) { + event.getEliteMobEntity().incrementAntiExploit(11, "largeDarkroomAntiexploit3"); + event.setTriggered(true); + return; + } + + break; + + } + + previousFloorBlockLocation = floorBlockLocation.clone(); + + //new DebugBlockLocation(rayTraceLocation); + //new DebugBlockLocation(eyeLevelBlockLocation); + //new DebugBlockLocation(floorBlockLocation); + } + + } + + private void antiHopper(EliteMobDamagedByPlayerAntiExploitEvent event) { + if (!AntiExploitConfig.isLargeDarkroomAntiExploit1()) return; + if (event.getEliteMobEntity().getLivingEntity().getLocation().clone().subtract(new Vector(0, 1, 0)).getBlock().getType().equals(Material.HOPPER) || + event.getEliteMobEntity().getLivingEntity().getLocation().clone().subtract(new Vector(0, 1, 0)).getBlock().getType().equals(Material.HOPPER)) { + event.getEliteMobEntity().incrementAntiExploit(5, "largeRoomAntiExploit1"); + event.setTriggered(true); + } + } + + /* + Looks if there's 2 solid blocks (player height) between the player and the entity + */ + private boolean solidWall(Location footLevel, Location eyeLevel, EliteEntity eliteEntity) { + if (!AntiExploitConfig.isLargeDarkroomAntiExploit2()) return false; + if (!footLevel.getBlock().isPassable() && !eyeLevel.getBlock().isPassable()) { + eliteEntity.incrementAntiExploit(3, "largeDarkroomAntiexploit2 (wall)"); + return true; + } + if (footLevel.getBlock().isPassable() && !eyeLevel.getBlock().isPassable()) { + eliteEntity.incrementAntiExploit(3, "largeDarkroomAntiexploit2 (window1)"); + return true; + } + if (!footLevel.getBlock().isPassable() && eyeLevel.getBlock().isPassable() && !eyeLevel.clone().add(new Vector(0, 1, 0)).getBlock().isPassable()) { + eliteEntity.incrementAntiExploit(3, "largeDarkroomAntiexploit2 (window2)"); + return true; + } + return false; + } + + private boolean checkSlope(Location footLevel, Location eyeLevel, Location floorBlockLocation, double heightOffset) { + //Positive height offset: player is higher + //Negative height offset: elite is higher + //Equal height offset: player and elite are on the same level + if (heightOffset == 0) + return false; + if (heightOffset > 0) + return !footLevel.getBlock().isPassable() && eyeLevel.getBlock().isPassable() && eyeLevel.clone().add(new Vector(0, 1, 0)).getBlock().isPassable(); + return floorBlockLocation.getBlock().isPassable() && footLevel.getBlock().isPassable() && eyeLevel.getBlock().isPassable(); + } + + private boolean antiShortStairs(Location footLevel, Location floorLevel, Location previousFloorLevel) { + if (!AntiExploitConfig.isLargeDarkroomAntiExploit3()) return false; + return !NonSolidBlockTypes.isPassthrough(footLevel.getBlock().getType()) || + !NonSolidBlockTypes.isPassthrough(floorLevel.getBlock().getType()) || + !NonSolidBlockTypes.isPassthrough(previousFloorLevel.getBlock().getType()); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/combatsystem/antiexploit/PreventMountExploit.java b/src/main/java/com/magmaguy/elitemobs/combatsystem/antiexploit/PreventMountExploit.java new file mode 100644 index 000000000..c33e151cf --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/combatsystem/antiexploit/PreventMountExploit.java @@ -0,0 +1,23 @@ +package com.magmaguy.elitemobs.combatsystem.antiexploit; + +import com.magmaguy.elitemobs.config.AntiExploitConfig; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.spigotmc.event.entity.EntityMountEvent; + +public class PreventMountExploit implements Listener { + + public static boolean bypass = false; + + @EventHandler + public void mountEvent(EntityMountEvent event) { + if (bypass) { + bypass = false; + return; + } + if (!AntiExploitConfig.isMountAntiExploit()) return; + if (EntityTracker.isEliteMob(event.getEntity())) event.setCancelled(true); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/combatsystem/antiexploit/PreventTowerExploit.java b/src/main/java/com/magmaguy/elitemobs/combatsystem/antiexploit/PreventTowerExploit.java new file mode 100644 index 000000000..23ffe2317 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/combatsystem/antiexploit/PreventTowerExploit.java @@ -0,0 +1,58 @@ +package com.magmaguy.elitemobs.combatsystem.antiexploit; + +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerAntiExploitEvent; +import com.magmaguy.elitemobs.config.AntiExploitConfig; +import com.magmaguy.elitemobs.utils.NonSolidBlockTypes; +import org.bukkit.Location; +import org.bukkit.block.Block; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.util.Vector; + +public class PreventTowerExploit implements Listener { + + @EventHandler + public void onHit(EliteMobDamagedByPlayerAntiExploitEvent event) { + + if (event.isCancelled()) return; + if (!event.getEliteMobEntity().getLivingEntity().hasAI()) return; + if (!AntiExploitConfig.isTowerAntiExploit()) return; + + Location mobLocation = event.getEntity().getLocation().add(new Vector(0.5, 0, 0.5)); + Location playerLocation = event.getEliteMobDamagedByPlayerEvent().getPlayer().getLocation().getBlock().getLocation().add(new Vector(0.5, 0, 0.5)); + + if (event.getEliteMobDamagedByPlayerEvent().getPlayer().hasPotionEffect(PotionEffectType.LEVITATION)) return; + if (playerLocation.getY() - mobLocation.getY() < 2) return; + + Block block1 = playerLocation.clone().add(new Vector(0, -1, 1)).getBlock(); + Block block2 = playerLocation.clone().add(new Vector(0, -1, -1)).getBlock(); + Block block3 = playerLocation.clone().add(new Vector(0, -2, 1)).getBlock(); + Block block4 = playerLocation.clone().add(new Vector(0, -2, -1)).getBlock(); + Block block5 = playerLocation.clone().add(new Vector(1, -1, 0)).getBlock(); + Block block6 = playerLocation.clone().add(new Vector(-1, -1, 0)).getBlock(); + Block block7 = playerLocation.clone().add(new Vector(1, -2, 0)).getBlock(); + Block block8 = playerLocation.clone().add(new Vector(-1, -2, 0)).getBlock(); + + if (!(NonSolidBlockTypes.isPassthrough(block1.getType()) && + NonSolidBlockTypes.isPassthrough(block2.getType()) && + NonSolidBlockTypes.isPassthrough(block3.getType()) && + NonSolidBlockTypes.isPassthrough(block4.getType()) && + NonSolidBlockTypes.isPassthrough(block5.getType()) && + NonSolidBlockTypes.isPassthrough(block6.getType()) && + NonSolidBlockTypes.isPassthrough(block7.getType()) && + NonSolidBlockTypes.isPassthrough(block8.getType()))) + return; + + //prevent triggering when the player is falling + if (!event.getEliteMobDamagedByPlayerEvent().getPlayer().isFlying() && + NonSolidBlockTypes.isPassthrough(playerLocation.clone().add(new Vector(0, -1, 0)).getBlock().getType())) { + return; + } + + event.getEliteMobEntity().incrementAntiExploit(5, "tower"); + event.setTriggered(true); + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/combattag/CombatTag.java b/src/main/java/com/magmaguy/elitemobs/combatsystem/combattag/CombatTag.java similarity index 68% rename from src/main/java/com/magmaguy/elitemobs/combattag/CombatTag.java rename to src/main/java/com/magmaguy/elitemobs/combatsystem/combattag/CombatTag.java index a1efa636d..552341ca3 100644 --- a/src/main/java/com/magmaguy/elitemobs/combattag/CombatTag.java +++ b/src/main/java/com/magmaguy/elitemobs/combatsystem/combattag/CombatTag.java @@ -1,10 +1,8 @@ -package com.magmaguy.elitemobs.combattag; +package com.magmaguy.elitemobs.combatsystem.combattag; -import com.magmaguy.elitemobs.ChatColorConverter; -import com.magmaguy.elitemobs.EntityTracker; import com.magmaguy.elitemobs.MetadataHandler; import com.magmaguy.elitemobs.config.CombatTagConfig; -import com.magmaguy.elitemobs.config.ConfigValues; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; import net.md_5.bungee.api.ChatMessageType; import net.md_5.bungee.api.chat.TextComponent; import org.bukkit.GameMode; @@ -14,10 +12,28 @@ import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; import org.bukkit.scheduler.BukkitRunnable; public class CombatTag implements Listener { + private static Player playerFinder(EntityDamageByEntityEvent event) { + + if (event.getDamager() instanceof Player && EntityTracker.isEliteMob(event.getEntity())) + return (Player) event.getDamager(); + if (event.getEntity() instanceof Player && (EntityTracker.isEliteMob(event.getEntity()) || + event.getDamager() instanceof Projectile && ((Projectile) event.getDamager()).getShooter() instanceof LivingEntity && + EntityTracker.isEliteMob(((LivingEntity) ((Projectile) event.getDamager()).getShooter())))) + return (Player) event.getEntity(); + if (event.getDamager() instanceof Projectile && ((Projectile) event.getDamager()).getShooter() instanceof Player && + EntityTracker.isEliteMob(event.getEntity())) + return (Player) ((Projectile) event.getDamager()).getShooter(); + + return null; + + } + @EventHandler public void onDamage(EntityDamageByEntityEvent event) { @@ -31,48 +47,20 @@ public void onDamage(EntityDamageByEntityEvent event) { if (player.isFlying()) { player.setFlying(false); player.spigot().sendMessage(ChatMessageType.ACTION_BAR, - TextComponent.fromLegacyText(ChatColorConverter.convert(ConfigValues.combatTagConfig.getString(CombatTagConfig.COMBAT_TAG_MESSAGE)))); + TextComponent.fromLegacyText(CombatTagConfig.getCombatTagMessage())); + player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW_FALLING, 20 * 60, 0)); new BukkitRunnable() { @Override public void run() { - //TODO: introduce the featherfall potion effect for versions above 1.12.2 -// if (NameHandler.currentVersionIsUnder(13, 0)) { if (!player.isOnline() || player.isDead()) cancel(); if (player.isOnGround()) { - player.setFallDistance(0F); cancel(); + player.removePotionEffect(PotionEffectType.SLOW); } -// } else { -////TODO: introduce the featherfall potion effect for versions above 1.12.2 -// if (!player.isOnline() || player.isDead()) -// player.removePotionEffect(PotionEffectType.SLOW); -// cancel(); -// if (player.isOnGround()) { -// player.setFallDistance(0F); -// cancel(); -// } -// -// } } }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); } } - private static Player playerFinder(EntityDamageByEntityEvent event) { - - if (event.getDamager() instanceof Player && EntityTracker.isEliteMob(event.getEntity())) - return (Player) event.getDamager(); - if (event.getEntity() instanceof Player && (EntityTracker.isEliteMob(event.getEntity()) || - event.getDamager() instanceof Projectile && ((Projectile) event.getDamager()).getShooter() instanceof LivingEntity && - EntityTracker.isEliteMob(((LivingEntity) ((Projectile) event.getDamager()).getShooter())))) - return (Player) event.getEntity(); - if (event.getDamager() instanceof Projectile && ((Projectile) event.getDamager()).getShooter() instanceof Player && - EntityTracker.isEliteMob(event.getEntity())) - return (Player) ((Projectile) event.getDamager()).getShooter(); - - return null; - - } - } diff --git a/src/main/java/com/magmaguy/elitemobs/combatsystem/displays/HealthDisplay.java b/src/main/java/com/magmaguy/elitemobs/combatsystem/displays/HealthDisplay.java new file mode 100644 index 000000000..6d1eb1a5c --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/combatsystem/displays/HealthDisplay.java @@ -0,0 +1,37 @@ +package com.magmaguy.elitemobs.combatsystem.displays; + +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerEvent; +import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; +import com.magmaguy.elitemobs.utils.DialogArmorStand; +import org.bukkit.ChatColor; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; + +public class HealthDisplay implements Listener { + + /* + Color progression: Dark green - Green - Red - Dark red + */ + private static ChatColor setHealthColor(int currentHealth, int maxHealth) { + double healthPercentage = currentHealth * 100 / maxHealth; + if (healthPercentage > 75) + return ChatColor.DARK_GREEN; + if (healthPercentage > 50) + return ChatColor.GREEN; + if (healthPercentage > 25) + return ChatColor.RED; + if (healthPercentage > 0) + return ChatColor.DARK_RED; + return ChatColor.DARK_RED; + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onHit(EliteMobDamagedByPlayerEvent event) { + if (!MobCombatSettingsConfig.isDisplayHealthOnHit()) return; + int maxHealth = (int) event.getEliteMobEntity().getMaxHealth(); + int currentHealth = (int) (event.getEliteMobEntity().getHealth() - event.getDamage()); + DialogArmorStand.createDialogArmorStand(event.getEliteMobEntity().getLivingEntity(), setHealthColor(currentHealth, maxHealth) + "" + currentHealth + "/" + maxHealth); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/combatsystem/displays/PopupDisplay.java b/src/main/java/com/magmaguy/elitemobs/combatsystem/displays/PopupDisplay.java new file mode 100644 index 000000000..462db729d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/combatsystem/displays/PopupDisplay.java @@ -0,0 +1,157 @@ +package com.magmaguy.elitemobs.combatsystem.displays; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerEvent; +import com.magmaguy.elitemobs.api.EliteMobHealEvent; +import com.magmaguy.elitemobs.api.internal.RemovalReason; +import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; +import com.magmaguy.elitemobs.config.enchantments.premade.CriticalStrikesConfig; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.items.customenchantments.CriticalStrikesEnchantment; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.utils.DialogArmorStand; +import com.magmaguy.elitemobs.utils.VisualArmorStand; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Sound; +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.inventory.ItemStack; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.EulerAngle; +import org.bukkit.util.Vector; + +import java.util.concurrent.ThreadLocalRandom; + +public class PopupDisplay implements Listener { + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onHit(EliteMobDamagedByPlayerEvent event) { + if (!MobCombatSettingsConfig.isDisplayDamageOnHit()) return; + + Location mobLocation = event.getEliteMobEntity().getLocation(); + + Vector offset = new Vector(ThreadLocalRandom.current().nextDouble(-2, 2), 0, ThreadLocalRandom.current().nextDouble(-2, 2)); + + String colorPrefix = ""; + if (event.getDamageModifier() < 1) { + //resist + colorPrefix += MobCombatSettingsConfig.getResistTextColor(); + DialogArmorStand.createDialogArmorStand(event.getEliteMobEntity().getUnsyncedLivingEntity(), + MobCombatSettingsConfig.getResistText(), offset.clone().subtract(new Vector(0, 0.2, 0))); + mobLocation.getWorld().playSound(mobLocation, Sound.BLOCK_ANVIL_USE, 1f, 1f); + if (MobCombatSettingsConfig.isDoResistEffect()) + resistArmorStandCreator(event.getEliteMobEntity(), event.getPlayer(), Material.SHIELD); + } else if (event.getDamageModifier() > 1) { + //weak + colorPrefix += MobCombatSettingsConfig.getWeakTextColor(); + DialogArmorStand.createDialogArmorStand(event.getEliteMobEntity().getUnsyncedLivingEntity(), + MobCombatSettingsConfig.getWeakText(), offset.clone().subtract(new Vector(0, 0.2, 0))); + mobLocation.getWorld().playSound(mobLocation, Sound.ENTITY_ITEM_BREAK, 1f, 1f); + if (MobCombatSettingsConfig.isDoWeakEffect()) + weakArmorStandCreator(event.getEliteMobEntity(), event.getPlayer(), Material.DIAMOND_SWORD); + } + if (event.isCriticalStrike()) { + //crit + colorPrefix += CriticalStrikesConfig.getCriticalHitColor(); + CriticalStrikesEnchantment.criticalStrikePopupMessage(event.getEliteMobEntity().getUnsyncedLivingEntity(), new Vector(0, 0.2, 0)); + } + + DialogArmorStand.createDialogArmorStand(event.getEliteMobEntity().getUnsyncedLivingEntity(), ChatColor.RED + + colorPrefix + "" + ChatColor.BOLD + "" + (int) event.getDamage() + "", offset); + + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onHit(EliteMobHealEvent event) { + if (!MobCombatSettingsConfig.isDisplayDamageOnHit()) return; + if (!event.getEliteEntity().isValid()) return; + + Vector offset = new Vector(ThreadLocalRandom.current().nextDouble(-1, 1), 0, ThreadLocalRandom.current().nextDouble(-1, 1)); + + if (event.isFullHeal()) { + DialogArmorStand.createDialogArmorStand(event.getEliteEntity().getUnsyncedLivingEntity(), + ChatColor.GREEN + "FULL HEAL!", offset.clone().subtract(new Vector(0, 0.2, 0))); + } else { + DialogArmorStand.createDialogArmorStand(event.getEliteEntity().getUnsyncedLivingEntity(), + ChatColor.GREEN + "" + event.getHealAmount() + " HP HEAL!", offset.clone().subtract(new Vector(0, 0.2, 0))); + } + + } + + private void resistArmorStandCreator(EliteEntity eliteEntity, Player player, Material material) { + if (!eliteEntity.isValid() || !player.isValid() || !eliteEntity.getLocation().getWorld().equals(player.getWorld())) + return; + + ArmorStand armorStand = VisualArmorStand.VisualArmorStand(getResistLocation(player, eliteEntity), "Resist"); + armorStand.getEquipment().setItemInMainHand(new ItemStack(material)); + armorStand.addEquipmentLock(EquipmentSlot.HAND, ArmorStand.LockType.REMOVING_OR_CHANGING); + armorStand.setRightArmPose(new EulerAngle(Math.PI / 2d, Math.PI + Math.PI / 2d, Math.PI)); + + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + if (counter > 20 || !eliteEntity.isValid() || !player.isValid() || !eliteEntity.getLocation().getWorld().equals(player.getWorld())) { + EntityTracker.unregister(armorStand, RemovalReason.EFFECT_TIMEOUT); + cancel(); + return; + } + armorStand.teleport(getResistLocation(player, eliteEntity)); + counter++; + } + }.runTaskTimer(MetadataHandler.PLUGIN, 1, 1); + } + + private Location getResistLocation(Player player, EliteEntity eliteEntity) { + Vector armorsStandVector = player.getLocation().subtract(eliteEntity.getLocation()).toVector().normalize().multiply(1.5); + Location armorStandLocation = eliteEntity.getLocation().add(armorsStandVector); + armorStandLocation.setDirection(armorsStandVector); + return armorStandLocation; + } + + private void weakArmorStandCreator(EliteEntity eliteEntity, Player player, Material material) { + if (!eliteEntity.isValid() || !player.isValid() || !eliteEntity.getLocation().getWorld().equals(player.getWorld())) + return; + + ArmorStand[] armorStands = new ArmorStand[2]; + armorStands[0] = generateWeakArmorStand(player, eliteEntity, material, -1); + armorStands[1] = generateWeakArmorStand(player, eliteEntity, material, 1); + + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + if (counter > 10 || !eliteEntity.isValid() || !player.isValid() || !eliteEntity.getLocation().getWorld().equals(player.getWorld())) { + EntityTracker.unregister(armorStands[0], RemovalReason.EFFECT_TIMEOUT); + EntityTracker.unregister(armorStands[1], RemovalReason.EFFECT_TIMEOUT); + cancel(); + return; + } + for (ArmorStand armorStand : armorStands) + armorStand.teleport(armorStand.getLocation().add(eliteEntity.getLocation().add(new Vector(0, 0, 0)) + .subtract(armorStand.getLocation()).toVector().normalize().multiply(.4))); + counter++; + } + }.runTaskTimer(MetadataHandler.PLUGIN, 1, 1); + } + + private ArmorStand generateWeakArmorStand(Player player, EliteEntity eliteEntity, Material material, int offset) { + Vector armorsStandVector = player.getLocation().clone().add(new Vector(0, 2, 0)).subtract(eliteEntity.getLocation()).toVector().normalize().multiply(3.0).rotateAroundY(Math.PI / 8 * offset); + Location armorStandLocation = eliteEntity.getLocation().add(armorsStandVector); + armorStandLocation.setDirection(armorsStandVector.multiply(-1)); + ArmorStand armorStand = VisualArmorStand.VisualArmorStand(armorStandLocation, "Weak"); + armorStand.getEquipment().setHelmet(new ItemStack(material)); + armorStand.addEquipmentLock(EquipmentSlot.HAND, ArmorStand.LockType.REMOVING_OR_CHANGING); + armorStand.setHeadPose(new EulerAngle(-Math.PI - Math.PI / 4D, Math.PI / 4D, 0)); + return armorStand; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/AdminCommands.java b/src/main/java/com/magmaguy/elitemobs/commands/AdminCommands.java new file mode 100644 index 000000000..4b18a907e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/commands/AdminCommands.java @@ -0,0 +1,791 @@ +package com.magmaguy.elitemobs.commands; + +import cloud.commandframework.ArgumentDescription; +import cloud.commandframework.Command; +import cloud.commandframework.arguments.CommandArgument; +import cloud.commandframework.arguments.standard.*; +import cloud.commandframework.bukkit.BukkitCommandManager; +import cloud.commandframework.meta.CommandMeta; +import cloud.commandframework.types.tuples.Triplet; +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.commands.admin.*; +import com.magmaguy.elitemobs.commands.quests.QuestCommand; +import com.magmaguy.elitemobs.config.ConfigurationExporter; +import com.magmaguy.elitemobs.config.DefaultConfig; +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfig; +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import com.magmaguy.elitemobs.config.customtreasurechests.CustomTreasureChestsConfig; +import com.magmaguy.elitemobs.config.npcs.NPCsConfig; +import com.magmaguy.elitemobs.dungeons.Minidungeon; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.events.TimedEvent; +import com.magmaguy.elitemobs.items.ItemTagger; +import com.magmaguy.elitemobs.items.customenchantments.SoulbindEnchantment; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import com.magmaguy.elitemobs.menus.GetLootMenu; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import com.magmaguy.elitemobs.mobconstructor.custombosses.transitiveblocks.TransitiveBlockCommand; +import com.magmaguy.elitemobs.powers.meta.ElitePower; +import com.magmaguy.elitemobs.thirdparty.discordsrv.DiscordSRVAnnouncement; +import com.magmaguy.elitemobs.utils.DebugMessage; +import com.magmaguy.elitemobs.utils.DiscordLinks; +import io.leangen.geantyref.TypeToken; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Fireball; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.List; + +public class AdminCommands { + + public AdminCommands(BukkitCommandManager manager, Command.Builder builder) { + + // /em setup + manager.command(builder.literal("setup") + .meta(CommandMeta.DESCRIPTION, "Opens the main setup menu") + .senderType(Player.class) + .permission("elitemobs.*") + .handler(commandContext -> SetupHandler.setupMenuCommand((Player) commandContext.getSender()))); + + // /em setup done + manager.command(builder.literal("setup") + .literal("done") + .meta(CommandMeta.DESCRIPTION, "Stops showing messages on admin login.") + .senderType(CommandSender.class) + .permission("elitemobs.*") + .handler(commandContext -> { + DefaultConfig.toggleSetupDone(); + if (DefaultConfig.isSetupDone()) + commandContext.getSender().sendMessage(ChatColorConverter.convert("&8[EliteMobs] &aEliteMobs" + + " will no longer send messages on login. You can do [/em setup done] again to revert this.")); + else commandContext.getSender().sendMessage(ChatColorConverter.convert("&8[EliteMobs] &aEliteMobs" + + " will once again send messages on login. You can do [/em setup done] again to revert this.")); + })); + + // /em setup minidungeon + manager.command(builder.literal("setup") + .literal("minidungeon") + .argument(StringArgument.newBuilder("minidungeonName"), ArgumentDescription.of("minidungeon name")) + .meta(CommandMeta.DESCRIPTION, "Installs a Minidungeon") + .senderType(Player.class) + .permission("elitemobs.*") + .handler(commandContext -> SetupHandler.setupMinidungeonCommand((Player) commandContext.getSender(), commandContext.get("minidungeonName")))); + + // /em setup minidungeonNoPaste + manager.command(builder.literal("setup") + .literal("minidungeonNoPaste") + .argument(StringArgument.newBuilder("minidungeonName"), ArgumentDescription.of("minidungeon name")) + .meta(CommandMeta.DESCRIPTION, "Installs a Minidungeon without pasting the WorldEdit schematic") + .senderType(Player.class) + .permission("elitemobs.*") + .handler(commandContext -> SetupHandler.setupMinidungeonNoPasteCommand((Player) commandContext.getSender(), commandContext.get("minidungeonName")))); + + // /em setup unminidungeon + manager.command(builder.literal("setup") + .literal("unminidungeon") + .argument(StringArgument.newBuilder("minidungeonName"), ArgumentDescription.of("minidungeon name")) + .meta(CommandMeta.DESCRIPTION, "Uninstalls a Minidungeon") + .senderType(Player.class) + .permission("elitemobs.*") + .handler(commandContext -> SetupHandler.setupUnminidungeonCommand((Player) commandContext.getSender(), commandContext.get("minidungeonName")))); + + // /em setup unminidungeonNoPaste + manager.command(builder.literal("setup") + .literal("unminidungeonNoPaste") + .argument(StringArgument.newBuilder("minidungeonName"), ArgumentDescription.of("minidungeon name")) + .literal("noPaste") + .meta(CommandMeta.DESCRIPTION, "Uninstalls a Minidungeon without undoing a WorldEdit paste.") + .senderType(Player.class) + .permission("elitemobs.*") + .handler(commandContext -> SetupHandler.setupUnminidungeonNoPasteCommand((Player) commandContext.getSender(), commandContext.get("minidungeonName")))); + + // /em setup area + manager.command(builder.literal("setup") + .literal("area") + .argument(StringArgument.newBuilder("areaName"), ArgumentDescription.of("WorldGuard region name")) + .meta(CommandMeta.DESCRIPTION, "Protects an area using WorldGuard, used for Minidungeons and the Adventurer's World Hub") + .senderType(Player.class) + .permission("elitemobs.*") + .handler(commandContext -> SetupHandler.setupAreaCommand((Player) commandContext.getSender(), commandContext.get("areaName")))); + + ArrayList powers = new ArrayList<>(); + for (ElitePower elitePower : ElitePower.getElitePowers()) + powers.add(elitePower.getFileName()); + powers.add("custom"); + + // /em spawnelite + manager.command(builder.literal("spawnelite") + .argument(EnumArgument.newBuilder(EntityType.class, "entityType"), + ArgumentDescription.of("Minecraft Entity Type, must be a valid type for an Elite")) + .argument(IntegerArgument.newBuilder("eliteLevel"), ArgumentDescription.of("Elite Mob level")) + .argument(StringArrayArgument.optional("powers", ((commandContext, lastString) -> powers)), + ArgumentDescription.of("List of powers")) + .meta(CommandMeta.DESCRIPTION, "Spawns an Elite based on the entity type.") + .senderType(Player.class) + .permission("elitemobs.*") + .handler(commandContext -> SpawnCommand.spawnEliteEntityTypeCommand( + (Player) commandContext.getSender(), + commandContext.get("entityType"), + commandContext.get("eliteLevel"), + commandContext.getOrDefault("powers", new String[0])))); + + // /em spawnlocationelite + manager.command(builder.literal("spawnlocationelite") + .argument(EnumArgument.newBuilder(EntityType.class, "entityType"), + ArgumentDescription.of("Minecraft Entity Type, must be a valid type for an Elite")) + .argument(StringArgument.newBuilder("worldName"), ArgumentDescription.of("Name of the world")) + .argumentTriplet("coords", + TypeToken.get(Vector.class), + Triplet.of("x", "y", "z"), + Triplet.of(Integer.class, Integer.class, Integer.class), + (sender, triplet) -> new Vector(triplet.getFirst(), triplet.getSecond(), triplet.getThird()), + ArgumentDescription.of("Coordinates")) + .argument(IntegerArgument.newBuilder("eliteLevel"), ArgumentDescription.of("Elite Mob level")) + .argument(StringArrayArgument.optional("powers", ((commandContext, lastString) -> powers)), + ArgumentDescription.of("List of powers")) + .meta(CommandMeta.DESCRIPTION, "Spawns an Elite based on the entity type and location.") + .senderType(CommandSender.class) + .permission("elitemobs.*") + .handler(commandContext -> SpawnCommand.spawnEliteEntityTypeCommand( + commandContext.getSender(), + commandContext.get("entityType"), + commandContext.get("worldName"), + commandContext.get("coords"), + commandContext.get("eliteLevel"), + commandContext.get("powers")))); + + ArrayList customBosses = new ArrayList<>(CustomBossesConfig.getCustomBosses().keySet()); + ArrayList regionalBosses = new ArrayList<>(CustomBossesConfigFields.getRegionalElites().keySet()); + + // /em spawncustom + manager.command(builder.literal("spawncustom", "spawncustomboss") + .argument(StringArgument.newBuilder("fileName").withSuggestionsProvider(((objectCommandContext, s) -> customBosses)), + ArgumentDescription.of("Custom Boss configuration file name")) + .meta(CommandMeta.DESCRIPTION, "Spawns an Elite based on the entity type.") + .senderType(Player.class) + .permission("elitemobs.*") + .handler(commandContext -> SpawnCommand.spawnCustomBossCommand( + (Player) commandContext.getSender(), + commandContext.get("fileName")))); + + // /em spawncustomlevel + manager.command(builder.literal("spawncustomlevel", "spawncustombosslevel") + .argument(StringArgument.newBuilder("fileName").withSuggestionsProvider(((objectCommandContext, s) -> customBosses)), + ArgumentDescription.of("Custom Boss configuration file name")) + .argument(IntegerArgument.newBuilder("eliteLevel"), ArgumentDescription.of("Elite Mob level")) + .meta(CommandMeta.DESCRIPTION, "Spawns a Custom Boss at a specific level.") + .senderType(Player.class) + .permission("elitemobs.*") + .handler(commandContext -> SpawnCommand.spawnCustomBossCommand( + (Player) commandContext.getSender(), + commandContext.get("fileName"), + commandContext.get("eliteLevel")))); + + // /em spawnlocationcustom + manager.command(builder.literal("spawnlocationcustom", "spawnlocationcustomboss") + .argument(StringArgument.newBuilder("fileName").withSuggestionsProvider(((objectCommandContext, s) -> customBosses)), + ArgumentDescription.of("Custom Boss configuration file name")) + .argument(StringArgument.newBuilder("worldName"), ArgumentDescription.of("Name of the world")) + .argumentTriplet("coords", + TypeToken.get(Vector.class), + Triplet.of("x", "y", "z"), + Triplet.of(Integer.class, Integer.class, Integer.class), + (sender, triplet) -> new Vector(triplet.getFirst(), triplet.getSecond(), triplet.getThird()), + ArgumentDescription.of("Coordinates")) + .meta(CommandMeta.DESCRIPTION, "Spawns an Elite based on the entity type and location.") + .senderType(CommandSender.class) + .permission("elitemobs.*") + .handler(commandContext -> SpawnCommand.spawnCustomBossCommand( + commandContext.getSender(), + commandContext.get("fileName"), + commandContext.get("worldName"), + commandContext.get("coords")))); + + // /em spawnlocationcustomlevel + manager.command(builder.literal("spawnlocationcustomlevel", "spawnlocationcustombosslevel") + .argument(StringArgument.newBuilder("fileName").withSuggestionsProvider(((objectCommandContext, s) -> customBosses)), + ArgumentDescription.of("Custom Boss configuration file name")) + .argument(IntegerArgument.newBuilder("eliteLevel"), ArgumentDescription.of("Elite Mob level")) + .argument(StringArgument.newBuilder("worldName"), ArgumentDescription.of("Name of the world")) + .argumentTriplet("coords", + TypeToken.get(Vector.class), + Triplet.of("x", "y", "z"), + Triplet.of(Integer.class, Integer.class, Integer.class), + (sender, triplet) -> new Vector(triplet.getFirst(), triplet.getSecond(), triplet.getThird()), + ArgumentDescription.of("Coordinates")) + .meta(CommandMeta.DESCRIPTION, "Spawns an Elite based on the entity type and location.") + .senderType(CommandSender.class) + .permission("elitemobs.*") + .handler(commandContext -> SpawnCommand.spawnCustomBossCommand( + commandContext.getSender(), + commandContext.get("fileName"), + commandContext.get("worldName"), + commandContext.get("coords"), + commandContext.get("eliteLevel")))); + + // /em spawnsuper + manager.command(builder.literal("spawnsuper", "spawnsupermob") + .argument(EnumArgument.newBuilder(EntityType.class, "entityType"), + ArgumentDescription.of("Minecraft Entity Type, must be a valid type for a Super Mob")) + .meta(CommandMeta.DESCRIPTION, "Spawns a Super Mob based on the entity type.") + .senderType(Player.class) + .permission("elitemobs.*") + .handler(commandContext -> SpawnCommand.spawnSuperMobCommand( + (Player) commandContext.getSender(), + commandContext.get("entityType")))); + + // /em addSpawnLocation + manager.command(builder.literal("addSpawnLocation", "asp") + .argument(StringArgument.newBuilder("fileName").withSuggestionsProvider(((objectCommandContext, s) -> regionalBosses)), + ArgumentDescription.of("Custom Boss configuration file name")) + .meta(CommandMeta.DESCRIPTION, "Adds a spawn location to a Regional Boss.") + .senderType(Player.class) + .permission("elitemobs.*") + .handler(commandContext -> CustomBossCommandHandler.addSpawnLocation( + commandContext.get("fileName"), (Player) commandContext.getSender()))); + + List treasureChestFilenames = new ArrayList<>(CustomTreasureChestsConfig.getCustomTreasureChestConfigFields().keySet()); + + // /em addTreasureChest + manager.command(builder.literal("addTreasureChest", "atc") + .argument(StringArgument.newBuilder("fileName").withSuggestionsProvider(((objectCommandContext, s) -> treasureChestFilenames)), + ArgumentDescription.of("Treasure Chest configuration file name")) + .meta(CommandMeta.DESCRIPTION, "Adds a location to a Treasure Chest.") + .senderType(Player.class) + .permission("elitemobs.*") + .handler(commandContext -> CustomTreasureChestsConfig.addTreasureChestEntry( + (Player) commandContext.getSender(), commandContext.get("fileName")))); + + ArrayList minidungeonFileNames = new ArrayList<>(Minidungeon.getMinidungeons().keySet()); + + // /em addRelativeSpawnLocation + manager.command(builder.literal("addRelativeSpawnLocation", "arsp") + .argument(StringArgument.newBuilder("bossFileName").withSuggestionsProvider(((objectCommandContext, s) -> regionalBosses)), + ArgumentDescription.of("Custom Boss configuration file name")) + .argument(StringArgument.newBuilder("minidungeonFileName").withSuggestionsProvider(((objectCommandContext, s) -> minidungeonFileNames)), + ArgumentDescription.of("Minidungeon configuration file name")) + .meta(CommandMeta.DESCRIPTION, "Adds a spawn location to a Regional Boss.") + .senderType(Player.class) + .permission("elitemobs.*") + .handler(commandContext -> CustomBossCommandHandler.addRelativeSpawnLocation( + (Player) commandContext.getSender(), commandContext.get("bossFileName"), commandContext.get("minidungeonFileName")))); + + // /em addRelativeTreasureChest + manager.command(builder.literal("addRelativeTreasureChest", "artc") + .argument(StringArgument.newBuilder("treasureChestFilename").withSuggestionsProvider(((objectCommandContext, s) -> treasureChestFilenames)), + ArgumentDescription.of("Treasure Chest configuration file name")) + .argument(StringArgument.newBuilder("minidungeonFileName").withSuggestionsProvider(((objectCommandContext, s) -> minidungeonFileNames)), + ArgumentDescription.of("Minidungeon configuration file name")) + .meta(CommandMeta.DESCRIPTION, "Adds a spawn location to a Regional Boss.") + .senderType(Player.class) + .permission("elitemobs.*") + .handler(commandContext -> TreasureChestCommands.addRelativeTreasureChest( + (Player) commandContext.getSender(), commandContext.get("treasureChestFilename"), commandContext.get("minidungeonFileName")))); + + // /em setLeashRadius + manager.command(builder.literal("setLeashRadius") + .argument(StringArgument.newBuilder("fileName").withSuggestionsProvider(((objectCommandContext, s) -> regionalBosses)), + ArgumentDescription.of("Custom Boss configuration file name")) + .argument(DoubleArgument.newBuilder("radius"), ArgumentDescription.of("Radius of the Regional Boss leash")) + .meta(CommandMeta.DESCRIPTION, "Adds a spawn location to a Regional Boss.") + .senderType(CommandSender.class) + .permission("elitemobs.*") + .handler(commandContext -> CustomBossCommandHandler.setLeashRadius( + commandContext.get("fileName"), commandContext.getSender(), commandContext.get("radius")))); + + // /em remove + manager.command(builder.literal("remove", "r") + .meta(CommandMeta.DESCRIPTION, "Permanently removes an Elite Mob entity. Elite/Regional/Super/NPCs all work.") + .senderType(Player.class) + .permission("elitemobs.*") + .handler(commandContext -> RemoveCommand.remove((Player) commandContext.getSender()))); + + + // /em debug + manager.command(builder.literal("debug", "d") + .argument(StringArgument.newBuilder("argument").withSuggestionsProvider(((objectCommandContext, s) -> { + ArrayList arrayList = new ArrayList((Collection) regionalBosses.clone()); + Bukkit.getOnlinePlayers().forEach(player -> arrayList.add(player.getName())); + return arrayList; + })), + ArgumentDescription.of("Player name or regional boss file name")) + .meta(CommandMeta.DESCRIPTION, "Opens a debug screen for players or regional bosses.") + .senderType(Player.class) + .permission("elitemobs.*") + .handler(commandContext -> DebugScreen.open((Player) commandContext.getSender(), commandContext.get("argument")))); + + ArrayList events = new ArrayList<>(); + TimedEvent.getBlueprintEvents().stream().forEach(event -> events.add(event.getCustomEventsConfigFields().getFilename())); + + // /em event + manager.command(builder.literal("event") + .argument(StringArgument.newBuilder("events").withSuggestionsProvider(((objectCommandContext, s) -> events)), + ArgumentDescription.of("Custom Boss configuration file name")) + .meta(CommandMeta.DESCRIPTION, "Opens a debug screen for players or regional bosses.") + .senderType(CommandSender.class) + .permission("elitemobs.*") + .handler(commandContext -> EventCommand.trigger(commandContext.getSender(), commandContext.get("events")))); + + ArrayList npcs = new ArrayList<>(NPCsConfig.npcEntities.keySet()); + + // /em spawnnpc + manager.command(builder.literal("spawnnpc") + .argument(StringArgument.newBuilder("npcFileName").withSuggestionsProvider(((objectCommandContext, s) -> npcs)), + ArgumentDescription.of("Custom Boss configuration file name")) + .meta(CommandMeta.DESCRIPTION, "Spawns an NPC") + .senderType(Player.class) + .permission("elitemobs.*") + .handler(commandContext -> NPCCommands.set((Player) commandContext.getSender(), commandContext.get("npcFileName")))); + + // /em stats + manager.command(builder.literal("stats") + .meta(CommandMeta.DESCRIPTION, "Gets the stats for the currently active EliteMobs entities and players.") + .senderType(CommandSender.class) + .permission("elitemobs.stats") + .handler(commandContext -> StatsCommand.statsHandler(commandContext.getSender()))); + + // /em getloot + manager.command(builder.literal("getloot") + .meta(CommandMeta.DESCRIPTION, "Opens a menu where you can get any Custom Loot") + .senderType(Player.class) + .permission("elitemobs.*") + .handler(commandContext -> new GetLootMenu((Player) commandContext.getSender()))); + + ArrayList customItems = new ArrayList<>(CustomItem.getCustomItems().keySet()); + + // /em getloot + manager.command(builder.literal("getloot") + .argument(StringArgument.newBuilder("customItem").withSuggestionsProvider(((objectCommandContext, s) -> customItems)), + ArgumentDescription.of("File name of the custom item")) + .meta(CommandMeta.DESCRIPTION, "Gets a specific custom item") + .senderType(Player.class) + .permission("elitemobs.*") + .handler(commandContext -> LootCommand.get((Player) commandContext.getSender(), commandContext.get("customItem")))); + + // /em giveloot + manager.command(builder.literal("give") + .argument(StringArgument.newBuilder("customItem").withSuggestionsProvider(((objectCommandContext, s) -> customItems)), + ArgumentDescription.of("File name of the custom item")) + .argument(StringArgument.newBuilder("player").withSuggestionsProvider(((objectCommandContext, s) -> { + ArrayList arrayList = new ArrayList<>(); + Bukkit.getOnlinePlayers().forEach(player -> arrayList.add(player.getName())); + return arrayList; + })), + ArgumentDescription.of("Name of the player that will get the custom item")) + .meta(CommandMeta.DESCRIPTION, "Gives a specific custom item to a player.") + .senderType(CommandSender.class) + .permission("elitemobs.*") + .handler(commandContext -> LootCommand.give(commandContext.getSender(), + commandContext.get("player"), + commandContext.get("customItem")))); + + // /em simloot + manager.command(builder.literal("simloot") + .argument(IntegerArgument.newBuilder("level"), + ArgumentDescription.of("Level of Elite Mob to simulate")) + .meta(CommandMeta.DESCRIPTION, "Simulates drops from an Elite Mob from the set tier") + .senderType(Player.class) + .permission("elitemobs.*") + .handler(commandContext -> SimLootCommand.run((Player) commandContext.getSender(), commandContext.get("level")))); + + // /em simloot + manager.command(builder.literal("simloot") + .argument(IntegerArgument.newBuilder("level"), + ArgumentDescription.of("Level of Elite Mob to simulate")) + .argument(IntegerArgument.newBuilder("times"), + ArgumentDescription.of("Number of times that the simulation will run")) + .meta(CommandMeta.DESCRIPTION, "Simulates drops from an Elite Mob from the set tier a set amount of times") + .senderType(Player.class) + .permission("elitemobs.*") + .handler(commandContext -> SimLootCommand.runMultipleTimes( + (Player) commandContext.getSender(), + commandContext.get("level"), + commandContext.get("times")))); + + // /em simlootother + manager.command(builder.literal("simlootother") + .argument(IntegerArgument.newBuilder("level"), + ArgumentDescription.of("Level of Elite Mob to simulate")) + .meta(CommandMeta.DESCRIPTION, "Simulates drops from an Elite Mob from the set tier") + .argument(StringArgument.newBuilder("player").withSuggestionsProvider(((objectCommandContext, s) -> { + ArrayList arrayList = new ArrayList<>(); + Bukkit.getOnlinePlayers().forEach(player -> arrayList.add(player.getName())); + return arrayList; + })), + ArgumentDescription.of("Name of the player that will get the custom item")) + .senderType(CommandSender.class) + .permission("elitemobs.*") + .handler(commandContext -> SimLootCommand.run(commandContext.getSender(), commandContext.get("level"), commandContext.get("player")))); + + // /em simlootothermultiple + manager.command(builder.literal("simlootothermultiple") + .argument(IntegerArgument.newBuilder("level"), + ArgumentDescription.of("Level of Elite Mob to simulate")) + .argument(IntegerArgument.newBuilder("times"), + ArgumentDescription.of("Number of times that the simulation will run")) + .meta(CommandMeta.DESCRIPTION, "Simulates drops from an Elite Mob from the set tier a set amount of times") + .argument(StringArgument.newBuilder("target").withSuggestionsProvider(((objectCommandContext, s) -> { + ArrayList arrayList = new ArrayList<>(); + Bukkit.getOnlinePlayers().forEach(player -> arrayList.add(player.getName())); + return arrayList; + })), + ArgumentDescription.of("Name of the player that will get the custom item")) + .senderType(CommandSender.class) + .permission("elitemobs.*") + .handler(commandContext -> SimLootCommand.runMultipleTimes( + commandContext.getSender(), + commandContext.get("level"), + commandContext.get("times"), + commandContext.get("target")))); + + // /em version + manager.command(builder.literal("version") + .meta(CommandMeta.DESCRIPTION, "Gets the version of the plugin") + .senderType(CommandSender.class) + .permission("elitemobs.version") + .handler(commandContext -> VersionCommand.getVersion(commandContext.getSender()))); + + // /em reload + manager.command(builder.literal("reload") + .meta(CommandMeta.DESCRIPTION, "Reloads the plugin. Works almost every time.") + .senderType(CommandSender.class) + .permission("elitemobs.*") + .handler(commandContext -> ReloadCommand.reload(commandContext.getSender()))); + + // /em killaggressive + manager.command(builder.literal("killaggressive") + .meta(CommandMeta.DESCRIPTION, "Kills all aggressive Elite Mobs.") + .senderType(CommandSender.class) + .permission("elitemobs.*") + .handler(commandContext -> KillHandler.killAggressiveMobs(commandContext.getSender()))); + + // /em killaggressive + manager.command(builder.literal("killaggressive") + .argument(IntegerArgument.newBuilder("radius"), + ArgumentDescription.of("Distance to kill aggressive elite mobs in")) + .meta(CommandMeta.DESCRIPTION, "Kills all aggressive Elite Mobs in a radius.") + .senderType(Player.class) + .permission("elitemobs.*") + .handler(commandContext -> KillHandler.radiusKillAggressiveMobs((Player) commandContext.getSender(), commandContext.get("radius")))); + + // /em killpassive + manager.command(builder.literal("killpassive") + .meta(CommandMeta.DESCRIPTION, "Kills all passive Super Mobs") + .senderType(CommandSender.class) + .permission("elitemobs.*") + .handler(commandContext -> KillHandler.killPassiveMobs(commandContext.getSender()))); + + // /em killpassive + manager.command(builder.literal("killpassive") + .argument(IntegerArgument.newBuilder("radius"), + ArgumentDescription.of("Distance to kill aggressive elite mobs in")) + .meta(CommandMeta.DESCRIPTION, "Kills all passive Super Mobs in a radius") + .senderType(Player.class) + .permission("elitemobs.*") + .handler(commandContext -> KillHandler.radiusKillPassiveMobs((Player) commandContext.getSender(), commandContext.get("radius")))); + + + // /em killtype + manager.command(builder.literal("killtype") + .argument(EnumArgument.newBuilder(EntityType.class, "entityType"), + ArgumentDescription.of("Minecraft Entity Type to kill")) + .meta(CommandMeta.DESCRIPTION, "Kills all elites of a specific type") + .senderType(CommandSender.class) + .permission("elitemobs.*") + .handler(commandContext -> KillHandler.killEntityType(commandContext.getSender(), commandContext.get("entityType")))); + + // /em killtype + manager.command(builder.literal("killtype") + .argument(EnumArgument.newBuilder(EntityType.class, "entityType"), + ArgumentDescription.of("Minecraft Entity Type to kill")) + .argument(IntegerArgument.newBuilder("radius"), + ArgumentDescription.of("Distance to kill aggressive elite mobs in")) + .meta(CommandMeta.DESCRIPTION, "Kills all elites of a specific type in a radius") + .senderType(Player.class) + .permission("elitemobs.*") + .handler(commandContext -> KillHandler.radiusKillSpecificMobs((Player) commandContext.getSender(), + commandContext.get("entityType"), + commandContext.get("radius")))); + + // /em gettier + manager.command(builder.literal("gettier") + .argument(IntegerArgument.newBuilder("tier"), + ArgumentDescription.of("Tier of the item to get")) + .meta(CommandMeta.DESCRIPTION, "Gets debug items for testing purposes") + .senderType(Player.class) + .permission("elitemobs.*") + .handler(commandContext -> GetTierCommand.get((Player) commandContext.getSender(), commandContext.get("tier")))); + + + CommandArgument onlinePlayers = StringArgument.newBuilder("onlinePlayer") + .withSuggestionsProvider(((objectCommandContext, s) -> { + ArrayList arrayList = new ArrayList<>(); + Bukkit.getOnlinePlayers().forEach(player -> arrayList.add(player.getName())); + return arrayList; + })).build(); + + // /em money add + manager.command(builder.literal("money") + .literal("add") + .argument(onlinePlayers.copy(), ArgumentDescription.of("Player name")) + .argument(IntegerArgument.newBuilder("amount"), ArgumentDescription.of("Amount of money to add")) + .meta(CommandMeta.DESCRIPTION, "Adds a set amount of money to a player") + .senderType(CommandSender.class) + .permission("elitemobs.*") + .handler(commandContext -> CurrencyCommandsHandler.addCommand(commandContext.getSender(), + commandContext.get("onlinePlayer"), + commandContext.get("amount")))); + + // /em money addall + manager.command(builder.literal("money") + .literal("addall") + .argument(IntegerArgument.newBuilder("amount"), ArgumentDescription.of("Amount of money to add")) + .meta(CommandMeta.DESCRIPTION, "Adds a set amount of money to all online players") + .senderType(CommandSender.class) + .permission("elitemobs.*") + .handler(commandContext -> CurrencyCommandsHandler.addAllCommand(commandContext.getSender(), + commandContext.get("amount")))); + + // /em money remove + manager.command(builder.literal("money") + .literal("remove") + .argument(onlinePlayers.copy(), ArgumentDescription.of("Player name")) + .argument(IntegerArgument.newBuilder("amount"), ArgumentDescription.of("Amount of money to add")) + .meta(CommandMeta.DESCRIPTION, "Removes a set amount of money from a player") + .senderType(CommandSender.class) + .permission("elitemobs.*") + .handler(commandContext -> CurrencyCommandsHandler.subtractCommand(commandContext.getSender(), + commandContext.get("onlinePlayer"), + commandContext.get("amount")))); + + // /em money set + manager.command(builder.literal("money") + .literal("set") + .argument(onlinePlayers.copy(), ArgumentDescription.of("Player name")) + .argument(DoubleArgument.newBuilder("amount"), ArgumentDescription.of("Amount to be set")) + .meta(CommandMeta.DESCRIPTION, "Sets the total currency amount of a player") + .senderType(CommandSender.class) + .permission("elitemobs.*") + .handler(commandContext -> CurrencyCommandsHandler.setCommand(commandContext.getSender(), + commandContext.get("onlinePlayer"), + commandContext.get("amount")))); + + // /em setrank + manager.command(builder.literal("setrank") + .argument(onlinePlayers.copy(), ArgumentDescription.of("Player name")) + .argument(IntegerArgument.newBuilder("prestigeRank"), ArgumentDescription.of("Prestige rank, 0-10")) + .argument(IntegerArgument.newBuilder("guildRank"), ArgumentDescription.of("Guild rank, 0-20")) + .meta(CommandMeta.DESCRIPTION, "Sets the guild rank of a player.") + .senderType(CommandSender.class) + .permission("elitemobs.*") + .handler(commandContext -> GuildRankCommands.setGuildRank(commandContext.getSender(), + commandContext.get("onlinePlayer"), + commandContext.get("prestigeRank"), + commandContext.get("guildRank")))); + + // /em discord + manager.command(builder.literal("discord") + .meta(CommandMeta.DESCRIPTION, "Gets the link for the support Discord server.") + .senderType(CommandSender.class) + .permission("elitemobs.*") + .handler(commandContext -> commandContext.getSender().sendMessage( + ChatColorConverter.convert("&8[EliteMobs] &6Discord room for support & downloads: &9" + DiscordLinks.mainLink)))); + + // /em discord + manager.command(builder.literal("discord") + .argument(StringArgument.newBuilder("message").greedy().build(), + ArgumentDescription.of("Message to be sent to Discord")) + .meta(CommandMeta.DESCRIPTION, "Posts a debug message on Discord if DiscordSRV is configured correctly.") + .senderType(CommandSender.class) + .permission("elitemobs.*") + .handler(commandContext -> { + new DiscordSRVAnnouncement(commandContext.get("message")); + commandContext.getSender().sendMessage(ChatColorConverter.convert("&8[EliteMobs] &aAttempted to send a message to Discord!")); + })); + + // /em forceunbind + manager.command(builder.literal("forceunbind") + .senderType(Player.class) + .permission("elitemobs.*") + .meta(CommandMeta.DESCRIPTION, "Unbinds a held soulbound item.") + .handler(commandContext -> { + ItemStack itemStack = ((Player) commandContext.getSender()).getInventory().getItemInMainHand(); + if (ItemTagger.isEliteItem(itemStack)) + SoulbindEnchantment.removeEnchantment(itemStack); + })); + + // /em relativecoords + manager.command(builder.literal("relativecoords") + .argument(StringArgument.newBuilder("minidungeonFileName").withSuggestionsProvider(((objectCommandContext, s) -> minidungeonFileNames)), + ArgumentDescription.of("Minidungeon configuration file name")) + .senderType(Player.class) + .permission("elitemobs.*") + .meta(CommandMeta.DESCRIPTION, "Gets the relative coordinated to an installed dungeon.") + .handler(commandContext -> RelativeCoordinatesCommand.get((Player) commandContext.getSender(), commandContext.get("minidungeonFileName")))); + + // /em wallet + manager.command(builder.literal("wallet") + .argument(onlinePlayers.copy(), ArgumentDescription.of("Player name")) + .senderType(CommandSender.class) + .permission("elitemobs.currency.check.others") + .meta(CommandMeta.DESCRIPTION, "Checks the currency of a specific player.") + .handler(commandContext -> CurrencyCommandsHandler.checkCommand(commandContext.getSender(), commandContext.get("onlinePlayer")))); + + // /em fireball + manager.command(builder.literal("fireball") + .senderType(Player.class) + .permission("elitemobs.*") + .meta(CommandMeta.DESCRIPTION, "Fires a test Elite Fireball for explosion protection and regeneration testing purposes.") + .handler(commandContext -> testFireball((Player) commandContext.getSender()))); + + List blockTransitionPhases = new ArrayList<>(Arrays.asList("ON_SPAWN", "ON_REMOVE")); + + // /em registerblocks + manager.command(builder.literal("registerblocks") + .senderType(Player.class) + .argument(StringArgument.newBuilder("regionalBoss").withSuggestionsProvider(((objectCommandContext, s) -> customBosses)), + ArgumentDescription.of("Regional Boss configuration file name")) + .argument(StringArgument.newBuilder("blockTransitionPhase").withSuggestionsProvider(((objectCommandContext, s) -> blockTransitionPhases)), + ArgumentDescription.of("Block transition phase")) + .permission("elitemobs.*") + .meta(CommandMeta.DESCRIPTION, "Registers transitive blocks for use by regional bosses.") + .handler(commandContext -> TransitiveBlockCommand.processCommand((Player) commandContext.getSender(), + commandContext.get("regionalBoss"), commandContext.get("blockTransitionPhase"), false))); + + // /em registerblocksedit + manager.command(builder.literal("registerblocksedit") + .senderType(Player.class) + .argument(StringArgument.newBuilder("regionalBoss").withSuggestionsProvider(((objectCommandContext, s) -> customBosses)), + ArgumentDescription.of("Regional Boss configuration file name")) + .argument(StringArgument.newBuilder("blockTransitionPhase").withSuggestionsProvider(((objectCommandContext, s) -> blockTransitionPhases)), + ArgumentDescription.of("Block transition phase")) + .permission("elitemobs.*") + .meta(CommandMeta.DESCRIPTION, "Registers transitive blocks for use by regional bosses.") + .handler(commandContext -> TransitiveBlockCommand.processCommand((Player) commandContext.getSender(), + commandContext.get("regionalBoss"), commandContext.get("blockTransitionPhase"), true))); + + // /em registerblocksarea + manager.command(builder.literal("registerblocksarea") + .senderType(Player.class) + .argument(StringArgument.newBuilder("regionalBoss").withSuggestionsProvider(((objectCommandContext, s) -> customBosses)), + ArgumentDescription.of("Regional Boss configuration file name")) + .argument(StringArgument.newBuilder("blockTransitionPhase").withSuggestionsProvider(((objectCommandContext, s) -> blockTransitionPhases)), + ArgumentDescription.of("Block transition phase")) + .permission("elitemobs.*") + .meta(CommandMeta.DESCRIPTION, "Registers large transitive blocks areas for use by regional bosses.") + .handler(commandContext -> TransitiveBlockCommand.processCommand((Player) commandContext.getSender(), + commandContext.get("regionalBoss"), commandContext.get("blockTransitionPhase"), false, true))); + + // /em registerblocksareaedit + manager.command(builder.literal("registerblocksareaedit") + .senderType(Player.class) + .argument(StringArgument.newBuilder("regionalBoss").withSuggestionsProvider(((objectCommandContext, s) -> customBosses)), + ArgumentDescription.of("Regional Boss configuration file name")) + .argument(StringArgument.newBuilder("blockTransitionPhase").withSuggestionsProvider(((objectCommandContext, s) -> blockTransitionPhases)), + ArgumentDescription.of("Block transition phase")) + .permission("elitemobs.*") + .meta(CommandMeta.DESCRIPTION, "Edits large transitive blocks areas for use by regional bosses.") + .handler(commandContext -> TransitiveBlockCommand.processCommand((Player) commandContext.getSender(), + commandContext.get("regionalBoss"), commandContext.get("blockTransitionPhase"), true, true))); + + // /em cancelblocks + manager.command(builder.literal("cancelblocks") + .senderType(Player.class) + .permission("elitemobs.*") + .meta(CommandMeta.DESCRIPTION, "Cancels transitive block registration for a player.") + .handler(commandContext -> TransitiveBlockCommand.processCommand((Player) commandContext.getSender()))); + + // /em debugmode + manager.command(builder.literal("debugmode") + .senderType(CommandSender.class) + .permission("elitemobs.*") + .meta(CommandMeta.DESCRIPTION, "Toggles debug messages off and on.") + .handler(commandContext -> DebugMessage.toggleDebugMode(commandContext.getSender()))); + + // /em trace + manager.command(builder.literal("trace") + .senderType(CommandSender.class) + .argument(StringArgument.newBuilder("uuid"), + ArgumentDescription.of("EliteMobs UUID of the Custom Boss")) + .permission("elitemobs.*") + .meta(CommandMeta.DESCRIPTION, "Traces the life of a custom boss entity. Used by the debug menu.") + .handler(commandContext -> { + for (EliteEntity eliteEntity : EntityTracker.getEliteMobEntities().values()) + if (eliteEntity.getEliteUUID().toString().equals(commandContext.get("uuid"))) + if (eliteEntity instanceof CustomBossEntity) { + ((CustomBossEntity) eliteEntity).getBossTrace().postLog((Player) commandContext.getSender()); + return; + } + })); + + // /em debugtp + manager.command(builder.literal("debugtp") + .senderType(CommandSender.class) + .argument(StringArgument.newBuilder("uuid"), + ArgumentDescription.of("EliteMobs UUID of the Custom Boss")) + .permission("elitemobs.*") + .meta(CommandMeta.DESCRIPTION, "Traces the life of a custom boss entity. Used by the debug menu.") + .handler(commandContext -> { + for (EliteEntity eliteEntity : EntityTracker.getEliteMobEntities().values()) + if (eliteEntity.getEliteUUID().toString().equals(commandContext.get("uuid"))) + if (eliteEntity instanceof CustomBossEntity) { + if (eliteEntity.getLocation() != null) + ((Player) commandContext.getSender()).teleport(eliteEntity.getLocation()); + return; + } + })); + + // /em generateresourcepack + manager.command(builder.literal("generateresourcepack") + .senderType(CommandSender.class) + .permission("elitemobs.*") + .meta(CommandMeta.DESCRIPTION, "Generates a resource pack for EliteMobs using ModelEngine") + .handler(commandContext -> ConfigurationExporter.createResourcePack(commandContext.getSender()))); + + // /em updateresourcepack + manager.command(builder.literal("updateresourcepack") + .senderType(CommandSender.class) + .permission("elitemobs.*") + .meta(CommandMeta.DESCRIPTION, "Updates the SHA1 texture pack code based on the zipped resource pack in the exports.") + .handler(commandContext -> ConfigurationExporter.overwriteSHA1(commandContext.getSender()))); + + + // /em quest reset player + manager.command(builder.literal("quest") + .literal("reset") + .argument(StringArgument.newBuilder("player").withSuggestionsProvider(((objectCommandContext, s) -> { + ArrayList arrayList = new ArrayList<>(); + Bukkit.getOnlinePlayers().forEach(player -> arrayList.add(player.getName())); + return arrayList; + }))) + .senderType(CommandSender.class) + .permission("elitemobs.*") + .meta(CommandMeta.DESCRIPTION, "Resets player quest progress.") + .handler(commandContext -> QuestCommand.resetQuests(commandContext.getSender(), commandContext.get("player")))); + + // /em quest forcecomplete + manager.command(builder.literal("quest") + .literal("forcecomplete") + .senderType(CommandSender.class) + .permission("elitemobs.*") + .meta(CommandMeta.DESCRIPTION, "Forces completion of all player quests.") + .handler(commandContext -> QuestCommand.completeQuest((Player) commandContext.getSender()))); + } + + private void testFireball(Player player) { + Fireball fireball = (Fireball) player.getWorld().spawnEntity(player.getLocation(), EntityType.FIREBALL); + fireball.setDirection(player.getLocation().getDirection().normalize()); + fireball.setShooter(player); + fireball.setYield(3F); + EntityTracker.registerProjectileEntity(fireball); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/ArenaCommands.java b/src/main/java/com/magmaguy/elitemobs/commands/ArenaCommands.java new file mode 100644 index 000000000..9a1c4cd86 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/commands/ArenaCommands.java @@ -0,0 +1,11 @@ +package com.magmaguy.elitemobs.commands; + +import com.magmaguy.elitemobs.menus.ArenaMenu; +import org.bukkit.entity.Player; + +public class ArenaCommands { + public static void openArenaMenu(Player player, String arenaFilename) { + ArenaMenu arenaMenu = new ArenaMenu(); + arenaMenu.constructArenaMenu(player, arenaFilename); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/CheckMaxItemTierCommand.java b/src/main/java/com/magmaguy/elitemobs/commands/CheckMaxItemTierCommand.java deleted file mode 100644 index faa16eb9b..000000000 --- a/src/main/java/com/magmaguy/elitemobs/commands/CheckMaxItemTierCommand.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.magmaguy.elitemobs.commands; - -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.ItemsDropSettingsConfig; -import com.magmaguy.elitemobs.config.ItemsProceduralSettingsConfig; -import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; -import org.bukkit.command.CommandSender; - -public class CheckMaxItemTierCommand { - - public static void checkMaxItemTier(CommandSender commandSender) { - - commandSender.sendMessage("The current maximum item tier is tier " + ConfigValues.itemsDropSettingsConfig.getString(ItemsDropSettingsConfig.MAXIMUM_LOOT_TIER)); - commandSender.sendMessage("The current maximum power enchantment is " + ConfigValues.itemsProceduralSettingsConfig.getString(ItemsProceduralSettingsConfig.ARROW_DAMAGE_MAX_LEVEL)); - commandSender.sendMessage("The current maximum sharpness enchantment is " + ConfigValues.itemsProceduralSettingsConfig.getString(ItemsProceduralSettingsConfig.DAMAGE_ALL_MAX_LEVEL)); - commandSender.sendMessage("The current maximum protection enchantment is " + ConfigValues.itemsProceduralSettingsConfig.getString(ItemsProceduralSettingsConfig.PROTECTION_ENVIRONMENTAL_MAX_LEVEL)); - commandSender.sendMessage("The current maximum natural mob level is " + ConfigValues.mobCombatSettingsConfig.getString(MobCombatSettingsConfig.NATURAL_ELITEMOB_LEVEL_CAP)); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/CheckTierCommand.java b/src/main/java/com/magmaguy/elitemobs/commands/CheckTierCommand.java deleted file mode 100644 index 18a6ca642..000000000 --- a/src/main/java/com/magmaguy/elitemobs/commands/CheckTierCommand.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.magmaguy.elitemobs.commands; - -import com.magmaguy.elitemobs.adventurersguild.GuildRank; -import com.magmaguy.elitemobs.items.ItemTierFinder; -import org.bukkit.entity.Player; - -public class CheckTierCommand { - - public static void checkTier(Player player) { - - double gearTier = ItemTierFinder.findPlayerTier(player); - double guildTier = (GuildRank.getGuildRank(player.getUniqueId()) - 10) * 0.2; - - player.sendMessage("Your combat tier is " + gearTier); - player.sendMessage("Your guild tier bonus is " + guildTier); - player.sendMessage("Your threat tier is " + (gearTier + guildTier)); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/CommandHandler.java b/src/main/java/com/magmaguy/elitemobs/commands/CommandHandler.java index 941813756..e00922427 100644 --- a/src/main/java/com/magmaguy/elitemobs/commands/CommandHandler.java +++ b/src/main/java/com/magmaguy/elitemobs/commands/CommandHandler.java @@ -1,349 +1,144 @@ -/* - * 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 . - */ - package com.magmaguy.elitemobs.commands; +import cloud.commandframework.Command; +import cloud.commandframework.CommandTree; +import cloud.commandframework.arguments.standard.StringArgument; +import cloud.commandframework.bukkit.BukkitCommandManager; +import cloud.commandframework.execution.CommandExecutionCoordinator; +import cloud.commandframework.meta.CommandMeta; +import cloud.commandframework.minecraft.extras.MinecraftExceptionHandler; +import cloud.commandframework.minecraft.extras.MinecraftHelp; import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.adventurersguild.AdventurersGuildGUI; -import com.magmaguy.elitemobs.commands.shops.CustomShopHandler; -import com.magmaguy.elitemobs.commands.shops.ShopHandler; -import com.magmaguy.elitemobs.config.AdventurersGuildConfig; -import com.magmaguy.elitemobs.config.ConfigValues; +import com.magmaguy.elitemobs.commands.guild.AdventurersGuildCommand; import com.magmaguy.elitemobs.config.DefaultConfig; -import org.bukkit.Bukkit; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; +import com.magmaguy.elitemobs.items.ShareItem; +import com.magmaguy.elitemobs.playerdata.statusscreen.PlayerStatusScreen; +import com.magmaguy.elitemobs.utils.WarningMessage; +import net.kyori.adventure.platform.bukkit.BukkitAudiences; +import net.kyori.adventure.text.format.NamedTextColor; import org.bukkit.command.CommandSender; -import org.bukkit.command.ConsoleCommandSender; import org.bukkit.entity.Player; +import java.lang.reflect.Method; +import java.util.function.Function; + +import static net.kyori.adventure.text.Component.text; + /** * Created by MagmaGuy on 21/01/2017. */ -public class CommandHandler implements CommandExecutor { - - private final static String STATS = "elitemobs.stats"; - private final static String GETLOOT = "elitemobs.getloot"; - private final static String SIMLOOT = "elitemobs.simloot"; - public final static String RELOAD_CONFIGS = "elitemobs.reload"; - private final static String RELOAD_LOOT = "elitemobs.reload.loot"; - private final static String GIVELOOT = "elitemobs.giveloot"; - private final static String SPAWNMOB = "elitemobs.spawnmob"; - private final static String SPAWN_BOSS_MOB = "elitemobs.spawnbossmob"; - public final static String KILLALL_AGGRESSIVEELITES = "elitemobs.killall.aggressiveelites"; - public final static String KILLALL_PASSIVEELITES = "elitemobs.killall.passiveelites"; - public final static String KILLALL_SPECIFICENTITY = "elitemobs.killall.specificentity"; - private final static String SHOP = "elitemobs.shop"; - private final static String CUSTOMSHOP = "elitemobs.customshop"; - private final static String CURRENCY_PAY = "elitemobs.currency.pay"; - private final static String CURRENCY_ADD = "elitemobs.currency.add"; - private final static String CURRENCY_SUBTRACT = "elitemobs.currency.subtract"; - private final static String CURRENCY_SET = "elitemobs.currency.set"; - private final static String CURRENCY_CHECK = "elitemobs.currency.check"; - private final static String CURRENCY_WALLET = "elitemobs.currency.wallet"; - private final static String CURRENCY_COINTOP = "elitemobs.currency.cointop"; - private final static String VERSION = "elitemobs.version"; - public final static String EVENT_LAUNCH_SMALLTREASUREGOBLIN = "elitemobs.events.smalltreasuregoblin"; - public final static String EVENT_LAUNCH_DEADMOON = "elitemobs.events.smalltreasuregoblin"; - private final static String CHECK_TIER = "elitemobs.checktier"; - private final static String SET_MAX_TIER = "elitemobs.config.setmaxtier"; - private final static String GET_TIER = "elitemobs.gettier"; - private final static String CHECK_MAX_TIER = "elitemobs.checkmaxtier"; - private final static String ADVENTURERS_GUILD = "elitemobs.adventurersguild"; - - @Override - public boolean onCommand(CommandSender commandSender, Command command, String label, String[] args) { - - switch (label) { - case "ag": - case "adventurersguild": - case "adventurerguild": - if (userPermCheck(ADVENTURERS_GUILD, commandSender) && ConfigValues.adventurersGuildConfig.getBoolean(AdventurersGuildConfig.ENABLE_ADVENTURERS_GUILD)) - AdventurersGuildGUI.mainMenu((Player) commandSender); - return true; - } - - if (args.length == 0) { - validCommands(commandSender); - return true; +public class CommandHandler { + + private BukkitCommandManager manager; + //private CommandConfirmationManager paymentConfirmationManager; + private MinecraftHelp minecraftHelp; + private BukkitAudiences bukkitAudiences; + + /* + Commands powered by Cloud + */ + + public CommandHandler() { + Function commandExecutionCoordinator = null; + try { + Class c = Class.forName("cloud.commandframework.execution.CommandExecutionCoordinator"); + Method method = c.getDeclaredMethod("simpleCoordinator"); + commandExecutionCoordinator = (Function) method.invoke(Function.class); + } catch (Exception e) { + e.printStackTrace(); } - - args[0] = args[0].toLowerCase(); - - switch (args[0]) { - case "spawn": - case "spawnmob": - if (permCheck(SPAWNMOB, commandSender)) - SpawnMobCommandHandler.spawnMob(commandSender, args); - return true; - case "ag": - case "adventurersguild": - case "adventurerguild": - if (userPermCheck(ADVENTURERS_GUILD, commandSender)) - AdventurersGuildGUI.mainMenu((Player) commandSender); - return true; - case "stats": - if (permCheck(STATS, commandSender)) - StatsCommandHandler.statsHandler(commandSender); - return true; - case "getloot": - case "gl": - if (userPermCheck(GETLOOT, commandSender) && args.length == 1) { - LootGUI lootGUI = new LootGUI(); - lootGUI.lootGUI((Player) commandSender); - } else { - if (GetLootCommandHandler.getLoot(((Player) commandSender), args[1])) - return true; - else - ((Player) commandSender).sendTitle("", "Could not find that item name."); - } - return true; - case "shop": - case "store": - if (userPermCheck(SHOP, commandSender)) { - ShopHandler shopHandler = new ShopHandler(); - shopHandler.initializeShop((Player) commandSender); - } - return true; - case "customshop": - case "cshop": - case "customstore": - case "cstore": - if (userPermCheck(CUSTOMSHOP, commandSender)) { - CustomShopHandler customShopHandler = new CustomShopHandler(); - customShopHandler.initializeShop((Player) commandSender); - } - return true; - case "wallet": - case "bal": - case "balance": - case "currency": - case "money": - case "$": - if (userPermCheck(CURRENCY_WALLET, commandSender)) - CurrencyCommandsHandler.walletCommand(commandSender, args); - return true; - case "cointop": - case "baltop": - case "cashtop": - case "currencytop": - case "$top": - if (userPermCheck(CURRENCY_COINTOP, commandSender)) - CurrencyCommandsHandler.coinTop(commandSender); - return true; - case "version": - if (permCheck(VERSION, commandSender)) - VersionHandler.versionCommand(commandSender, args); - return true; - case "checktier": - case "tiercheck": - case "tier": - if (permCheck(CHECK_TIER, commandSender)) - CheckTierCommand.checkTier(((Player) commandSender)); - return true; - case "checkmaxtier": - case "maxtier": - if (permCheck(CHECK_MAX_TIER, commandSender)) - CheckMaxItemTierCommand.checkMaxItemTier(commandSender); - return true; - case "reload": - case "restart": - if (permCheck(RELOAD_CONFIGS, commandSender)) - ReloadHandler.reloadCommand(commandSender, args); - return true; - case "killall": - case "kill": - KillHandler.killCommand(commandSender, args); - return true; - case "simloot": - case "simulateloot": - case "simdrop": - case "simulatedrop": - if (userPermCheck(SIMLOOT, commandSender)) - SimLootHandler.simLoot((Player) commandSender, Integer.parseInt(args[1])); - return true; - case "check": - case "checkcurrency": - case "checkbal": - case "checkbalance": - case "check$": - if (permCheck(CURRENCY_CHECK, commandSender)) - CurrencyCommandsHandler.checkCommand(commandSender, args); - return true; - case "event": - case "launchevent": - case "startevent": - case "triggerevent": - TriggerEventHandler.triggerEventCommand(commandSender, args); - return true; - case "spawnbossmob": - case "spawnboss": - if (userPermCheck(SPAWNMOB, commandSender)) - SpawnMobCommandHandler.spawnBossMob((Player) commandSender, args); - return true; - case "gettier": - case "spawntier": - if (userPermCheck(GET_TIER, commandSender)) - TierSetSpawner.spawnTierItem(Integer.parseInt(args[1]), (Player) commandSender); - return true; - case "setmaxtier": - if (permCheck(SET_MAX_TIER, commandSender)) - SetMaxItemTierCommand.setMaxItemTier(Double.parseDouble(args[1]), commandSender); - return true; - case "giveloot": - if (permCheck(GIVELOOT, commandSender)) - GiveLootHandler.giveLootCommand(commandSender, args); - return true; - case "pay": - if (userPermCheck(CURRENCY_PAY, commandSender)) - CurrencyCommandsHandler.payCommand((Player) commandSender, args); - return true; - case "add": - if (permCheck(CURRENCY_ADD, commandSender)) - CurrencyCommandsHandler.addCommand(commandSender, args); - return true; - case ("subtract"): - if (permCheck(CURRENCY_SUBTRACT, commandSender)) - CurrencyCommandsHandler.subtractCommand(commandSender, args); - return true; - case ("set"): - if (permCheck(CURRENCY_SET, commandSender)) - CurrencyCommandsHandler.setCommand(commandSender, args); - return true; - default: - validCommands(commandSender); - return true; - + try { + manager = new BukkitCommandManager( + /* Owning plugin */ MetadataHandler.PLUGIN, + /* Coordinator function */ commandExecutionCoordinator, + /* Command Sender -> C */ Function.identity(), + /* C -> Command Sender */ Function.identity() + ); + } catch (final Exception e) { + new WarningMessage("Failed to initialize the command manager"); + /* Disable the plugin */ + MetadataHandler.PLUGIN.getServer().getPluginManager().disablePlugin(MetadataHandler.PLUGIN); + return; } + //try { + // manager.registerBrigadier(); + //} catch (final Exception e) { + // new WarningMessage("Failed to initialize Brigadier support: " + e.getMessage()); + //} + + // Create a BukkitAudiences instance (adventure) in order to use the minecraft-extras help system + bukkitAudiences = BukkitAudiences.create(MetadataHandler.PLUGIN); + + minecraftHelp = new MinecraftHelp( + "/elitemobs help", + bukkitAudiences::sender, + manager + ); + + // Override the default exception handlers + new MinecraftExceptionHandler() + .withInvalidSyntaxHandler() + .withInvalidSenderHandler() + .withNoPermissionHandler() + .withArgumentParsingHandler() + .withCommandExecutionHandler() + .withDecorator( + component -> text() + .append(text("[", NamedTextColor.DARK_GRAY)) + .append(text("Example", NamedTextColor.GOLD)) + .append(text("] ", NamedTextColor.DARK_GRAY)) + .append(component).build() + ).apply(manager, bukkitAudiences::sender); + + constructCommands(); } - public static boolean permCheck(String permission, CommandSender commandSender) { - - if (commandSender.hasPermission(permission)) return true; - - if (commandSender instanceof Player && - Bukkit.getPluginManager().getPlugin(MetadataHandler.ELITE_MOBS).getConfig().getBoolean(DefaultConfig.ENABLE_PERMISSION_TITLES)) { - - Player player = (Player) commandSender; - - player.sendTitle("I'm afraid I can't let you do that, " + player.getDisplayName() + ".", - "You need the following permission: " + permission); - - } else { - - commandSender.sendMessage("[EliteMobs] You may not run this command."); - commandSender.sendMessage("[EliteMobs] You don't have the permission " + permission); - - } - - return false; + public void constructCommands() { + + // /ag + final Command.Builder agBuilder = manager.commandBuilder("adventurersguild", "ag"); + manager.command(agBuilder.meta(CommandMeta.DESCRIPTION, "Teleports players to the Adventurers' Guild Hub") + .senderType(Player.class) + //permission is dealt inside of the command + .handler(commandContext -> { + if (DefaultConfig.isEmLeadsToStatusMenu()) + AdventurersGuildCommand.adventurersGuildCommand((Player) commandContext.getSender()); + })); + + // /shareitem + final Command.Builder shareItemBuilder = manager.commandBuilder("shareitem"); + manager.command(shareItemBuilder.meta(CommandMeta.DESCRIPTION, "Shares a held Elite item on chat.") + .senderType(Player.class) + //permission is dealt inside of the command + .permission("elitemobs.shareitem") + .handler(commandContext -> ShareItem.showOnChat((Player) commandContext.getSender()))); + + // Base command builder + final Command.Builder builder = manager.commandBuilder("elitemobs", "em"); + + manager.command(builder.literal("help") + .argument(StringArgument.optional("query", StringArgument.StringMode.GREEDY)) + .handler(context -> { + minecraftHelp.queryCommands(context.getOrDefault("query", ""), context.getSender()); + })); + + //// Create a world argument + //final CommandArgument worldArgument = WorldArgument.of("world"); + + // /em + manager.command(builder + .meta(CommandMeta.DESCRIPTION, "Opens the main player interface") + .senderType(Player.class) + .handler(commandContext -> { + if (DefaultConfig.isEmLeadsToStatusMenu()) + new PlayerStatusScreen((Player) commandContext.getSender()); + })); + + new AdminCommands(manager, builder); + new UserCommands(manager, builder); } - public static boolean userPermCheck(String permission, CommandSender commandSender) { - - if (commandSender instanceof Player) { - - return permCheck(permission, commandSender); - - } - - commandSender.sendMessage("[EliteMobs] You may not run this command."); - commandSender.sendMessage("[EliteMobs] This is a user command."); - return false; - - } - - private static void validCommands(CommandSender commandSender) { - - if (commandSender instanceof Player) { - - Player player = (Player) commandSender; - - player.sendMessage("[EliteMobs] Valid commands:"); - if (silentPermCheck(STATS, commandSender)) - player.sendMessage("/elitemobs stats"); - if (silentPermCheck(SHOP, commandSender)) - player.sendMessage("/elitemobs shop"); - if (silentPermCheck(CUSTOMSHOP, commandSender)) - player.sendMessage("/elitemobs customshop"); - if (silentPermCheck(CURRENCY_WALLET, commandSender)) - player.sendMessage("/elitemobs wallet"); - if (silentPermCheck(CURRENCY_COINTOP, commandSender)) - player.sendMessage("/elitemobs cointop"); - if (silentPermCheck(CURRENCY_PAY, commandSender)) - player.sendMessage("/elitemobs pay [username]"); - if (silentPermCheck(CURRENCY_ADD, commandSender)) - player.sendMessage("/elitemobs add [username]"); - if (silentPermCheck(CURRENCY_SUBTRACT, commandSender)) - player.sendMessage("/elitemobs subtract [username]"); - if (silentPermCheck(CURRENCY_SET, commandSender)) - player.sendMessage("/elitemobs set [username]"); - if (silentPermCheck(CURRENCY_CHECK, commandSender)) - player.sendMessage("/elitemobs check [username]"); - if (silentPermCheck(RELOAD_CONFIGS, commandSender)) - player.sendMessage("/elitemobs reload"); - if (silentPermCheck(KILLALL_AGGRESSIVEELITES, commandSender)) - player.sendMessage("/elitemobs kill aggressive"); - if (silentPermCheck(KILLALL_PASSIVEELITES, commandSender)) - player.sendMessage("/elitemobs kill passive"); - if (silentPermCheck(SIMLOOT, commandSender)) - player.sendMessage("/elitemobs simloot [mob level]"); - if (silentPermCheck(GETLOOT, commandSender)) - player.sendMessage("/elitemobs getloot [loot name (no loot name = AdventurersGuildGUI)]"); - if (silentPermCheck(GIVELOOT, commandSender)) - player.sendMessage("/elitemobs giveloot [player name] random/[loot_name_underscore_for_spaces]"); - if (silentPermCheck(SPAWNMOB, commandSender)) - player.sendMessage("/elitemobs SpawnMob [mobType] [mobLevel] [mobPower] [mobPower2(keep adding as many as you'd like)]"); - if (silentPermCheck(SPAWN_BOSS_MOB, commandSender)) - commandSender.sendMessage("/elitemobs spawnBossMob [bossName]"); - if (silentPermCheck(CHECK_TIER, commandSender)) - commandSender.sendMessage("/elitemobs checktier"); - if (silentPermCheck(CHECK_MAX_TIER, commandSender)) - commandSender.sendMessage("/elitemobs checkmaxtier"); - if (silentPermCheck(SET_MAX_TIER, commandSender)) - commandSender.sendMessage("/elitemobs setmaxtier [tier]"); - if (silentPermCheck(GET_TIER, commandSender)) - commandSender.sendMessage("/elitemobs gettier [tier]"); - - - } else if (commandSender instanceof ConsoleCommandSender) { - - commandSender.sendMessage("[EliteMobs] Command not recognized. Valid commands:"); - commandSender.sendMessage("elitemobs stats"); - commandSender.sendMessage("elitemobs reload"); - commandSender.sendMessage("elitemobs check [username]"); - commandSender.sendMessage("elitemobs set [username]"); - commandSender.sendMessage("elitemobs add [username]"); - commandSender.sendMessage("elitemobs subtract [username]"); - commandSender.sendMessage("elitemobs killall passiveelites"); - commandSender.sendMessage("elitemobs killall aggressiveelites"); - commandSender.sendMessage("elitemobs giveloot [player name] random/[loot_name_underscore_for_spaces]"); - commandSender.sendMessage("elitemobs SpawnMob [worldName] [x] [y] [z] [mobType] [mobLevel] [mobPower] [mobPower2(keep adding as many as you'd like)]"); - - } - - } - - private static boolean silentPermCheck(String permission, CommandSender commandSender) { - - return commandSender.hasPermission(permission); - - } - - } diff --git a/src/main/java/com/magmaguy/elitemobs/commands/CurrencyCommandsHandler.java b/src/main/java/com/magmaguy/elitemobs/commands/CurrencyCommandsHandler.java index 3dcb004a2..f48aaecc5 100644 --- a/src/main/java/com/magmaguy/elitemobs/commands/CurrencyCommandsHandler.java +++ b/src/main/java/com/magmaguy/elitemobs/commands/CurrencyCommandsHandler.java @@ -1,229 +1,146 @@ -/* - * 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 . - */ - package com.magmaguy.elitemobs.commands; -import com.magmaguy.elitemobs.config.ConfigValues; +import com.magmaguy.elitemobs.ChatColorConverter; import com.magmaguy.elitemobs.config.EconomySettingsConfig; +import com.magmaguy.elitemobs.config.TranslationConfig; import com.magmaguy.elitemobs.economy.EconomyHandler; -import com.magmaguy.elitemobs.economy.UUIDFilter; -import com.magmaguy.elitemobs.playerdata.PlayerData; -import org.bukkit.ChatColor; +import com.magmaguy.elitemobs.utils.Round; +import org.bukkit.Bukkit; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; -import java.util.ArrayList; -import java.util.UUID; - -import static org.bukkit.Bukkit.getServer; - /** * Created by MagmaGuy on 17/06/2017. */ public class CurrencyCommandsHandler { - public static void payCommand(String playerName, double amount) { - - if (amount > 0) - EconomyHandler.addCurrency(UUIDFilter.guessUUI(playerName), amount); - - - } - - public static void payCommand(Player commandSender, String[] args) { - - try { - - if (Double.parseDouble(args[2]) > 0 && Integer.parseInt(args[2]) <= EconomyHandler.checkCurrency(UUIDFilter.guessUUI(commandSender.getName()))) { - - payCommand(args[1], Integer.parseInt(args[2])); - subtractCommand(commandSender.getName(), Integer.parseInt(args[2])); - - commandSender.sendMessage("You have paisd " + args[2] + " " + ConfigValues.economyConfig.get("Currency name") + " to " + args[1]); - commandSender.sendMessage("You now have " + EconomyHandler.checkCurrency(UUIDFilter.guessUUI(commandSender.getName())) + " " + ConfigValues.economyConfig.get("Currency name")); - - Player recipient = getServer().getPlayer(args[1]); - recipient.sendMessage("You have received " + args[2] + " " + ConfigValues.economyConfig.get("Currency name") + " from " + commandSender.getDisplayName()); - - } else if (Double.parseDouble(args[2]) < 0) - commandSender.sendMessage("Nice try. This plugin doesn't make the same mistake as some banks have in the past."); - else - commandSender.sendMessage("You don't have enough " + ConfigValues.economyConfig.get("Currency name") + " to do that!"); - - - } catch (Exception e) { - - commandSender.sendMessage("Input not valid. Command format: /em pay [playerName] [amount]"); + public static void payCommand(Player sender, String recipientName, double amount) { + //CASE: Negative amount + if (amount <= 0) { + sender.sendMessage(ChatColorConverter.convert("&4[EliteMobs]Nice try.")); + return; } - } - - public static void addCommand(String playerName, double amount) { - - EconomyHandler.addCurrency(UUIDFilter.guessUUI(playerName), amount); - - } - - public static void addCommand(CommandSender commandSender, String[] args) { - - try { - - addCommand(args[1], Integer.parseInt(args[2])); - - commandSender.sendMessage("You have added " + args[2] + " to " + args[1]); - commandSender.sendMessage("They now have " + EconomyHandler.checkCurrency(UUIDFilter.guessUUI(commandSender.getName()))); - - } catch (Exception e) { - - commandSender.sendMessage("Input not valid. Command format: /em add [playerName] [amount]"); - + //CASE: Offline player + Player recipient = Bukkit.getPlayer(recipientName); + if (recipient == null) { + sender.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &4Player " + recipientName + " is not online and can therefore not get a payment.")); + return; } - } - - public static void subtractCommand(String playerName, double amount) { - - EconomyHandler.subtractCurrency(UUIDFilter.guessUUI(playerName), amount); - - } - - public static void subtractCommand(CommandSender commandSender, String[] args) { - - try { - - subtractCommand(args[1], Integer.parseInt(args[2])); - - commandSender.sendMessage("You have subtracted " + args[2] + " from " + args[1]); - commandSender.sendMessage("They now have " + EconomyHandler.checkCurrency(UUIDFilter.guessUUI(commandSender.getName()))); - - } catch (Exception e) { - - commandSender.sendMessage("Input not valid. Command format: /em subtract [playerName] [amount]"); - + //CASE: Insufficient funds + double senderCurrency = EconomyHandler.checkCurrency(sender.getUniqueId()); + if (senderCurrency - amount < 0) { + sender.sendMessage( + ChatColorConverter.convert( + TranslationConfig.getEconomyPaymentInsufficientCurrency() + .replace("$currency_name", EconomySettingsConfig.getCurrencyName()))); + return; } - } - - public static void setCommand(String playerName, double amount) { - - EconomyHandler.setCurrency(UUIDFilter.guessUUI(playerName), amount); - - } - - public static void setCommand(CommandSender commandSender, String[] args) { - - try { - - CurrencyCommandsHandler.setCommand(args[1], Integer.parseInt(args[2])); - commandSender.sendMessage("You set " + args[1] + "'s " + ConfigValues.economyConfig.get("Currency name") + " to " + args[2]); - - } catch (Exception e) { - - commandSender.sendMessage("Input not valid. Command format: /em set [playerName] [amount]"); - - } + double actuallyReceivedAmount = Round.twoDecimalPlaces(amount - amount * EconomySettingsConfig.getPlayerToPlayerTaxes()); + double taxes = Round.twoDecimalPlaces(amount * EconomySettingsConfig.getPlayerToPlayerTaxes()); + + //CASE: Successful payment + EconomyHandler.addCurrency(recipient.getUniqueId(), actuallyReceivedAmount); + EconomyHandler.subtractCurrency(sender.getUniqueId(), amount); + + sender.sendMessage( + ChatColorConverter.convert( + TranslationConfig.getEconomyPayMessage() + .replace("$amount_sent", amount + "") + .replace("$amount_received", actuallyReceivedAmount + "") + .replace("$taxes", taxes + "") + .replace("$currency_name", EconomySettingsConfig.getCurrencyName()) + .replace("$receiver", recipient.getDisplayName()))); + + sender.sendMessage( + ChatColorConverter.convert( + TranslationConfig.getEconomyCurrencyLeftMessage() + .replace("$amount_left", String.valueOf(EconomyHandler.checkCurrency(sender.getUniqueId()))) + .replace("$currency_name", EconomySettingsConfig.getCurrencyName()))); + + recipient.sendMessage( + ChatColorConverter.convert( + TranslationConfig.getEconomyPaymentReceivedMessage() + .replace("$amount_sent", amount + "") + .replace("$amount_received", actuallyReceivedAmount + "") + .replace("$taxes", taxes + "") + .replace("$sender", sender.getDisplayName()) + .replace("$currency_name", EconomySettingsConfig.getCurrencyName()))); + + recipient.sendMessage( + ChatColorConverter.convert( + TranslationConfig.getEconomyCurrencyLeftMessage() + .replace("$amount_left", String.valueOf(EconomyHandler.checkCurrency(recipient.getUniqueId()))) + .replace("$currency_name", EconomySettingsConfig.getCurrencyName()))); } - public static Double checkCommand(String playerName) { - - return EconomyHandler.checkCurrency(UUIDFilter.guessUUI(playerName)); - + public static void addCommand(Player player, double amount) { + EconomyHandler.addCurrency(player.getUniqueId(), amount); } - public static void checkCommand(CommandSender commandSender, String[] args) { - - try { - Double money = CurrencyCommandsHandler.checkCommand(args[1]); - commandSender.sendMessage(args[1] + " has " + money + " " + ConfigValues.economyConfig.get("Currency name")); - } catch (Exception e) { - commandSender.sendMessage("Input not valid. Command format: /em check [playerName]"); + public static void addCommand(CommandSender commandSender, String onlinePlayer, int amount) { + Player player = Bukkit.getPlayer(onlinePlayer); + if (player == null) { + commandSender.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &4Player " + onlinePlayer + " &4is not valid!")); + return; } - + addCommand(player, amount); + commandSender.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &2You have added " + amount + " to " + onlinePlayer)); + commandSender.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &2They now have " + EconomyHandler.checkCurrency(player.getUniqueId()))); } - public static Double walletCommand(String playerName) { - - return EconomyHandler.checkCurrency(UUIDFilter.guessUUI(playerName)); - + public static void addAllCommand(CommandSender commandSender, int amount) { + for (Player player : Bukkit.getOnlinePlayers()) + addCommand(player, amount); + commandSender.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &2You have added " + amount + " to all online players.")); } - public static void walletCommand(CommandSender commandSender, String[] args) { - - commandSender.sendMessage(ChatColor.GREEN + "You have " + - CurrencyCommandsHandler.walletCommand(commandSender.getName()) + " " + - ConfigValues.economyConfig.getString("Currency name")); + public static void subtractCommand(String playerName, double amount) { + EconomyHandler.subtractCurrency(Bukkit.getPlayer(playerName).getUniqueId(), amount); } - public static void coinTop(CommandSender commandSender) { - - ArrayList arrayList = new ArrayList(); - - for (UUID uuid : PlayerData.playerCurrency.keySet()) { - - if (arrayList.size() == 0) { - - arrayList.add(uuid); - - } else { - - int index = arrayList.size(); - - for (UUID inArrayUUID : arrayList) { - - double arrayEntryValue = PlayerData.playerCurrency.get(inArrayUUID); - double newValue = PlayerData.playerCurrency.get(uuid); - - if (newValue > arrayEntryValue) { - - index = arrayList.indexOf(inArrayUUID); - break; - - } - - } - - arrayList.add(index, uuid); - - } - + public static void subtractCommand(CommandSender commandSender, String onlinePlayer, int amount) { + Player player = Bukkit.getPlayer(onlinePlayer); + if (player == null) { + commandSender.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &4Player " + onlinePlayer + " &4is not valid!")); + return; } + subtractCommand(onlinePlayer, amount); + commandSender.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &2You have subtracted " + amount + " from " + onlinePlayer)); + commandSender.sendMessage(ChatColorConverter.convert("&8[EliteMobs]They now have " + EconomyHandler.checkCurrency(player.getUniqueId()))); + } - commandSender.sendMessage(ChatColor.RED + "[EliteMobs] " + ChatColor.DARK_GREEN + ConfigValues.economyConfig.get(EconomySettingsConfig.CURRENCY_NAME) + " High Score:"); - - int iterationAmount = 10; - - if (arrayList.size() < 10) { - - iterationAmount = arrayList.size(); - + public static void setCommand(CommandSender commandSender, String onlinePlayer, double amount) { + Player player = Bukkit.getPlayer(onlinePlayer); + if (player == null) { + commandSender.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &4Player " + onlinePlayer + " &4is not valid!")); + return; } + EconomyHandler.setCurrency(player.getUniqueId(), amount); + commandSender.sendMessage("You set " + onlinePlayer + "'s " + EconomySettingsConfig.getCurrencyName() + " to " + amount); + } - for (int i = 0; i < iterationAmount; i++) { - - String name = PlayerData.playerDisplayName.get(arrayList.get(i)); - double amount = PlayerData.playerCurrency.get(arrayList.get(i)); - - int place = i + 1; - - commandSender.sendMessage(ChatColor.GREEN + "#" + place + " " + ChatColor.WHITE + name + " with " + - ChatColor.DARK_GREEN + amount + " " + ChatColor.GREEN + ConfigValues.economyConfig.get(EconomySettingsConfig.CURRENCY_NAME)); + public static void checkCommand(CommandSender commandSender, String playerName) { + Player player = Bukkit.getPlayer(playerName); + if (player == null) { + commandSender.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &4Player " + playerName + " &4is not valid!")); + return; } + double money = EconomyHandler.checkCurrency(player.getUniqueId()); + commandSender.sendMessage(ChatColorConverter.convert("&8[EliteMobs]&f " + playerName + " &2has " + money + " " + EconomySettingsConfig.getCurrencyName())); + } + public static void walletCommand(Player player) { + player.sendMessage( + ChatColorConverter.convert( + TranslationConfig.getEconomyWalletCommand() + .replace("$balance", String.valueOf(EconomyHandler.checkCurrency(player.getUniqueId()))) + .replace("$currency_name", EconomySettingsConfig.getCurrencyName()))); } } diff --git a/src/main/java/com/magmaguy/elitemobs/commands/CustomBossCommandHandler.java b/src/main/java/com/magmaguy/elitemobs/commands/CustomBossCommandHandler.java new file mode 100644 index 000000000..d0ec8e9fd --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/commands/CustomBossCommandHandler.java @@ -0,0 +1,75 @@ +package com.magmaguy.elitemobs.commands; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import com.magmaguy.elitemobs.dungeons.Minidungeon; +import com.magmaguy.elitemobs.mobconstructor.custombosses.RegionalBossEntity; +import com.magmaguy.elitemobs.utils.DebugBlockLocation; +import org.bukkit.Location; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.util.Vector; + +public class CustomBossCommandHandler { + private CustomBossCommandHandler() { + } + + public static Location autoSeekSafeSpawnLocation(Location originalLocation) { + Location newLocation = new Location(originalLocation.getWorld(), + originalLocation.getBlockX() + 0.5, + originalLocation.getBlockY() + 0.5, + originalLocation.getBlockZ() + 0.5); + for (int i = 0; i < 4; i++) + if (newLocation.add(new Vector(0, i, 0)).getBlock().isPassable()) { + new DebugBlockLocation(newLocation); + return newLocation; + } + return null; + } + + public static void addSpawnLocation(String customBossConfigFieldsString, Player player) { + CustomBossesConfigFields customBossesConfigFields = CustomBossesConfigFields.getRegionalElites().get(customBossConfigFieldsString); + if (customBossesConfigFields == null) + player.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &4Failed to add spawn location! Custom Boss " + customBossConfigFieldsString + " is not valid regional boss!")); + else { + Location safeSpawnLocation = autoSeekSafeSpawnLocation(player.getLocation()); + if (safeSpawnLocation == null) + player.sendMessage("[EliteMobs] No safe spawn location found! Make sure the area is passable!"); + else { + RegionalBossEntity.createPermanentRegionalBossEntity(customBossesConfigFields, safeSpawnLocation); + } + } + } + + public static void addRelativeSpawnLocation(Player player, String customBossConfigFieldsString, String minidungeonString) { + Minidungeon minidungeon = Minidungeon.getMinidungeons().get(minidungeonString); + if (minidungeon == null) { + player.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &4Failed to add relative location! Minidungeon is not valid!")); + return; + } + CustomBossesConfigFields customBossesConfigFields = CustomBossesConfigFields.getRegionalElites().get(customBossConfigFieldsString); + if (customBossesConfigFields == null) + player.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &4Failed to add relative location! Custom boss is not valid!")); + else { + Location safeSpawnLocation = autoSeekSafeSpawnLocation(player.getLocation()); + if (safeSpawnLocation == null) + player.sendMessage("[EliteMobs] No safe spawn location found! Make sure the area is passable!"); + else + minidungeon.initializeRelativeLocationAddition(customBossesConfigFields, safeSpawnLocation); + } + } + + public static void setLeashRadius(String customBossConfigFieldsString, CommandSender commandSender, int leashRadius) { + CustomBossesConfigFields customBossesConfigFields = CustomBossesConfigFields.getRegionalElites().get(customBossConfigFieldsString); + if (customBossesConfigFields == null) { + commandSender.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &4Failed set the leash radius! Was the boss a valid regional boss?")); + return; + } + customBossesConfigFields.runtimeSetLeashRadius(leashRadius); + for (RegionalBossEntity regionalBossEntity : RegionalBossEntity.getRegionalBossEntitySet()) + if (customBossesConfigFields.getFilename().equals(regionalBossEntity.getCustomBossesConfigFields().getFilename())) + regionalBossEntity.setLeashRadius(leashRadius); + } + + +} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/DungeonCommands.java b/src/main/java/com/magmaguy/elitemobs/commands/DungeonCommands.java new file mode 100644 index 000000000..870fbc8c5 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/commands/DungeonCommands.java @@ -0,0 +1,26 @@ +package com.magmaguy.elitemobs.commands; + +import com.magmaguy.elitemobs.api.PlayerPreTeleportEvent; +import com.magmaguy.elitemobs.config.dungeonpackager.DungeonPackagerConfigFields; +import com.magmaguy.elitemobs.dungeons.Minidungeon; +import org.bukkit.Location; +import org.bukkit.entity.Player; + +public class DungeonCommands { + public static void teleport(Player player, String minidungeonName) { + Minidungeon minidungeon = Minidungeon.getMinidungeons().get(minidungeonName); + if (minidungeon != null) + if (minidungeon.getDungeonPackagerConfigFields().getDungeonLocationType().equals(DungeonPackagerConfigFields.DungeonLocationType.SCHEMATIC)) + PlayerPreTeleportEvent.teleportPlayer(player, minidungeon.getTeleportLocation()); + else + PlayerPreTeleportEvent.teleportPlayer(player, + new Location(minidungeon.getTeleportLocation().getWorld(), + minidungeon.getTeleportLocation().getX(), + minidungeon.getTeleportLocation().getY(), + minidungeon.getTeleportLocation().getZ(), + Float.parseFloat("" + minidungeon.getDungeonPackagerConfigFields().getTeleportPointPitch()), + Float.parseFloat("" + minidungeon.getDungeonPackagerConfigFields().getTeleportPointYaw()))); + else + player.sendMessage("[EliteMobs] That dungeon isn't valid!"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/GetLootCommandHandler.java b/src/main/java/com/magmaguy/elitemobs/commands/GetLootCommandHandler.java deleted file mode 100644 index f18728d51..000000000 --- a/src/main/java/com/magmaguy/elitemobs/commands/GetLootCommandHandler.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.commands; - -import com.magmaguy.elitemobs.items.uniqueitems.UniqueItemInitializer; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - -import static com.magmaguy.elitemobs.items.CustomItemConstructor.customItemList; - -/** - * Created by MagmaGuy on 01/05/2017. - */ -public class GetLootCommandHandler { - - public static boolean getLoot(Player player, String args1) { - - boolean itemExists = false; - - for (ItemStack itemStack : customItemList) - itemExists = getItem(itemStack, args1, player); - - if (itemExists) return true; - - for (ItemStack itemStack : UniqueItemInitializer.uniqueItemsList) - itemExists = getItem(itemStack, args1, player); - - if (itemExists) return true; - return false; - - } - - private static boolean getItem(ItemStack itemStack, String args1, Player player) { - - String itemRawName = itemStack.getItemMeta().getDisplayName(); - - if (itemRawName != null) { - - Bukkit.getLogger().info(itemStack.getItemMeta().getDisplayName()); - - String itemProcessedName = itemRawName.replaceAll(" ", "_").toLowerCase(); - itemProcessedName = ChatColor.stripColor(itemProcessedName); - - if (itemProcessedName.equalsIgnoreCase(args1) && player.isValid()) { - - player.getInventory().addItem(itemStack); - - return true; - - } - - } - - return false; - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/GiveLootHandler.java b/src/main/java/com/magmaguy/elitemobs/commands/GiveLootHandler.java deleted file mode 100644 index 59619128e..000000000 --- a/src/main/java/com/magmaguy/elitemobs/commands/GiveLootHandler.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.magmaguy.elitemobs.commands; - -import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - -import java.util.concurrent.ThreadLocalRandom; - -import static com.magmaguy.elitemobs.items.CustomItemConstructor.customItemList; - -public class GiveLootHandler { - - public static void giveLootCommand(CommandSender commandSender, String[] args) { - - if (Bukkit.getServer().getPlayer(args[1]) != null) { - - Player receiver = Bukkit.getServer().getPlayer(args[1]); - - if (args[2].equalsIgnoreCase("random") || args[2].equalsIgnoreCase("r")) { - - int index = ThreadLocalRandom.current().nextInt(customItemList.size()); - ItemStack itemStack = new ItemStack(customItemList.get(index)); - receiver.getInventory().addItem(itemStack); - - } else - GetLootCommandHandler.getLoot(receiver, args[2]); - - } else - commandSender.sendMessage("Can't give loot to player - player not found."); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/GuildRankCommands.java b/src/main/java/com/magmaguy/elitemobs/commands/GuildRankCommands.java new file mode 100644 index 000000000..76afff26c --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/commands/GuildRankCommands.java @@ -0,0 +1,31 @@ +package com.magmaguy.elitemobs.commands; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.adventurersguild.GuildRank; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +public class GuildRankCommands { + public static void setGuildRank(CommandSender commandSender, String playerString, int prestigeLevel, int activeLevel) { + + Player player = Bukkit.getPlayer(playerString); + if (player == null) { + commandSender.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &4The player isn't online!")); + return; + } + + if (activeLevel < 0 || activeLevel > 10 + prestigeLevel || prestigeLevel > 10 || activeLevel > 20) { + commandSender.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &4The prestige rank / guild rank combination you picked is not valid!")); + return; + } + + GuildRank.setGuildPrestigeRank(player, prestigeLevel); + GuildRank.setMaxGuildRank(player, activeLevel); + GuildRank.setActiveGuildRank(player, activeLevel); + + commandSender.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &2You set the EliteMobs rank of " + + playerString + " to " + GuildRank.getRankName(GuildRank.getGuildPrestigeRank(player), GuildRank.getActiveGuildRank(player)))); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/KillHandler.java b/src/main/java/com/magmaguy/elitemobs/commands/KillHandler.java deleted file mode 100644 index cc6fd731a..000000000 --- a/src/main/java/com/magmaguy/elitemobs/commands/KillHandler.java +++ /dev/null @@ -1,176 +0,0 @@ -package com.magmaguy.elitemobs.commands; - -import com.magmaguy.elitemobs.EliteMobs; -import com.magmaguy.elitemobs.EntityTracker; -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; -import org.bukkit.World; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; - -public class KillHandler { - - public static void killCommand(CommandSender commandSender, String[] args) { - - if (args.length < 2) - commandSender.sendMessage("[EliteMobs] Incorrect command syntax. Try /em kill aggressive/passive/mobType [radius]"); - - /* - Run with no radius search - */ - if (args.length == 2) { - if (args[1].equalsIgnoreCase("aggressive")) - killAggressiveMobs(commandSender); - else if (args[1].equalsIgnoreCase("passive")) - killPassiveMobs(commandSender); - else - killEntityType(commandSender, args); - return; - } - - /* - Run radius search - */ - if (args.length == 3) { - if (args[1].equalsIgnoreCase("aggressive")) - radiusKillAggressiveMobs(commandSender, args); - else if (args[1].equalsIgnoreCase("passive")) - radiusKillPassiveMobs(commandSender, args); - else - radiusKillSpecificMobs(commandSender, args); - } else - commandSender.sendMessage("[EliteMobs] Incorrect command syntax. Try /em kill aggressive/passive/mobType [radius]"); - - - } - - private static void killAggressiveMobs(CommandSender commandSender) { - - if (CommandHandler.permCheck(CommandHandler.KILLALL_AGGRESSIVEELITES, commandSender)) { - int counter = 0; - - for (EliteMobEntity eliteMobEntity : EntityTracker.getEliteMobs()) { - eliteMobEntity.getLivingEntity().remove(); - EntityTracker.unregisterEliteMob(eliteMobEntity); - counter++; - } - - - commandSender.sendMessage("Killed " + counter + " Elite Mobs."); - - } - - } - - private static void killPassiveMobs(CommandSender commandSender) { - - if (CommandHandler.permCheck(CommandHandler.KILLALL_PASSIVEELITES, commandSender)) { - int counter = 0; - for (World world : EliteMobs.validWorldList) - for (LivingEntity livingEntity : world.getLivingEntities()) - if (EntityTracker.isSuperMob(livingEntity)) { - livingEntity.remove(); - counter++; - } - - commandSender.sendMessage("Killed " + counter + " Elite Mobs."); - - } - } - - private static void killEntityType(CommandSender commandSender, String[] args) { - - if (CommandHandler.permCheck(CommandHandler.KILLALL_SPECIFICENTITY, commandSender)) { - - try { - EntityType entityType = EntityType.fromName(args[1].toUpperCase()); - int counter = 0; - for (World world : EliteMobs.validWorldList) - for (LivingEntity livingEntity : world.getLivingEntities()) - if (livingEntity.getType().equals(entityType) && - (EntityTracker.isEliteMob(livingEntity) || - EntityTracker.isSuperMob(livingEntity))) { - livingEntity.remove(); - counter++; - } - - commandSender.sendMessage("Killed " + counter + " Elite " + args[1] + "."); - - } catch (Exception e) { - commandSender.sendMessage("[EliteMobs] Entity type is not valid!"); - } - - } - - } - - private static void radiusKillAggressiveMobs(CommandSender commandSender, String[] args) { - - if (!CommandHandler.userPermCheck(CommandHandler.KILLALL_AGGRESSIVEELITES, commandSender)) - return; - - try { - - int counter = 0; - for (Entity entity : ((Player) commandSender).getNearbyEntities(Integer.parseInt(args[2]), Integer.parseInt(args[2]), Integer.parseInt(args[2]))) - if (EntityTracker.isEliteMob(entity)) { - entity.remove(); - counter++; - } - - commandSender.sendMessage("Killed " + counter + " Elite Mobs."); - - } catch (Exception e) { - commandSender.sendMessage("[EliteMobs] Incorrect command syntax. Try /em kill aggressive/passive/mobType [radius]"); - } - - } - - private static void radiusKillPassiveMobs(CommandSender commandSender, String[] args) { - - if (!CommandHandler.userPermCheck(CommandHandler.KILLALL_PASSIVEELITES, commandSender)) - return; - - try { - int counter = 0; - for (Entity entity : ((Player) commandSender).getNearbyEntities(Integer.parseInt(args[2]), Integer.parseInt(args[2]), Integer.parseInt(args[2]))) - if (EntityTracker.isSuperMob(entity)) { - entity.remove(); - counter++; - } - commandSender.sendMessage("Killed " + counter + " Elite Mobs."); - - } catch (Exception e) { - commandSender.sendMessage("[EliteMobs] Incorrect command syntax. Try /em kill aggressive/passive/mobType [radius]"); - } - - } - - private static void radiusKillSpecificMobs(CommandSender commandSender, String[] args) { - - if (!CommandHandler.userPermCheck(CommandHandler.KILLALL_SPECIFICENTITY, commandSender)) - return; - - try { - - EntityType entityType = EntityType.fromName(args[1].toUpperCase()); - - int counter = 0; - for (Entity entity : ((Player) commandSender).getNearbyEntities(Integer.parseInt(args[2]), Integer.parseInt(args[2]), Integer.parseInt(args[2]))) - if (entity.getType().equals(entityType) && - (EntityTracker.isEliteMob(entity) || - EntityTracker.isSuperMob(entity))) { - entity.remove(); - counter++; - } - commandSender.sendMessage("Killed " + counter + " Elite " + args[1] + "."); - - } catch (Exception e) { - commandSender.sendMessage("[EliteMobs] Incorrect command syntax. Try /em kill aggressive/passive/mobType [radius]"); - } - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/LootGUI.java b/src/main/java/com/magmaguy/elitemobs/commands/LootGUI.java deleted file mode 100644 index e43a8f8c7..000000000 --- a/src/main/java/com/magmaguy/elitemobs/commands/LootGUI.java +++ /dev/null @@ -1,267 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.commands; - -import com.magmaguy.elitemobs.items.CustomItemConstructor; -import com.magmaguy.elitemobs.items.uniqueitems.UniqueItemInitializer; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.inventory.meta.SkullMeta; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * Created by MagmaGuy on 04/05/2017. - */ -public class LootGUI implements Listener { - - private int currentHeaderPage = 1; - private int currentLootPage = 1; - private boolean filter = false; - private int filterRank = 0; - - private List lootSlots = new ArrayList<>(Arrays.asList(10, 11, 12, 13, 14, 15, 16, 19, 20, 21, 22, 23, 24, 25, 28, 29, 30, 31, - 32, 33, 34, 37, 38, 39, 40, 41, 42, 43, 46, 47, 48, 49, 50, 51, 52)); - - private String shopName = "EliteMobs Custom Loot"; - - public void lootGUI(Player player) { - - Inventory fakeChestInventory = Bukkit.createInventory(null, 54, shopName); - tierConstructor(fakeChestInventory); - headerConstructor(fakeChestInventory); - lootNavigationConstructor(fakeChestInventory); - lootConstructor(fakeChestInventory); - - player.openInventory(fakeChestInventory); - - } - - private void headerConstructor(Inventory inventory) { - - ItemStack arrowLeft = new ItemStack(Material.SKULL_ITEM, 1, (short) 3); - SkullMeta arrowLeftSkullMeta = (SkullMeta) arrowLeft.getItemMeta(); - arrowLeftSkullMeta.setOwner("MHF_ArrowLeft"); - arrowLeftSkullMeta.setDisplayName("Previous Item Ranks"); - arrowLeft.setItemMeta(arrowLeftSkullMeta); - - inventory.setItem(0, arrowLeft); - - - ItemStack arrowRight = new ItemStack(Material.SKULL_ITEM, 1, (short) 3); - SkullMeta arrowRightSkullMeta = (SkullMeta) arrowRight.getItemMeta(); - arrowRightSkullMeta.setOwner("MHF_ArrowRight"); - arrowRightSkullMeta.setDisplayName("Next Item Ranks"); - arrowRight.setItemMeta(arrowRightSkullMeta); - - inventory.setItem(8, arrowRight); - - - ItemStack signature = new ItemStack(Material.SKULL_ITEM, 1, (short) 3); - SkullMeta signatureSkullMeta = (SkullMeta) signature.getItemMeta(); - signatureSkullMeta.setOwner("magmaguy"); - signatureSkullMeta.setDisplayName("EliteMobs by MagmaGuy"); - List signatureList = new ArrayList<>(); - signatureList.add("Support the plugins you enjoy!"); - signatureSkullMeta.setLore(signatureList); - signature.setItemMeta(signatureSkullMeta); - - inventory.setItem(4, signature); - - } - - private void tierConstructor(Inventory inventory) { - - List tierSlots = new ArrayList<>(); - - tierSlots.add(1); - tierSlots.add(2); - tierSlots.add(3); - tierSlots.add(5); - tierSlots.add(6); - tierSlots.add(7); - - List keySet = new ArrayList<>(CustomItemConstructor.dynamicRankedItemStacks.keySet()); - - int counter = 1; - - for (int number : tierSlots) { - - if (keySet.size() >= counter + ((currentHeaderPage - 1) * 6)) { - - ItemStack chest = new ItemStack(Material.CHEST, 1); - ItemMeta chestItemMeta = chest.getItemMeta(); - chestItemMeta.setDisplayName("Tier " + keySet.get((counter - 1) + ((currentHeaderPage - 1) * 6))); - List lore = new ArrayList(); - lore.add("Filter by items of this rank."); - chestItemMeta.setLore(lore); - chest.setItemMeta(chestItemMeta); - - inventory.setItem(number, chest); - - } - - counter++; - - } - - } - - private void lootNavigationConstructor(Inventory inventory) { - - ItemStack arrowLeft = new ItemStack(Material.SKULL_ITEM, 1, (short) 3); - SkullMeta arrowLeftSkullMeta = (SkullMeta) arrowLeft.getItemMeta(); - arrowLeftSkullMeta.setOwner("MHF_ArrowLeft"); - arrowLeftSkullMeta.setDisplayName("Previous Loot Page"); - arrowLeft.setItemMeta(arrowLeftSkullMeta); - - inventory.setItem(27, arrowLeft); - - - ItemStack arrowRight = new ItemStack(Material.SKULL_ITEM, 1, (short) 3); - SkullMeta arrowRightSkullMeta = (SkullMeta) arrowRight.getItemMeta(); - arrowRightSkullMeta.setOwner("MHF_ArrowRight"); - arrowRightSkullMeta.setDisplayName("Next Loot Page"); - arrowRight.setItemMeta(arrowRightSkullMeta); - - inventory.setItem(35, arrowRight); - - } - - private void lootConstructor(Inventory inventory) { - - List getLootList = new ArrayList<>(); - for (List list : CustomItemConstructor.dynamicRankedItemStacks.values()) - getLootList.addAll(list); - - getLootList.addAll(CustomItemConstructor.staticCustomItemHashMap.keySet()); - getLootList.addAll(UniqueItemInitializer.uniqueItemsList); - - int counter = 1; - - for (int number : lootSlots) { - - if (!filter) { - - if (getLootList.size() >= counter + ((currentLootPage - 1) * 35)) { - - inventory.setItem(number, getLootList.get(counter - 1 + ((currentLootPage - 1) * 35))); - - } - - } else { - - List currentRankloot = CustomItemConstructor.dynamicRankedItemStacks.get(filterRank); - - if (currentRankloot.size() >= counter + ((currentLootPage - 1) * 35)) { - - inventory.setItem(number, currentRankloot.get(counter - 1 + ((currentLootPage - 1) * 35))); - - } - - } - - counter++; - - } - - } - - @EventHandler - public void onClick(InventoryClickEvent event) { - - if (event.getInventory().getName().equalsIgnoreCase(shopName)) { - - if (event.getCurrentItem() == null || event.getCurrentItem().getType().equals(Material.AIR)) { - - event.setCancelled(true); - return; - - } - - String itemDisplayName = event.getCurrentItem().getItemMeta().getDisplayName(); - Player player = (Player) event.getWhoClicked(); - - if (itemDisplayName != null) { - - if (itemDisplayName.equals("Next Loot Page")) { - - currentLootPage++; - lootGUI(player); - - } else if (itemDisplayName.equals("Previous Loot Page")) { - - if (currentLootPage > 1) { - - currentLootPage--; - lootGUI(player); - - } - - } else if (itemDisplayName.equals("Next Item Ranks")) { - - currentHeaderPage++; - lootGUI(player); - - } else if (itemDisplayName.equals("Previous Item Ranks")) { - - if (currentHeaderPage > 1) { - - currentHeaderPage--; - lootGUI(player); - - } - - } else if (itemDisplayName.equals("EliteMobs by MagmaGuy")) { - - filter = false; - currentLootPage = 1; - lootGUI(player); - - } else if (event.getCurrentItem().getItemMeta().getLore().get(0).equals("Filter by items of this rank.")) { - - filter = true; - String[] lore = itemDisplayName.split("\\s"); - filterRank = Integer.valueOf(lore[1]); - currentLootPage = 1; - lootGUI(player); - - } - - } - - if (lootSlots.contains(event.getSlot())) { - - player.getInventory().addItem(event.getCurrentItem()); - - } - - event.setCancelled(true); - - } - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/ReloadConfigCommandHandler.java b/src/main/java/com/magmaguy/elitemobs/commands/ReloadConfigCommandHandler.java deleted file mode 100644 index af9977664..000000000 --- a/src/main/java/com/magmaguy/elitemobs/commands/ReloadConfigCommandHandler.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.commands; - -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.items.CustomItemConstructor; -import org.bukkit.Bukkit; - -/** - * Created by MagmaGuy on 13/05/2017. - */ -public class ReloadConfigCommandHandler { - - public void reloadConfiguration() { - - //Reload all configs - ConfigValues.initializeCachedConfigurations(); - - //reload config-based initialized data - CustomItemConstructor customItemConstructor = new CustomItemConstructor(); - customItemConstructor.superDropParser(); - - Bukkit.getLogger().info("EliteMobs config reloaded!"); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/ReloadHandler.java b/src/main/java/com/magmaguy/elitemobs/commands/ReloadHandler.java deleted file mode 100644 index 77d208483..000000000 --- a/src/main/java/com/magmaguy/elitemobs/commands/ReloadHandler.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.magmaguy.elitemobs.commands; - -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.items.CustomItemConstructor; -import com.magmaguy.elitemobs.items.uniqueitems.UniqueItemInitializer; -import org.bukkit.command.CommandSender; - -public class ReloadHandler { - - public static void reloadCommand(CommandSender commandSender, String[] args) { - - ConfigValues.initializeCachedConfigurations(); - CustomItemConstructor.customItemList.clear(); - CustomItemConstructor.staticCustomItemHashMap.clear(); - CustomItemConstructor.dynamicRankedItemStacks.clear(); - UniqueItemInitializer.uniqueItemsList.clear(); - CustomItemConstructor customItemConstructor = new CustomItemConstructor(); - customItemConstructor.superDropParser(); -// UniqueItemConstructor uniqueItemConstructor = new UniqueItemConstructor(); -// uniqueItemConstructor.intializeUniqueItems(); - UniqueItemInitializer.initialize(); - commandSender.sendMessage("EliteMobs reloaded!"); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/SetMaxItemTierCommand.java b/src/main/java/com/magmaguy/elitemobs/commands/SetMaxItemTierCommand.java deleted file mode 100644 index 9d84fdb8c..000000000 --- a/src/main/java/com/magmaguy/elitemobs/commands/SetMaxItemTierCommand.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.magmaguy.elitemobs.commands; - -import com.magmaguy.elitemobs.ChatColorConverter; -import com.magmaguy.elitemobs.config.*; -import org.bukkit.command.CommandSender; -import org.bukkit.configuration.Configuration; - -public class SetMaxItemTierCommand { - - public static void setMaxItemTier(double tier, CommandSender commandSender) { - - CustomConfigLoader customConfigLoader = new CustomConfigLoader(); - Configuration itemsDropSettingsConfig = customConfigLoader.getCustomConfig(ItemsDropSettingsConfig.CONFIG_NAME); - - itemsDropSettingsConfig.set(ItemsDropSettingsConfig.MAXIMUM_LOOT_TIER, tier); - customConfigLoader.saveCustomConfig(ItemsDropSettingsConfig.CONFIG_NAME); - - CustomConfigLoader customConfigLoader1 = new CustomConfigLoader(); - Configuration itemsProceduralSettingsConfig = customConfigLoader1.getCustomConfig(ItemsProceduralSettingsConfig.CONFIG_NAME); - - itemsProceduralSettingsConfig.set(ItemsProceduralSettingsConfig.ARROW_DAMAGE_MAX_LEVEL, tier-1); - itemsProceduralSettingsConfig.set(ItemsProceduralSettingsConfig.DAMAGE_ALL_MAX_LEVEL, tier-1); - itemsProceduralSettingsConfig.set(ItemsProceduralSettingsConfig.PROTECTION_ENVIRONMENTAL_MAX_LEVEL, tier-1); - customConfigLoader1.saveCustomConfig(ItemsProceduralSettingsConfig.CONFIG_NAME); - - - int maxMobLevel = (int) (tier * ConfigValues.mobCombatSettingsConfig.getDouble(MobCombatSettingsConfig.PER_TIER_LEVEL_INCREASE) * 10); - - CustomConfigLoader customConfigLoader2 = new CustomConfigLoader(); - Configuration mobCombatSettingsConfig = customConfigLoader2.getCustomConfig(MobCombatSettingsConfig.CONFIG_NAME); - mobCombatSettingsConfig.set(MobCombatSettingsConfig.NATURAL_ELITEMOB_LEVEL_CAP, maxMobLevel); - customConfigLoader2.saveCustomConfig(MobCombatSettingsConfig.CONFIG_NAME); - - ConfigValues.initializeCachedConfigurations(); - - commandSender.sendMessage(ChatColorConverter.convert( - "Warning: You have set the max tier to " + tier + "!")); - commandSender.sendMessage(ChatColorConverter.convert( - "The max protection enchantment has been increased to " + (tier - 1))); - commandSender.sendMessage(ChatColorConverter.convert( - "The max sharpness enchantment has been increased to " + (tier- 1))); - commandSender.sendMessage(ChatColorConverter.convert( - "The max power enchantment has been increased to " + (tier - 1))); - commandSender.sendMessage(ChatColorConverter.convert( - "The max mob level has been increased to " + maxMobLevel)); - commandSender.sendMessage(ChatColorConverter.convert( - "You can run this command again to tweak the values or change them in the ItemProceduralSettings.yml file," + - " as well as the ItemsDropSettings and the MobCombatSettings")); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/SetupHandler.java b/src/main/java/com/magmaguy/elitemobs/commands/SetupHandler.java new file mode 100644 index 000000000..a1d5f604e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/commands/SetupHandler.java @@ -0,0 +1,75 @@ +package com.magmaguy.elitemobs.commands; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.EliteMobs; +import com.magmaguy.elitemobs.commands.setup.SetupMenu; +import com.magmaguy.elitemobs.dungeons.Minidungeon; +import com.magmaguy.elitemobs.thirdparty.worldguard.WorldGuardCompatibility; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +public class SetupHandler { + + public static void setupMenuCommand(Player player) { + new SetupMenu(player); + } + + public static void setupMinidungeonCommand(Player player, String minidungeonName) { + Minidungeon minidungeon = Minidungeon.getMinidungeons().get(minidungeonName); + minidungeon.finalizeMinidungeonInstallation(player, true); + player.performCommand("/rotate " + minidungeon.getDungeonPackagerConfigFields().getRotation()); + player.performCommand("/paste"); + } + + public static void setupMinidungeonNoPasteCommand(Player player, String minidungeonName) { + Minidungeon minidungeon = Minidungeon.getMinidungeons().get(minidungeonName); + minidungeon.finalizeMinidungeonInstallation(player, false); + } + + public static void setupUnminidungeonCommand(Player player, String minidungeonName) { + Minidungeon minidungeon = Minidungeon.getMinidungeons().get(minidungeonName); + minidungeon.uninstallSchematicMinidungeon(player); + player.performCommand("/undo"); + } + + public static void setupUnminidungeonNoPasteCommand(Player player, String minidungeonName) { + Minidungeon minidungeon = Minidungeon.getMinidungeons().get(minidungeonName); + minidungeon.finalizeMinidungeonInstallation(player, false); + } + + public static void setupAreaCommand(Player player, String regionName) { + if (!EliteMobs.worldGuardIsEnabled) { + player.sendMessage("[EliteMobs] You don't have WorldGuard installed! It is not possible to correctly set " + + "up a lair/minidungeon/dungeon without that plugin!"); + return; + } + if (!WorldGuardCompatibility.protectMinidungeonArea(regionName, player.getLocation())) { + player.sendMessage(ChatColorConverter.convert("&4[EliteMobs] Failed to protect region! Was the region name correct?")); + //worldguardextraflags + if (Bukkit.getPluginManager().isPluginEnabled("WorldGuardExtraFlags")) { + commandPackage("&2", "fly", "deny", player, regionName); + } else { + player.sendMessage(ChatColor.RED + "[EliteMobs] Warning: the WorldGuardExtraFlags plugin is not present. It is recommended for the use of the anti-flight flag."); + } + + player.performCommand("rg info"); + } else + player.sendMessage(ChatColorConverter.convert("&2[EliteMobs] Set all WorldGuard flags correctly!")); + + } + + private static void commandPackage(String colorCode, String flagString, String state, Player player, String regionName) { + player.sendMessage(flagString(colorCode + flagString, player)); + player.performCommand(commandString(flagString, state, player, regionName)); + } + + private static String flagString(String flagString, Player player) { + return ChatColorConverter.convert("&a[EliteMobs] Adding flag " + flagString); + } + + private static String commandString(String flagString, String state, Player player, String regionName) { + return "region flag " + regionName + " " + flagString + " " + state; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/SimLootHandler.java b/src/main/java/com/magmaguy/elitemobs/commands/SimLootHandler.java deleted file mode 100644 index 62ae75a82..000000000 --- a/src/main/java/com/magmaguy/elitemobs/commands/SimLootHandler.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.commands; - -import org.bukkit.entity.Player; - -/** - * Created by MagmaGuy on 08/06/2017. - */ -public class SimLootHandler { - - public static void simLoot(Player player, int level) { - -// if (level < 1) -// level = 0; -// -// LootTables.generateLoot(player); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/SpawnCommand.java b/src/main/java/com/magmaguy/elitemobs/commands/SpawnCommand.java new file mode 100644 index 000000000..bec8a6a01 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/commands/SpawnCommand.java @@ -0,0 +1,178 @@ +package com.magmaguy.elitemobs.commands; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfig; +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.mobconstructor.SuperMobConstructor; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs.EliteMobProperties; +import com.magmaguy.elitemobs.mobconstructor.mobdata.passivemobs.SuperMobProperties; +import com.magmaguy.elitemobs.powers.meta.ElitePower; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.entity.CreatureSpawnEvent; +import org.bukkit.util.Vector; + +import java.util.HashSet; +import java.util.Optional; + +/** + * Created by MagmaGuy on 01/05/2017. + */ +public class SpawnCommand { + + public static void spawnEliteEntityTypeCommand(Player player, EntityType entityType, Integer level, String[] powers) { + LivingEntity livingEntity = (LivingEntity) player.getLocation().getWorld().spawnEntity(getLocation(player), entityType); + HashSet mobPowers = getPowers(powers, player); + EliteEntity eliteEntity = new EliteEntity(); + eliteEntity.setLevel(level); + eliteEntity.setLivingEntity(livingEntity, CreatureSpawnEvent.SpawnReason.CUSTOM); + if (!mobPowers.isEmpty()) eliteEntity.applyPowers(mobPowers); + else eliteEntity.randomizePowers(EliteMobProperties.getPluginData(livingEntity)); + } + + public static void spawnEliteEntityTypeCommand(CommandSender commandSender, + EntityType entityType, + String world, + Vector coords, + Integer level, + Optional powers) { + try { + Location location = new Location(Bukkit.getWorld(world), coords.getX(), coords.getY(), coords.getZ()); + spawnEliteEntityTypeCommand(commandSender, + location, + entityType, + level, + powers); + } catch (Exception e) { + commandSender.sendMessage("[EliteMobs] World argument was not valid!"); + } + } + + public static void spawnEliteEntityTypeCommand(CommandSender commandSender, + Location location, + EntityType entityType, + Integer level, + Optional powers) { + if (!EliteMobProperties.getValidMobTypes().contains(entityType)) { + commandSender.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &4Entity type " + entityType.toString() + " can't be an Elite!")); + return; + } + LivingEntity livingEntity = (LivingEntity) location.getWorld().spawnEntity(location, entityType); + HashSet mobPowers = new HashSet<>(); + if (powers.isPresent()) + mobPowers = getPowers(powers.get(), commandSender); + EliteEntity eliteEntity = new EliteEntity(); + eliteEntity.setLevel(level); + eliteEntity.setLivingEntity(livingEntity, CreatureSpawnEvent.SpawnReason.CUSTOM); + if (!mobPowers.isEmpty()) eliteEntity.applyPowers(mobPowers); + else eliteEntity.randomizePowers(EliteMobProperties.getPluginData(livingEntity)); + } + + public static void spawnCustomBossCommand(CommandSender commandSender, + String fileName, + String world, + Vector coords) { + try { + Location location = new Location(Bukkit.getWorld(world), coords.getX(), coords.getY(), coords.getZ()); + CustomBossesConfigFields customBossesConfigFields = CustomBossesConfig.getCustomBoss(fileName); + if (customBossesConfigFields == null) { + commandSender.sendMessage("Filename " + fileName + " is not valid! Make sure you are writing the name of a configuration file in the custombosses folder!"); + return; + } + CustomBossEntity customBossEntity = new CustomBossEntity(customBossesConfigFields); + customBossEntity.setSpawnLocation(location); + customBossEntity.spawn(false); + } catch (Exception e) { + commandSender.sendMessage("[EliteMobs] World argument was not valid!"); + } + + } + + public static void spawnCustomBossCommand(CommandSender commandSender, + String fileName, + String world, + Vector coords, + int level) { + try { + Location location = new Location(Bukkit.getWorld(world), coords.getX(), coords.getY(), coords.getZ()); + CustomBossesConfigFields customBossesConfigFields = CustomBossesConfig.getCustomBoss(fileName); + if (customBossesConfigFields == null) { + commandSender.sendMessage("Filename " + fileName + " is not valid! Make sure you are writing the name of a configuration file in the custombosses folder!"); + return; + } + CustomBossEntity customBossEntity = new CustomBossEntity(customBossesConfigFields); + customBossEntity.setSpawnLocation(location); + customBossEntity.setLevel(level); + customBossEntity.spawn(false); + } catch (Exception e) { + commandSender.sendMessage("[EliteMobs] World argument was not valid!"); + } + + } + + public static void spawnCustomBossCommand(Player player, String fileName, int level) { + CustomBossesConfigFields customBossesConfigFields = CustomBossesConfig.getCustomBoss(fileName); + if (customBossesConfigFields == null) { + player.sendMessage("Filename " + fileName + " is not valid! Make sure you are writing the name of a configuration file in the custombosses folder!"); + return; + } + CustomBossEntity customBossEntity = new CustomBossEntity(customBossesConfigFields); + customBossEntity.setSpawnLocation(getLocation(player)); + customBossEntity.setLevel(level); + customBossEntity.spawn(false); + } + + public static void spawnCustomBossCommand(Player player, String fileName) { + CustomBossesConfigFields customBossesConfigFields = CustomBossesConfig.getCustomBoss(fileName); + if (customBossesConfigFields == null) { + player.sendMessage("Filename " + fileName + " is not valid! Make sure you are writing the name of a configuration file in the custombosses folder!"); + return; + } + CustomBossEntity customBossEntity = new CustomBossEntity(customBossesConfigFields); + customBossEntity.setSpawnLocation(getLocation(player)); + customBossEntity.spawn(false); + } + + public static void spawnSuperMobCommand(Player player, EntityType entityType) { + if (SuperMobProperties.isValidSuperMobType(entityType)) + spawnSuperMob(entityType, getLocation(player)); + else + player.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &4Entity type " + entityType.toString() + " can't be a Super Mob!")); + } + + private static Location getLocation(Player player) { + return player.getTargetBlock(null, 30).getLocation().add(0.5, 1, 0.5); + } + + private static HashSet getPowers(String[] mobPowers, CommandSender commandSender) { + + HashSet elitePowers = new HashSet<>(); + + if (mobPowers.length > 0) + for (String string : mobPowers) { + ElitePower elitePower = ElitePower.getElitePower(string); + if (elitePower == null) { + commandSender.sendMessage("[EliteMobs] Power " + string + " is not a valid power! Valid powers:"); + StringBuilder allPowers = new StringBuilder(); + for (ElitePower iteratedPower : ElitePower.getElitePowers()) + allPowers.append(iteratedPower.getName()).append(", "); + allPowers.append("custom"); + commandSender.sendMessage(allPowers.toString()); + return new HashSet<>(); + } + elitePowers.add(elitePower); + } + return elitePowers; + } + + private static void spawnSuperMob(EntityType entityType, Location location) { + SuperMobConstructor.constructSuperMob((LivingEntity) location.getWorld().spawnEntity(location, entityType)); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/SpawnMobCommandHandler.java b/src/main/java/com/magmaguy/elitemobs/commands/SpawnMobCommandHandler.java deleted file mode 100644 index f1a072e90..000000000 --- a/src/main/java/com/magmaguy/elitemobs/commands/SpawnMobCommandHandler.java +++ /dev/null @@ -1,421 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.commands; - -import com.magmaguy.elitemobs.events.mobs.*; -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; -import com.magmaguy.elitemobs.mobconstructor.SuperMobConstructor; -import com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs.EliteMobProperties; -import com.magmaguy.elitemobs.mobconstructor.mobdata.passivemobs.SuperMobProperties; -import com.magmaguy.elitemobs.mobpowers.ElitePower; -import com.magmaguy.elitemobs.mobpowers.defensivepowers.*; -import com.magmaguy.elitemobs.mobpowers.majorpowers.*; -import com.magmaguy.elitemobs.mobpowers.miscellaneouspowers.BonusLoot; -import com.magmaguy.elitemobs.mobpowers.miscellaneouspowers.MovementSpeed; -import com.magmaguy.elitemobs.mobpowers.miscellaneouspowers.Taunt; -import com.magmaguy.elitemobs.mobpowers.offensivepowers.*; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.command.BlockCommandSender; -import org.bukkit.command.CommandSender; -import org.bukkit.command.ConsoleCommandSender; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; -import org.bukkit.entity.Squid; -import org.bukkit.util.Vector; - -import java.util.ArrayList; -import java.util.HashSet; - -import static com.magmaguy.elitemobs.EliteMobs.validWorldList; - -/** - * Created by MagmaGuy on 01/05/2017. - */ -public class SpawnMobCommandHandler { - - public static void spawnMob(CommandSender commandSender, String[] args) { - - Location location = getLocation(commandSender, args); - if (location == null) return; - - EntityType entityType = getEntityType(commandSender, args); - if (entityType == null) return; - - if (SuperMobProperties.isValidSuperMobType(entityType)) { - spawnSuperMob(entityType, location); - return; - } - - Integer mobLevel = getLevel(commandSender, args); - if (mobLevel == null) return; - - HashSet mobPowers = getPowers(commandSender, args); - - EliteMobEntity eliteMobEntity = new EliteMobEntity(entityType, location, mobLevel, mobPowers); - - } - - private static Location getLocation(CommandSender commandSender, String args[]) { - - if (commandSender instanceof Player) - return getLocation((Player) commandSender); - - - if (commandSender instanceof ConsoleCommandSender || commandSender instanceof BlockCommandSender) { - - World world = null; - - try { - - for (World worldIterator : validWorldList) - if (worldIterator.getName().equals(args[1])) - world = worldIterator; - - } catch (Exception e) { - - commandSender.sendMessage("[EliteMobs] Invalid world name when summoning Elite Mob."); - commandSender.sendMessage("[EliteMobs] Valid worlds:"); - for (World worldIterator : validWorldList) - commandSender.sendMessage(worldIterator.getName()); - commandSender.sendMessage("[EliteMobs] Is your world enabled in the ValidWorlds.yml config file?"); - return null; - - } - - double xCoord, yCoord, zCoord; - - try { - - xCoord = Double.parseDouble(args[2]); - yCoord = Double.parseDouble(args[3]); - zCoord = Double.parseDouble(args[4]); - - } catch (Exception e) { - - commandSender.sendMessage("[EliteMobs] Invalid X Y Z coordinates."); - return null; - - } - - return new Location(world, xCoord, yCoord, zCoord); - - } - - return null; - - } - - private static Location getLocation(Player player) { - return player.getTargetBlock(null, 30).getLocation().add(0.5, 1, 0.5); - } - - - private static EntityType getEntityType(CommandSender commandSender, String args[]) { - - String entityInput = ""; - - if (commandSender instanceof Player) { - - try { - - entityInput = args[1].toLowerCase(); - - } catch (Exception e) { - - commandSender.sendMessage("[EliteMobs] Error trying to obtain mob type."); - String validEntities = ""; - for (EntityType entities : EliteMobProperties.getValidMobTypes()) - validEntities += entities + ", "; - commandSender.sendMessage("[EliteMobs] Valid mob types:" + validEntities); - - } - - - } else if (commandSender instanceof ConsoleCommandSender || commandSender instanceof BlockCommandSender) { - - - try { - - entityInput = args[5].toLowerCase(); - - } catch (Exception e) { - - commandSender.sendMessage("[EliteMobs] Error trying to obtain mob type."); - String validEntities = ""; - for (EntityType entities : EliteMobProperties.getValidMobTypes()) - validEntities += entities + ", "; - commandSender.sendMessage("[EliteMobs] Valid mob types:" + validEntities); - - } - - } - - try { - return EntityType.valueOf(entityInput.toUpperCase()); - } catch (Exception ex) { - commandSender.sendMessage("[EliteMobs] Could not spawn mob type " + entityInput + - " If this is incorrect, please contact the dev."); - return null; - } - - } - - private static Integer getLevel(CommandSender commandSender, String args[]) { - - int mobLevel = 0; - - if (commandSender instanceof Player) { - - try { - - mobLevel = Integer.valueOf(args[2]); - - } catch (Error error) { - - commandSender.sendMessage("Error assigning mob level to Elite Mob. Mob level must be above 0."); - - } - - - } else if (commandSender instanceof ConsoleCommandSender || commandSender instanceof BlockCommandSender) { - - try { - - mobLevel = Integer.valueOf(args[6]); - - } catch (Error error) { - - commandSender.sendMessage("Error assigning mob level to Elite Mob. Mob level must be above 0."); - - } - - } - - if (mobLevel < 1) - mobLevel = 1; - - return mobLevel; - - } - - private static HashSet getPowers(CommandSender commandSender, String args[]) { - - ArrayList mobPowers = new ArrayList(); - - if (commandSender instanceof Player) { - - if (args.length > 3) { - - int index = 0; - - for (String arg : args) { - - //mob powers start after arg 2 - if (index > 2) - mobPowers.add(arg); - - index++; - - } - - } - - } else if (commandSender instanceof ConsoleCommandSender || commandSender instanceof BlockCommandSender) { - - if (args.length > 6) { - - int index = 0; - - for (String arg : args) { - - //mob powers start after arg 6 - if (index > 6) - mobPowers.add(arg); - - index++; - - } - - } - - } - - return getPowers(mobPowers, commandSender); - - } - - private static HashSet getPowers(ArrayList mobPowers, CommandSender commandSender) { - - HashSet elitePowers = new HashSet<>(); - - if (mobPowers.size() > 0) { - - for (String string : mobPowers) { - - switch (string.toLowerCase()) { - //major powers - case "zombiefriends": - elitePowers.add(new ZombieFriends()); - break; - case "zombienecronomicon": - elitePowers.add(new ZombieNecronomicon()); - break; - case "zombieteamrocket": - elitePowers.add(new ZombieTeamRocket()); - break; - case "zombieparents": - elitePowers.add(new ZombieParents()); - break; - case "zombiebloat": - elitePowers.add(new ZombieBloat()); - break; - case "skeletontrackingarrow": - elitePowers.add(new SkeletonTrackingArrow()); - break; - case "skeletonpillar": - elitePowers.add(new SkeletonPillar()); - break; - //minor powers - case "attackarrow": - elitePowers.add(new AttackArrow()); - break; - case "attackblinding": - elitePowers.add(new AttackBlinding()); - break; - case "attackconfusing": - elitePowers.add(new AttackConfusing()); - break; - case "attackfire": - elitePowers.add(new AttackConfusing()); - break; - case "attackfireball": - elitePowers.add(new AttackFireball()); - break; - case "attackfreeze": - elitePowers.add(new AttackFreeze()); - break; - case "attackgravity": - elitePowers.add(new AttackGravity()); - break; - case "attackpoison": - elitePowers.add(new AttackPoison()); - break; - case "attackpush": - elitePowers.add(new AttackPush()); - break; - case "attackweakness": - elitePowers.add(new AttackWeakness()); - break; - case "attackweb": - elitePowers.add(new AttackWeb()); - break; - case "attackwither": - elitePowers.add(new AttackWither()); - break; - case "bonusloot": - elitePowers.add(new BonusLoot()); - break; - case "invisibility": - elitePowers.add(new Invisibility()); - break; - case "invulnerabilityarrow": - elitePowers.add(new InvulnerabilityArrow()); - break; - case "invulnerabilityfalldamage": - elitePowers.add(new InvulnerabilityFallDamage()); - break; - case "invulnerabilityfire": - elitePowers.add(new InvulnerabilityFire()); - break; - case "invulnerabilityknockback": - elitePowers.add(new InvulnerabilityKnockback()); - break; - case "movementspeed": - elitePowers.add(new MovementSpeed()); - break; - case "taunt": - elitePowers.add(new Taunt()); - break; - default: - commandSender.sendMessage(string + " is not a valid power."); - commandSender.sendMessage("Valid powers: attackarrow, attackblinding, attackconfusing," + - " attackfire, attackfireball, attackfreeze,attackgravity, attackpoison, attackpush, " + - "attackweakness, attackweb, attackwither, bonusloot, invisibility, invulnerabilityarrow," + - "invulnerabilityfalldamage, invulnerabilityfire, invulnerabilityknockback, movementspeed," + - "taunt, zombiefriends, zombienecronomicon, zombieteamrocket, zombieteamrocket, zombieparents," + - "zombiebloat, skeletontrackingarrow, skeletonpillar"); - break; - - } - - } - - } - - return elitePowers; - - } - - private static void spawnSuperMob(EntityType entityType, Location location) { - SuperMobConstructor.constructSuperMob((LivingEntity) location.getWorld().spawnEntity(location, entityType)); - } - - public static void spawnBossMob(Player player, String[] args) { - - Location cursorLocation = player.getTargetBlock(null, 5).getLocation().add(new Vector(0.5, 2, 0.5)); - - if (args[1].equalsIgnoreCase("treasuregoblin")) { - - TreasureGoblin.createGoblin(cursorLocation); - player.sendMessage("Spawned treasure goblin"); - - } - - if (args[1].equalsIgnoreCase("zombieking")) { - - ZombieKing.spawnZombieKing(cursorLocation); - player.sendMessage("Spawned zombie king"); - - } - - if (args[1].equalsIgnoreCase("kraken")) { - - Squid squid = (Squid) cursorLocation.getWorld().spawnEntity(cursorLocation, EntityType.SQUID); - Kraken.spawnKraken(squid.getLocation()); - squid.remove(); - player.sendMessage("Spawned Kraken"); - - } - - if (args[1].equalsIgnoreCase("balrog")) { - - Balrog.spawnBalrog(cursorLocation); - player.sendMessage("Spawned Balrog"); - - } - - if (args[1].equalsIgnoreCase("fae")) { - - Fae.spawnFae(cursorLocation); - player.sendMessage("Spawned Fae"); - - } - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/StatsCommandHandler.java b/src/main/java/com/magmaguy/elitemobs/commands/StatsCommandHandler.java deleted file mode 100644 index 639fc0d2f..000000000 --- a/src/main/java/com/magmaguy/elitemobs/commands/StatsCommandHandler.java +++ /dev/null @@ -1,328 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.commands; - -import com.magmaguy.elitemobs.EntityTracker; -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.DefaultConfig; -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.bukkit.command.CommandSender; -import org.bukkit.command.ConsoleCommandSender; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; - -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import static com.magmaguy.elitemobs.EliteMobs.validWorldList; -import static org.bukkit.Bukkit.getLogger; -import static org.bukkit.Bukkit.getServer; - -/** - * Created by MagmaGuy on 01/05/2017. - */ -public class StatsCommandHandler { - - public static void statsHandler(CommandSender commandSender) { - - int mobLevelSavingsCount = 0; - int totalMobCount = 0; - int aggressiveCount = 0; - int passiveCount = 0; - int blazeCount = 0; - int caveSpiderCount = 0; - int creeperCount = 0; - int endermanCount = 0; - int endermiteCount = 0; - int huskCount = 0; - int ironGolemCount = 0; - int pigZombieCount = 0; - int polarBearCount = 0; - int silverfishCount = 0; - int skeletonCount = 0; - int spiderCount = 0; - int strayCount = 0; - int witchCount = 0; - int witherSkeletonCount = 0; - int zombieCount = 0; - int zombieVillagerCount = 0; - - int chickenCount = 0; - int cowCount = 0; - int mushroomCowCount = 0; - int pigCount = 0; - int sheepCount = 0; - - for (World world : validWorldList) { - - for (LivingEntity livingEntity : world.getLivingEntities()) { - - if (EntityTracker.isEliteMob(livingEntity) || - EntityTracker.isSuperMob(livingEntity)) { - - totalMobCount++; - - if (EntityTracker.isEliteMob(livingEntity)) { - - mobLevelSavingsCount += EntityTracker.getEliteMobEntity(livingEntity).getLevel(); - aggressiveCount++; - - switch (livingEntity.getType()) { - - case ZOMBIE: - zombieCount++; - break; - case HUSK: - huskCount++; - break; - case ZOMBIE_VILLAGER: - zombieVillagerCount++; - break; - case SKELETON: - skeletonCount++; - break; - case WITHER_SKELETON: - witherSkeletonCount++; - break; - case STRAY: - strayCount++; - break; - case PIG_ZOMBIE: - pigZombieCount++; - break; - case CREEPER: - creeperCount++; - break; - case SPIDER: - spiderCount++; - break; - case ENDERMAN: - endermanCount++; - break; - case CAVE_SPIDER: - caveSpiderCount++; - break; - case SILVERFISH: - silverfishCount++; - break; - case BLAZE: - blazeCount++; - break; - case WITCH: - witchCount++; - break; - case ENDERMITE: - endermiteCount++; - break; - case POLAR_BEAR: - polarBearCount++; - break; - case IRON_GOLEM: - ironGolemCount++; - break; - default: - getLogger().info("Error: Couldn't assign custom mob name due to unexpected aggressive boss mob (talk to the dev!)"); - getLogger().info("Missing mob type: " + livingEntity.getType()); - break; - } - - - } else if (EntityTracker.isSuperMob(livingEntity)) { - - //passive EliteMobs only stack at 50 right now - //TODO: redo this count at some other stage of this plugin's development - mobLevelSavingsCount += ConfigValues.defaultConfig.getInt(DefaultConfig.SUPERMOB_STACK_AMOUNT); - passiveCount++; - - switch (livingEntity.getType()) { - - case CHICKEN: - chickenCount++; - break; - case COW: - cowCount++; - break; - case MUSHROOM_COW: - mushroomCowCount++; - break; - case PIG: - pigCount++; - break; - case SHEEP: - sheepCount++; - break; - default: - getLogger().info("Error: Couldn't assign custom mob name due to unexpected passive boss mob (talk to the dev!)"); - getLogger().info("Missing mob type: " + livingEntity.getType()); - break; - - } - - } - - } - - } - - } - - if (commandSender instanceof Player) { - - Player player = (Player) commandSender; - - player.sendMessage("§5§m-----------------------------------------------------"); - player.sendMessage("§a§lEliteMobs v. " + Bukkit.getPluginManager().getPlugin(MetadataHandler.ELITE_MOBS).getDescription().getVersion() + " stats:"); - player.sendMessage("There are currently §l§6" + totalMobCount + " §f§rEliteMobs replacing §l§e" + - mobLevelSavingsCount + " §f§rregular mobs."); - - if (aggressiveCount > 0) { - - String aggressiveCountMessage = "§c" + aggressiveCount + " §4Aggressive EliteMobs: §f"; - - HashMap unsortedMobCount = new HashMap(); - - unsortedMobCountFilter(unsortedMobCount, blazeCount, "blazes"); - unsortedMobCountFilter(unsortedMobCount, caveSpiderCount, "cave spiders"); - unsortedMobCountFilter(unsortedMobCount, creeperCount, "creepers"); - unsortedMobCountFilter(unsortedMobCount, endermanCount, "endermen"); - unsortedMobCountFilter(unsortedMobCount, endermiteCount, "endermites"); - unsortedMobCountFilter(unsortedMobCount, huskCount, "husks"); - unsortedMobCountFilter(unsortedMobCount, pigZombieCount, "zombiepigmen"); - unsortedMobCountFilter(unsortedMobCount, polarBearCount, "polar bears"); - unsortedMobCountFilter(unsortedMobCount, silverfishCount, "silverfish"); - unsortedMobCountFilter(unsortedMobCount, skeletonCount, "skeletons"); - unsortedMobCountFilter(unsortedMobCount, spiderCount, "spiders"); - unsortedMobCountFilter(unsortedMobCount, strayCount, "strays"); - unsortedMobCountFilter(unsortedMobCount, witchCount, "witches"); - unsortedMobCountFilter(unsortedMobCount, witherSkeletonCount, "wither skeletons"); - unsortedMobCountFilter(unsortedMobCount, zombieCount, "zombie"); - unsortedMobCountFilter(unsortedMobCount, zombieVillagerCount, "zombie villagers"); - - player.sendMessage(messageStringAppender(aggressiveCountMessage, unsortedMobCount)); - - } - - if (passiveCount > 0) { - - String passiveCountMessage = "§b" + passiveCount + " §3Passive EliteMobs: §f"; - - HashMap unsortedMobCount = new HashMap(); - - unsortedMobCountFilter(unsortedMobCount, chickenCount, "chickens"); - unsortedMobCountFilter(unsortedMobCount, cowCount, "cows"); - unsortedMobCountFilter(unsortedMobCount, ironGolemCount, "iron golems"); - unsortedMobCountFilter(unsortedMobCount, mushroomCowCount, "mushroom cows"); - unsortedMobCountFilter(unsortedMobCount, pigCount, "pigs"); - unsortedMobCountFilter(unsortedMobCount, sheepCount, "sheep"); - - player.sendMessage(messageStringAppender(passiveCountMessage, unsortedMobCount)); - - } - - player.sendMessage("§5§m-----------------------------------------------------"); - - } else if (commandSender instanceof ConsoleCommandSender) { - - getServer().getConsoleSender().sendMessage("§5§m-------------------------------------------------------------"); - getServer().getConsoleSender().sendMessage("§a§lEliteMobs stats:"); - getServer().getConsoleSender().sendMessage("There are currently §l§6" + totalMobCount + " §f§rEliteMobs replacing §l§e" + - mobLevelSavingsCount + " §f§rregular mobs."); - - if (aggressiveCount > 0) { - - String aggressiveCountMessage = "§c" + aggressiveCount + " §4Aggressive EliteMobs: §f"; - - HashMap unsortedMobCount = new HashMap(); - - unsortedMobCountFilter(unsortedMobCount, blazeCount, "blazes"); - unsortedMobCountFilter(unsortedMobCount, caveSpiderCount, "cave spiders"); - unsortedMobCountFilter(unsortedMobCount, creeperCount, "creepers"); - unsortedMobCountFilter(unsortedMobCount, endermanCount, "endermen"); - unsortedMobCountFilter(unsortedMobCount, endermiteCount, "endermites"); - unsortedMobCountFilter(unsortedMobCount, huskCount, "husks"); - unsortedMobCountFilter(unsortedMobCount, ironGolemCount, "iron golems"); - unsortedMobCountFilter(unsortedMobCount, pigZombieCount, "zombiepigmen"); - unsortedMobCountFilter(unsortedMobCount, polarBearCount, "polar bears"); - unsortedMobCountFilter(unsortedMobCount, silverfishCount, "silverfish"); - unsortedMobCountFilter(unsortedMobCount, skeletonCount, "skeletons"); - unsortedMobCountFilter(unsortedMobCount, spiderCount, "spiders"); - unsortedMobCountFilter(unsortedMobCount, strayCount, "strays"); - unsortedMobCountFilter(unsortedMobCount, witchCount, "witches"); - unsortedMobCountFilter(unsortedMobCount, witherSkeletonCount, "wither skeletons"); - unsortedMobCountFilter(unsortedMobCount, zombieCount, "zombie"); - unsortedMobCountFilter(unsortedMobCount, zombieVillagerCount, "zombie villagers"); - - getServer().getConsoleSender().sendMessage(messageStringAppender(aggressiveCountMessage, unsortedMobCount)); - - } - - if (passiveCount > 0) { - - String passiveCountMessage = "§b" + passiveCount + " §3Passive EliteMobs: §f"; - - HashMap unsortedMobCount = new HashMap(); - - unsortedMobCountFilter(unsortedMobCount, chickenCount, "chickens"); - unsortedMobCountFilter(unsortedMobCount, cowCount, "cows"); - unsortedMobCountFilter(unsortedMobCount, mushroomCowCount, "mushroom cows"); - unsortedMobCountFilter(unsortedMobCount, pigCount, "pigs"); - unsortedMobCountFilter(unsortedMobCount, sheepCount, "sheep"); - - getServer().getConsoleSender().sendMessage(messageStringAppender(passiveCountMessage, unsortedMobCount)); - - } - - getServer().getConsoleSender().sendMessage("§5§m-------------------------------------------------------------"); - - } - - } - - private static void unsortedMobCountFilter(HashMap unsortedMobCount, int count, String mobTypeName) { - - if (count > 0) { - - unsortedMobCount.put(mobTypeName, count); - - } - - } - - private static String messageStringAppender(String countMessage, HashMap unsortedMobCount) { - - Iterator iterator = unsortedMobCount.entrySet().iterator(); - - while (iterator.hasNext()) { - - Map.Entry pair = (Map.Entry) iterator.next(); - - String mobCountString = "§6§l" + pair.getValue(); - String commaString = ","; - String spacing = " "; - String mobNameString = "§r§f" + pair.getKey(); - - countMessage += commaString + spacing + mobCountString + spacing + mobNameString; - - } - - return countMessage; - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/TreasureChestCommands.java b/src/main/java/com/magmaguy/elitemobs/commands/TreasureChestCommands.java new file mode 100644 index 000000000..a0204b75a --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/commands/TreasureChestCommands.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.commands; + +import com.magmaguy.elitemobs.dungeons.Minidungeon; +import org.bukkit.entity.Player; + +public class TreasureChestCommands { + private TreasureChestCommands() { + } + + public static void addRelativeTreasureChest(Player player, String treasureChestFilename, String minidungeonName) { + Minidungeon minidungeon = Minidungeon.getMinidungeons().get(minidungeonName); + if (minidungeon == null) { + player.sendMessage("Invalid minidungeon name!"); + return; + } + minidungeon.addRelativeTreasureChest(treasureChestFilename, player.getLocation().getBlock().getLocation(), player); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/TriggerEventHandler.java b/src/main/java/com/magmaguy/elitemobs/commands/TriggerEventHandler.java deleted file mode 100644 index 53218c106..000000000 --- a/src/main/java/com/magmaguy/elitemobs/commands/TriggerEventHandler.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.magmaguy.elitemobs.commands; - -import com.magmaguy.elitemobs.events.DeadMoon; -import com.magmaguy.elitemobs.events.SmallTreasureGoblin; -import org.bukkit.command.CommandSender; - -public class TriggerEventHandler { - - public static void triggerEventCommand(CommandSender commandSender, String[] args){ - - if (CommandHandler.permCheck(CommandHandler.EVENT_LAUNCH_SMALLTREASUREGOBLIN, commandSender) && args[1].equalsIgnoreCase("smalltreasuregoblin")) { - SmallTreasureGoblin.initializeEvent(); - commandSender.sendMessage("Queued small treasure goblin event for next valid zombie spawn"); - } - if (CommandHandler.permCheck(CommandHandler.EVENT_LAUNCH_DEADMOON, commandSender) && args[1].equalsIgnoreCase("deadmoon")) { - DeadMoon.initializeEvent(); - commandSender.sendMessage("Queued deadmoon event for next new moon"); - } - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/UserCommands.java b/src/main/java/com/magmaguy/elitemobs/commands/UserCommands.java new file mode 100644 index 000000000..fab55a27d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/commands/UserCommands.java @@ -0,0 +1,374 @@ +package com.magmaguy.elitemobs.commands; + +import cloud.commandframework.ArgumentDescription; +import cloud.commandframework.Command; +import cloud.commandframework.arguments.CommandArgument; +import cloud.commandframework.arguments.standard.DoubleArgument; +import cloud.commandframework.arguments.standard.StringArgument; +import cloud.commandframework.bukkit.BukkitCommandManager; +import cloud.commandframework.extra.confirmation.CommandConfirmationManager; +import cloud.commandframework.meta.CommandMeta; +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.api.PlayerPreTeleportEvent; +import com.magmaguy.elitemobs.commands.admin.CheckTierOthersCommand; +import com.magmaguy.elitemobs.commands.combat.CheckTierCommand; +import com.magmaguy.elitemobs.commands.guild.AdventurersGuildCommand; +import com.magmaguy.elitemobs.commands.quests.QuestCommand; +import com.magmaguy.elitemobs.config.DefaultConfig; +import com.magmaguy.elitemobs.config.EconomySettingsConfig; +import com.magmaguy.elitemobs.config.TranslationConfig; +import com.magmaguy.elitemobs.instanced.MatchInstance; +import com.magmaguy.elitemobs.items.EliteItemLore; +import com.magmaguy.elitemobs.items.ShareItem; +import com.magmaguy.elitemobs.menus.*; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import com.magmaguy.elitemobs.playerdata.database.PlayerData; +import com.magmaguy.elitemobs.playerdata.statusscreen.PlayerStatusScreen; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.UUID; +import java.util.concurrent.TimeUnit; + +public class UserCommands { + + public UserCommands(BukkitCommandManager manager, Command.Builder builder) { + // /em adventurersguild + manager.command(builder.literal("adventurersguild", "ag") + .meta(CommandMeta.DESCRIPTION, "Teleports players to the Adventurer's Guild Hub or opens the Adventurer's Guild menu.") + .senderType(Player.class) + .permission("elitemobs.adventurersguild.command") + //permission is dealt inside of the command + .handler(commandContext -> { + AdventurersGuildCommand.adventurersGuildCommand((Player) commandContext.getSender()); + })); + + // /em shareitem + manager.command(builder.literal("shareitem") + .meta(CommandMeta.DESCRIPTION, "Shares a held Elite item on chat") + .senderType(Player.class) + .permission("elitemobs.shareitem") + .handler(commandContext -> ShareItem.showOnChat((Player) commandContext.getSender()))); + + // /em shop + manager.command(builder.literal("shop") + .meta(CommandMeta.DESCRIPTION, "Opens the procedurally generated item shop or teleports the player to the Adventurer's Guild Hub") + .senderType(Player.class) + .permission("elitemobs.shop.command") + .handler(commandContext -> { + if (!AdventurersGuildCommand.adventurersGuildTeleport((Player) commandContext.getSender())) + ProceduralShopMenu.shopInitializer((Player) commandContext.getSender()); + })); + + // /em customshop + manager.command(builder.literal("customshop") + .meta(CommandMeta.DESCRIPTION, "Opens the custom item shop or teleports the player to the Adventurer's Guild Hub") + .senderType(Player.class) + .permission("elitemobs.customshop.command") + .handler(commandContext -> { + if (!AdventurersGuildCommand.adventurersGuildTeleport((Player) commandContext.getSender())) + CustomShopMenu.customShopInitializer((Player) commandContext.getSender()); + })); + + // /em repair + manager.command(builder.literal("repair") + .meta(CommandMeta.DESCRIPTION, "Opens the custom item shop or teleports the player to the Adventurer's Guild Hub") + .senderType(Player.class) + .permission("elitemobs.repair.command") + .handler(commandContext -> { + if (!AdventurersGuildCommand.adventurersGuildTeleport((Player) commandContext.getSender())) { + RepairMenu repairMenu = new RepairMenu(); + repairMenu.constructRepairMenu((Player) commandContext.getSender()); + } + })); + + // /em enhance + manager.command(builder.literal("enhance") + .meta(CommandMeta.DESCRIPTION, "Opens the custom item shop or teleports the player to the Adventurer's Guild Hub") + .senderType(Player.class) + .permission("elitemobs.enhancer.command") + .handler(commandContext -> { + if (!AdventurersGuildCommand.adventurersGuildTeleport((Player) commandContext.getSender())) { + EnhancementMenu enhancementMenu = new EnhancementMenu(); + enhancementMenu.constructEnhancementMenu((Player) commandContext.getSender()); + } + })); + + // /em refine + manager.command(builder.literal("refine") + .meta(CommandMeta.DESCRIPTION, "Opens the custom item shop or teleports the player to the Adventurer's Guild Hub") + .senderType(Player.class) + .permission("elitemobs.refiner.command") + .handler(commandContext -> { + if (!AdventurersGuildCommand.adventurersGuildTeleport((Player) commandContext.getSender())) { + RefinerMenu refinerMenu = new RefinerMenu(); + refinerMenu.constructRefinerMenu((Player) commandContext.getSender()); + } + })); + + // /em smelt + manager.command(builder.literal("smelt") + .meta(CommandMeta.DESCRIPTION, "Opens the custom item shop or teleports the player to the Adventurer's Guild Hub") + .senderType(Player.class) + .permission("elitemobs.smelt.command") + .handler(commandContext -> { + if (!AdventurersGuildCommand.adventurersGuildTeleport((Player) commandContext.getSender())) { + SmeltMenu smeltMenu = new SmeltMenu(); + smeltMenu.constructSmeltMenu((Player) commandContext.getSender()); + } + })); + + // /em scrap + manager.command(builder.literal("scrap") + .meta(CommandMeta.DESCRIPTION, "Opens the custom item shop or teleports the player to the Adventurer's Guild Hub") + .senderType(Player.class) + .permission("elitemobs.scrap.command") + .handler(commandContext -> { + if (!AdventurersGuildCommand.adventurersGuildTeleport((Player) commandContext.getSender())) { + ScrapperMenu scrapperMenu = new ScrapperMenu(); + scrapperMenu.constructScrapMenu((Player) commandContext.getSender()); + } + })); + + // /em unbind + manager.command(builder.literal("unbind") + .meta(CommandMeta.DESCRIPTION, "Opens the custom item shop or teleports the player to the Adventurer's Guild Hub") + .senderType(Player.class) + .permission("elitemobs.unbind.command") + .handler(commandContext -> { + if (!AdventurersGuildCommand.adventurersGuildTeleport((Player) commandContext.getSender())) { + UnbindMenu unbindMenu = new UnbindMenu(); + unbindMenu.constructUnbinderMenu((Player) commandContext.getSender()); + } + })); + + // /em wallet + manager.command(builder.literal("wallet") + .meta(CommandMeta.DESCRIPTION, "Checks the EliteMobs currency") + .senderType(Player.class) + .permission("elitemobs.currency.check") + .handler(commandContext -> { + if (DefaultConfig.isOtherCommandsLeadToEMStatusMenu()) + new PlayerStatusScreen((Player) commandContext.getSender()); + else + CurrencyCommandsHandler.walletCommand((Player) commandContext.getSender()); + })); + + // /em quest accept + manager.command(builder.literal("quest") + .literal("accept") + .argument(StringArgument.newBuilder("questID"), ArgumentDescription.of("Quest ID")) + .meta(CommandMeta.DESCRIPTION, "Accepts a quest") + .senderType(Player.class) + .permission("elitemobs.quest.command") + .handler(commandContext -> { + QuestCommand.joinQuest(commandContext.get("questID"), (Player) commandContext.getSender()); + })); + + // /em quest track + manager.command(builder.literal("quest") + .literal("track") + .argument(StringArgument.newBuilder("questID"), ArgumentDescription.of("Quest ID")) + .meta(CommandMeta.DESCRIPTION, "Toggles quest tracking") + .senderType(Player.class) + .permission("elitemobs.quest.command") + .handler(commandContext -> { + QuestCommand.trackQuest(commandContext.get("questID"), (Player) commandContext.getSender()); + })); + + // /em quest complete + manager.command(builder.literal("quest") + .literal("complete") + .argument(StringArgument.newBuilder("questID"), ArgumentDescription.of("Quest ID")) + .meta(CommandMeta.DESCRIPTION, "Completes a quest") + .senderType(Player.class) + .permission("elitemobs.quest.command") + .handler(commandContext -> { + QuestCommand.completeQuest(commandContext.get("questID"), (Player) commandContext.getSender()); + })); + + + // /em quest leave + manager.command(builder.literal("quest") + .literal("leave") + .argument(StringArgument.newBuilder("questID"), ArgumentDescription.of("Quest ID")) + .meta(CommandMeta.DESCRIPTION, "Leaves a quest") + .senderType(Player.class) + .permission("elitemobs.quest.command") + .handler(commandContext -> QuestCommand.leaveQuest((Player) commandContext.getSender(), commandContext.get("questID")))); + + CommandArgument onlinePlayers = StringArgument.newBuilder("onlinePlayer") + .withSuggestionsProvider(((objectCommandContext, s) -> { + ArrayList arrayList = new ArrayList<>(); + Bukkit.getOnlinePlayers().forEach(player -> arrayList.add(player.getName())); + return arrayList; + })).build(); + + + // Create the confirmation manager. This allows us to require certain commands to be + // confirmed before they can be executed + CommandConfirmationManager paymentConfirmationManager = new CommandConfirmationManager<>( + /* Timeout */ 30L, + /* Timeout unit */ TimeUnit.SECONDS, + /* Action when confirmation is required */ context -> context.getCommandContext().getSender().sendMessage( + ChatColorConverter.convert(TranslationConfig.getEconomyTaxMessage() + .replace("$command", "/em confirm") + .replace("$percentage", (EconomySettingsConfig.getPlayerToPlayerTaxes() * 100) + ""))), + /* Action when no confirmation is pending */ sender -> sender.sendMessage( + ChatColorConverter.convert(TranslationConfig.getNoPendingCommands())) + ); + + // Register the confirmation processor. This will enable confirmations for commands that require it + paymentConfirmationManager.registerConfirmationProcessor(manager); + + // Add a confirmation command + manager.command(builder.literal("confirm") + .meta(CommandMeta.DESCRIPTION, "Confirm a pending command") + .handler(paymentConfirmationManager.createConfirmationExecutionHandler())); + + // /em pay + manager.command(builder.literal("pay") + .argument(onlinePlayers.copy(), ArgumentDescription.of("Player name")) + .argument(DoubleArgument.newBuilder("amount"), ArgumentDescription.of("Amount to pay")) + .meta(CommandMeta.DESCRIPTION, "Pays an amount of currency to another player") + .meta(CommandConfirmationManager.META_CONFIRMATION_REQUIRED, true) + .senderType(Player.class) + .permission("elitemobs.currency.pay") + .handler(commandContext -> { + paymentConfirmationManager.createConfirmationExecutionHandler(); + CurrencyCommandsHandler.payCommand( + (Player) commandContext.getSender(), + commandContext.get("onlinePlayer"), + commandContext.get("amount")); + })); + + + // /em rank + manager.command(builder.literal("rank") + .meta(CommandMeta.DESCRIPTION, "Opens the EliteMobs rank menu.") + .senderType(Player.class) + .permission("elitemobs.rank.command") + .handler(commandContext -> { + if (!AdventurersGuildCommand.adventurersGuildTeleport((Player) commandContext.getSender())) + AdventurersGuildCommand.adventurersGuildCommand((Player) commandContext.getSender()); + })); + + // /em menu + manager.command(builder.literal("menu") + .meta(CommandMeta.DESCRIPTION, "Opens the EliteMobs status screen.") + .senderType(Player.class) + .handler(commandContext -> new PlayerStatusScreen((Player) commandContext.getSender()))); + + // /em rank + manager.command(builder.literal("checktier") + .meta(CommandMeta.DESCRIPTION, "Checks your equipped EliteMobs gear tier.") + .senderType(Player.class) + .handler(commandContext -> { + if (DefaultConfig.isOtherCommandsLeadToEMStatusMenu()) + new PlayerStatusScreen((Player) commandContext.getSender()); + else new CheckTierCommand((Player) commandContext.getSender()); + })); + + // /em checktier + manager.command(builder.literal("checktier") + .argument(onlinePlayers.copy(), ArgumentDescription.of("Player name")) + .meta(CommandMeta.DESCRIPTION, "Checks the equipped EliteMobs gear tier of another player.") + .senderType(CommandSender.class) + .permission("elitemobs.checktier.others") + .handler(commandContext -> new CheckTierOthersCommand(commandContext.getSender(), commandContext.get("onlinePlayer")))); + + // /em trackcustomboss uuid + manager.command(builder.literal("trackcustomboss") + .argument(StringArgument.newBuilder("uuid"), ArgumentDescription.of("UUID of the custom boss to track.")) + .meta(CommandMeta.DESCRIPTION, "Tracks a Custom Boss.") + .senderType(Player.class) + .handler(commandContext -> { + try { + for (CustomBossEntity customBossEntity : CustomBossEntity.getTrackableCustomBosses()) + if (customBossEntity.getEliteUUID().equals(UUID.fromString(commandContext.get("uuid")))) { + customBossEntity.getCustomBossBossBar().addTrackingPlayer((Player) commandContext.getSender()); + return; + } + commandContext.getSender().sendMessage("[EliteMobs] Sorry, this boss is already gone!"); + } catch (Exception ex) { + //happens when players try to track an entity that has despawned for any reason + commandContext.getSender().sendMessage("[EliteMobs] Sorry, this boss is already gone!"); + } + })); + + // /em updateitem + manager.command(builder.literal("updateitem") + .meta(CommandMeta.DESCRIPTION, "Manually updates the lore of an item. Used for debugging purposes.") + .senderType(Player.class) + .handler(commandContext -> { + new EliteItemLore(((Player) commandContext.getSender()).getItemInHand(), false); + })); + + // /em dungeontp + manager.command(builder.literal("dungeontp") + .argument(StringArgument.newBuilder("dungeonid"), ArgumentDescription.of("ID of the dungeon to teleport to.")) + .meta(CommandMeta.DESCRIPTION, "Teleports players to Lairs, Minidungeons and Dungeons.") + .permission("elitemobs.dungeontp") + .senderType(Player.class) + .handler(commandContext -> DungeonCommands.teleport((Player) commandContext.getSender(), commandContext.get("dungeonid")))); + + // /em spawntp + manager.command(builder.literal("spawntp") + .meta(CommandMeta.DESCRIPTION, "Teleports players to the server spawn.") + .senderType(Player.class) + .permission("elitemobs.spawntp") + .handler(commandContext -> { + if (DefaultConfig.getDefaultSpawnLocation() != null) + PlayerPreTeleportEvent.teleportPlayer((Player) commandContext.getSender(), DefaultConfig.getDefaultSpawnLocation()); + })); + + // /em alt + manager.command(builder.literal("alt") + .meta(CommandMeta.DESCRIPTION, "Changes the style of the /em menu.") + .senderType(Player.class) + .handler(commandContext -> { + PlayerData.setUseBookMenus(((Player) commandContext.getSender()), !PlayerData.getUseBookMenus(((Player) commandContext.getSender()).getUniqueId())); + commandContext.getSender().sendMessage(TranslationConfig.getSwitchEMStyleMessage()); + })); + + // /em dismiss + manager.command(builder.literal("dismiss") + .meta(CommandMeta.DESCRIPTION, "Dismisses /em menu message.") + .senderType(Player.class) + .handler(commandContext -> { + PlayerData.setDismissEMStatusScreenMessage(((Player) commandContext.getSender()), !PlayerData.getDismissEMStatusScreenMessage(((Player) commandContext.getSender()).getUniqueId())); + })); + + // /em arena + manager.command(builder.literal("arena") + .meta(CommandMeta.DESCRIPTION, "Opens the arena menu.") + .argument(StringArgument.newBuilder("dungeonid"), ArgumentDescription.of("Name of the arena to go to.")) + .senderType(Player.class) + .handler(commandContext -> { + ArenaCommands.openArenaMenu(((Player) commandContext.getSender()), commandContext.get("arena")); + })); + + // /em start - this is for instanced content + manager.command(builder.literal("start") + .meta(CommandMeta.DESCRIPTION, "When in instanced content, starts the countdown to start doing the content.") + .senderType(Player.class) + .handler(commandContext -> { + MatchInstance matchInstance = MatchInstance.getPlayerInstance(((Player) commandContext.getSender())); + if (matchInstance != null) + matchInstance.countdownMatch(); + })); + + // /em quit - this is for instanced content + manager.command(builder.literal("quit") + .meta(CommandMeta.DESCRIPTION, "When in instanced content, makes the player leave the instance.") + .senderType(Player.class) + .handler(commandContext -> { + MatchInstance matchInstance = MatchInstance.getAnyPlayerInstance(((Player) commandContext.getSender())); + if (matchInstance != null) + matchInstance.removeAnyKind((Player) commandContext.getSender()); + })); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/admin/CheckTierOthersCommand.java b/src/main/java/com/magmaguy/elitemobs/commands/admin/CheckTierOthersCommand.java new file mode 100644 index 000000000..60bcfaae4 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/commands/admin/CheckTierOthersCommand.java @@ -0,0 +1,35 @@ +package com.magmaguy.elitemobs.commands.admin; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.adventurersguild.GuildRank; +import com.magmaguy.elitemobs.config.commands.premade.CheckTierOthersConfig; +import com.magmaguy.elitemobs.playerdata.ElitePlayerInventory; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +public class CheckTierOthersCommand { + + public CheckTierOthersCommand(CommandSender commandSender, String playerName) { + + Player player = Bukkit.getPlayer(playerName); + if (player == null) { + commandSender.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &4Invalid player name!")); + return; + } + + double gearTier = ElitePlayerInventory.playerInventories.get(player.getUniqueId()).getFullPlayerTier(true); + double guildRank = GuildRank.getActiveGuildRank(player); + if (guildRank == 0) + guildRank = -10; + else + guildRank--; + guildRank = (guildRank * 0.2); + + commandSender.sendMessage(CheckTierOthersConfig.message1.replace("$player", player.getDisplayName()).replace("$tier", gearTier + "")); + commandSender.sendMessage(CheckTierOthersConfig.message2.replace("$player", player.getDisplayName()).replace("$tier", guildRank + "")); + commandSender.sendMessage(CheckTierOthersConfig.message3.replace("$player", player.getDisplayName()).replace("$tier", (gearTier + guildRank) + "")); + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/admin/DebugScreen.java b/src/main/java/com/magmaguy/elitemobs/commands/admin/DebugScreen.java new file mode 100644 index 000000000..7bd3986c8 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/commands/admin/DebugScreen.java @@ -0,0 +1,84 @@ +package com.magmaguy.elitemobs.commands.admin; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import com.magmaguy.elitemobs.mobconstructor.custombosses.RegionalBossEntity; +import com.magmaguy.elitemobs.playerdata.statusscreen.PlayerStatusScreen; +import com.magmaguy.elitemobs.utils.BookMaker; +import com.magmaguy.elitemobs.utils.SpigotMessage; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +public class DebugScreen { + + public static void open(Player player, String argument) { + if (Bukkit.getPlayer(argument) != null) + new PlayerStatusScreen(player, Bukkit.getPlayer(argument)); + else openBossScreen(player, argument); + } + + private static void openBossScreen(Player player, String argument) { + + TextComponent[] pages = new TextComponent[100]; + + int counter = 0; + for (EliteEntity eliteEntity : EntityTracker.getEliteMobEntities().values()) + if (!(eliteEntity instanceof RegionalBossEntity)) + if (eliteEntity instanceof CustomBossEntity) { + TextComponent textComponent = generateEntry((CustomBossEntity) eliteEntity, argument, player); + if (textComponent == null) continue; + pages[counter] = textComponent; + counter++; + } + + for (RegionalBossEntity regionalBossEntity : RegionalBossEntity.getRegionalBossEntities()) { + TextComponent textComponent = generateEntry(regionalBossEntity, argument, player); + if (textComponent == null) continue; + pages[counter] = textComponent; + counter++; + } + + BookMaker.generateBook(player, pages); + + } + + private static TextComponent generateEntry(CustomBossEntity customBossEntity, String argument, Player player) { + if (!customBossEntity.getCustomBossesConfigFields().getFilename().contains(argument) && + !customBossEntity.getCustomBossesConfigFields().getName().toLowerCase().contains(argument.toLowerCase())) + return null; + TextComponent page = new TextComponent(); + page.addExtra(customBossEntity.getCustomBossesConfigFields().getFilename() + "\n"); + page.addExtra("Name: " + ChatColorConverter.convert(customBossEntity.getCustomBossesConfigFields().getName()) + ChatColor.BLACK + "\n"); + page.addExtra("Level: " + customBossEntity.getCustomBossesConfigFields().getLevel() + "\n"); + if (customBossEntity.getLivingEntity() != null) { + page.addExtra("Is Alive (MC): " + !customBossEntity.getLivingEntity().isDead() + "\n"); + page.addExtra(SpigotMessage.commandHoverMessage(ChatColor.BLUE + "XYZ: " + "\n", + customBossEntity.getLocation().getBlockX() + ", " + + customBossEntity.getLocation().getBlockY() + ", " + + customBossEntity.getLocation().getBlockZ() + "\n" + + ChatColor.BLUE + "Click to teleport! (if alive)", + "/em debugtp " + customBossEntity.getEliteUUID().toString())); + page.addExtra("Has AI: " + !customBossEntity.getLivingEntity().hasAI() + "\n"); + } else + page.addExtra("Is Alive (MC): false\n"); + if (customBossEntity.getLocation() != null && player.getWorld().equals(customBossEntity.getLocation().getWorld())) + page.addExtra(SpigotMessage.hoverMessage(ChatColor.BLUE + "Spawn distance", + "Spawn distance: X=" + (int) (player.getLocation().getX() - customBossEntity.getSpawnLocation().getX()) + + " | Y=" + (int) (player.getLocation().getY() - customBossEntity.getSpawnLocation().getY()) + + " | Z=" + (int) (player.getLocation().getZ() - customBossEntity.getSpawnLocation().getZ()) + "\n")); + page.addExtra("Is Persistent: " + customBossEntity.getCustomBossesConfigFields().isPersistent() + "\n"); + if (customBossEntity instanceof RegionalBossEntity) { + page.addExtra("Is Respawning: " + ((RegionalBossEntity) customBossEntity).isRespawning() + "\n"); + } + + page.addExtra(SpigotMessage.commandHoverMessage(ChatColor.BLUE + "Boss trace!", + "Remember, it requires debug mode to be on! This is used for advanced debugging, ask on discord if you want to know more about it.", + "/elitemobs trace " + customBossEntity.getEliteUUID().toString())); + return page; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/admin/EventCommand.java b/src/main/java/com/magmaguy/elitemobs/commands/admin/EventCommand.java new file mode 100644 index 000000000..e0301dcb7 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/commands/admin/EventCommand.java @@ -0,0 +1,20 @@ +package com.magmaguy.elitemobs.commands.admin; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.events.TimedEvent; +import org.bukkit.command.CommandSender; + +public class EventCommand { + private EventCommand() { + } + + public static void trigger(CommandSender commandSender, String eventName) { + for (TimedEvent timedEvent : TimedEvent.getBlueprintEvents()) + if (timedEvent.getCustomEventsConfigFields().getFilename().equals(eventName)) { + timedEvent.instantiateEvent(); + commandSender.sendMessage(ChatColorConverter.convert("&8[EliteMobs] Queued event " + eventName + " for the next valid time it can spawn. &cThis might take a while depending on the start conditions of the event.")); + return; + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/TierSetSpawner.java b/src/main/java/com/magmaguy/elitemobs/commands/admin/GetTierCommand.java similarity index 63% rename from src/main/java/com/magmaguy/elitemobs/commands/TierSetSpawner.java rename to src/main/java/com/magmaguy/elitemobs/commands/admin/GetTierCommand.java index f8fe78065..aefc73af9 100644 --- a/src/main/java/com/magmaguy/elitemobs/commands/TierSetSpawner.java +++ b/src/main/java/com/magmaguy/elitemobs/commands/admin/GetTierCommand.java @@ -1,4 +1,4 @@ -package com.magmaguy.elitemobs.commands; +package com.magmaguy.elitemobs.commands.admin; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; @@ -6,27 +6,29 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; -public class TierSetSpawner { +public class GetTierCommand { + private GetTierCommand() { + } - public static void spawnTierItem(int tierLevel, Player player) { + public static void get(Player player, int tierLevel) { - ItemStack helmet = new ItemStack(Material.DIAMOND_HELMET); - ItemStack chestplate = new ItemStack(Material.DIAMOND_CHESTPLATE); - ItemStack leggings = new ItemStack(Material.DIAMOND_LEGGINGS); - ItemStack boots = new ItemStack(Material.DIAMOND_BOOTS); - ItemStack sword = new ItemStack(Material.DIAMOND_SWORD); - ItemStack axe = new ItemStack(Material.DIAMOND_AXE); + ItemStack helmet = new ItemStack(Material.NETHERITE_HELMET); + ItemStack chestplate = new ItemStack(Material.NETHERITE_CHESTPLATE); + ItemStack leggings = new ItemStack(Material.NETHERITE_LEGGINGS); + ItemStack boots = new ItemStack(Material.NETHERITE_BOOTS); + ItemStack sword = new ItemStack(Material.NETHERITE_SWORD); + ItemStack axe = new ItemStack(Material.NETHERITE_AXE); ItemStack bow = new ItemStack(Material.BOW); - if (tierLevel > 1) { + if (tierLevel > 8) { - applyEnchantment(helmet, Enchantment.PROTECTION_ENVIRONMENTAL, tierLevel); - applyEnchantment(chestplate, Enchantment.PROTECTION_ENVIRONMENTAL, tierLevel); - applyEnchantment(leggings, Enchantment.PROTECTION_ENVIRONMENTAL, tierLevel); - applyEnchantment(boots, Enchantment.PROTECTION_ENVIRONMENTAL, tierLevel); - applyEnchantment(sword, Enchantment.DAMAGE_ALL, tierLevel); - applyEnchantment(axe, Enchantment.DAMAGE_ALL, tierLevel); - applyEnchantment(bow, Enchantment.ARROW_DAMAGE, tierLevel); + applyEnchantment(helmet, Enchantment.PROTECTION_ENVIRONMENTAL, tierLevel - 8); + applyEnchantment(chestplate, Enchantment.PROTECTION_ENVIRONMENTAL, tierLevel - 8); + applyEnchantment(leggings, Enchantment.PROTECTION_ENVIRONMENTAL, tierLevel - 8); + applyEnchantment(boots, Enchantment.PROTECTION_ENVIRONMENTAL, tierLevel - 8); + applyEnchantment(sword, Enchantment.DAMAGE_ALL, tierLevel - 8); + applyEnchantment(axe, Enchantment.DAMAGE_ALL, tierLevel - 8); + applyEnchantment(bow, Enchantment.ARROW_DAMAGE, tierLevel - 8); } @@ -38,8 +40,6 @@ public static void spawnTierItem(int tierLevel, Player player) { player.getInventory().addItem(axe); player.getInventory().addItem(bow); - return; - } private static void applyEnchantment(ItemStack itemStack, Enchantment enchantment, int tierLevel) { diff --git a/src/main/java/com/magmaguy/elitemobs/commands/admin/KillHandler.java b/src/main/java/com/magmaguy/elitemobs/commands/admin/KillHandler.java new file mode 100644 index 000000000..74372f822 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/commands/admin/KillHandler.java @@ -0,0 +1,95 @@ +package com.magmaguy.elitemobs.commands.admin; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.api.internal.RemovalReason; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs.EliteMobProperties; +import com.magmaguy.elitemobs.mobconstructor.mobdata.passivemobs.SuperMobProperties; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; + +import java.util.ArrayList; + +public class KillHandler { + + //TODO: FIX NPE ISSUE YOU FUCKING MORON + + public static void killAggressiveMobs(CommandSender commandSender) { + int counter = 0; + for (EliteEntity eliteEntity : new ArrayList<>(EntityTracker.getEliteMobEntities().values())) { + eliteEntity.remove(RemovalReason.REMOVE_COMMAND); + counter++; + } + commandSender.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &4Killed " + counter + " Elite Mobs.")); + } + + + public static void killPassiveMobs(CommandSender commandSender) { + int counter = 0; + for (LivingEntity superMobEntity : EntityTracker.getSuperMobs()) { + superMobEntity.remove(); + counter++; + } + commandSender.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &4Killed " + counter + " Super Mobs.")); + } + + public static void killEntityType(CommandSender commandSender, EntityType entityType) { + if (EliteMobProperties.getValidMobTypes().contains(entityType)) { + int counter = 0; + for (EliteEntity eliteEntity : EntityTracker.getEliteMobEntities().values()) { + if (!eliteEntity.getLivingEntity().getType().equals(entityType)) continue; + eliteEntity.remove(RemovalReason.REMOVE_COMMAND); + counter++; + } + commandSender.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &4Killed " + counter + " Elite " + entityType.toString() + ".")); + } else if (SuperMobProperties.superMobTypeList.contains(entityType)) { + int counter = 0; + for (LivingEntity superMobEntity : EntityTracker.getSuperMobs()) { + if (!superMobEntity.getType().equals(entityType)) continue; + superMobEntity.remove(); + counter++; + } + commandSender.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &4Killed " + counter + " Super " + entityType.toString() + ".")); + } else + commandSender.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &cNot a valid entity type for EliteMobs!")); + } + + public static void radiusKillAggressiveMobs(Player player, int radius) { + int counter = 0; + for (Entity entity : player.getNearbyEntities(radius, radius, radius)) { + EliteEntity eliteEntity = EntityTracker.getEliteMobEntity(entity); + if (eliteEntity != null) + eliteEntity.remove(RemovalReason.REMOVE_COMMAND); + } + player.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &4Killed " + counter + " Elite Mobs.")); + } + + public static void radiusKillPassiveMobs(Player player, int radius) { + int counter = 0; + for (Entity entity : player.getNearbyEntities(radius, radius, radius)) + if (EntityTracker.isSuperMob(entity)) { + entity.remove(); + counter++; + } + player.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &4Killed " + counter + " Super Mobs.")); + } + + public static void radiusKillSpecificMobs(Player player, EntityType entityType, int radius) { + int counter = 0; + for (Entity entity : player.getNearbyEntities(radius, radius, radius)) { + if (entity.getType().equals(entityType) && (EntityTracker.isEliteMob(entity))) { + ((EliteEntity) entity).remove(RemovalReason.KILL_COMMAND); + counter++; + } else if (entity.getType().equals(entityType) && EntityTracker.isSuperMob(entity)) { + EntityTracker.unregister(entity, RemovalReason.KILL_COMMAND); + counter++; + } + } + player.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &4Killed " + counter + " Elite Mobs.")); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/admin/LootCommand.java b/src/main/java/com/magmaguy/elitemobs/commands/admin/LootCommand.java new file mode 100644 index 000000000..45f7f6872 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/commands/admin/LootCommand.java @@ -0,0 +1,36 @@ +package com.magmaguy.elitemobs.commands.admin; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +/** + * Created by MagmaGuy on 01/05/2017. + */ +public class LootCommand { + + public static void get(Player player, String args1) { + CustomItem customItem = CustomItem.getCustomItem(args1); + if (customItem == null) { + player.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &cFile name " + args1 + " &cis not a valid custom item file name!")); + return; + } + player.getInventory().addItem(customItem.generateDefaultsItemStack(player, false, null)); + } + + public static void give(CommandSender commandSender, String playerString, String args1) { + CustomItem customItem = CustomItem.getCustomItem(args1); + if (customItem == null) { + commandSender.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &cFile name " + args1 + " &cis not a valid custom item file name!")); + return; + } + Player player = Bukkit.getPlayer(playerString); + if (player == null) + commandSender.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &cTried to give item to invalid player!")); + else + player.getInventory().addItem(customItem.generateDefaultsItemStack(player, false, null)); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/admin/NPCCommands.java b/src/main/java/com/magmaguy/elitemobs/commands/admin/NPCCommands.java new file mode 100644 index 000000000..ee1065718 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/commands/admin/NPCCommands.java @@ -0,0 +1,44 @@ +package com.magmaguy.elitemobs.commands.admin; + +import com.magmaguy.elitemobs.api.internal.RemovalReason; +import com.magmaguy.elitemobs.config.npcs.NPCsConfig; +import com.magmaguy.elitemobs.config.npcs.NPCsConfigFields; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.npcs.NPCEntity; +import com.magmaguy.elitemobs.utils.Round; +import org.bukkit.Location; +import org.bukkit.entity.Player; + +public class NPCCommands { + + public static void set(Player player, String npcFileName) { + + NPCsConfigFields npCsConfigFields = NPCsConfig.getNpcEntities().get(npcFileName); + if (npCsConfigFields == null) { + player.sendMessage("[EliteMobs] Invalid NPC filename."); + return; + } + + Location playerLocation = player.getLocation(); + + String location = playerLocation.getWorld().getName() + "," + + Round.twoDecimalPlaces(playerLocation.getX()) + "," + + Round.twoDecimalPlaces(playerLocation.getY()) + "," + + Round.twoDecimalPlaces(playerLocation.getZ()) + "," + + Round.twoDecimalPlaces(playerLocation.getYaw()) + "," + + Round.twoDecimalPlaces(playerLocation.getPitch()); + + try { + for (NPCEntity npcEntity : EntityTracker.getNpcEntities().values()) + if (npcEntity.npCsConfigFields.equals(npCsConfigFields)) + npcEntity.remove(RemovalReason.REMOVE_COMMAND); + } catch (Exception ex) { + } + + npCsConfigFields.setEnabled(true); + npCsConfigFields.setLocation(location); + new NPCEntity(npCsConfigFields); + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/admin/RelativeCoordinatesCommand.java b/src/main/java/com/magmaguy/elitemobs/commands/admin/RelativeCoordinatesCommand.java new file mode 100644 index 000000000..f7b52ca3c --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/commands/admin/RelativeCoordinatesCommand.java @@ -0,0 +1,44 @@ +package com.magmaguy.elitemobs.commands.admin; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.dungeons.Minidungeon; +import com.magmaguy.elitemobs.powerstances.GenericRotationMatrixMath; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.util.Vector; + +public class RelativeCoordinatesCommand { + public static void get(Player player, String minidungeonString) { + + Minidungeon minidungeon = Minidungeon.getMinidungeons().get(minidungeonString); + if (minidungeon == null) { + player.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &4Minidungeons name " + minidungeonString + " &4isn't valid!")); + return; + } + + if (!minidungeon.isInstalled()) { + player.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &4Minidungeon isn't installed! Can't get the relative location for uninstalled Minidungeons!")); + return; + } + + Location anchorpoint = minidungeon.getDungeonPackagerConfigFields().getAnchorPoint(); + + if (anchorpoint == null) { + player.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &4Something went wrong and made the anchor point not valid!")); + return; + } + + Vector relativeVector = player.getLocation().clone().subtract(anchorpoint).toVector(); + if (minidungeon.getDungeonPackagerConfigFields().getRotation() != 0) + GenericRotationMatrixMath.rotateVectorYAxis(minidungeon.getDungeonPackagerConfigFields().getRotation(), anchorpoint, relativeVector); + + String relativePosition = relativeVector.getBlockX() + ", " + + relativeVector.getBlockY() + ", " + + relativeVector.getBlockZ(); + + player.sendMessage(ChatColorConverter.convert( + "[EliteMobs] Relative position to anchor point of " + minidungeon.getDungeonPackagerConfigFields().getName() + ": " + relativePosition)); + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/admin/ReloadCommand.java b/src/main/java/com/magmaguy/elitemobs/commands/admin/ReloadCommand.java new file mode 100644 index 000000000..d29dc169a --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/commands/admin/ReloadCommand.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.commands.admin; + +import com.magmaguy.elitemobs.MetadataHandler; +import org.bukkit.command.CommandSender; + +public class ReloadCommand { + public static void reload(CommandSender commandSender) { + MetadataHandler.PLUGIN.onDisable(); + MetadataHandler.PLUGIN.onLoad(); + MetadataHandler.PLUGIN.onEnable(); + commandSender.sendMessage("[EliteMobs] Reload attempted. This may not 100% work. Restart instead if it didn't!!"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/admin/RemoveCommand.java b/src/main/java/com/magmaguy/elitemobs/commands/admin/RemoveCommand.java new file mode 100644 index 000000000..50c0a1eb7 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/commands/admin/RemoveCommand.java @@ -0,0 +1,67 @@ +package com.magmaguy.elitemobs.commands.admin; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.api.internal.RemovalReason; +import com.magmaguy.elitemobs.config.dungeonpackager.DungeonPackagerConfigFields; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import com.magmaguy.elitemobs.mobconstructor.custombosses.RegionalBossEntity; +import com.magmaguy.elitemobs.npcs.NPCEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; + +import java.util.HashSet; +import java.util.Set; +import java.util.UUID; + +public class RemoveCommand { + private static final Set removingPlayers = new HashSet<>(); + + private RemoveCommand() { + } + + public static void remove(Player player) { + if (removingPlayers.contains(player.getUniqueId())) { + player.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &aYou are no longer removing elites!")); + removingPlayers.remove(player.getUniqueId()); + } else { + removingPlayers.add(player.getUniqueId()); + player.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &cYou are now removing elites when you punch them! Run &a/em remove &cagain to stop removing elites!")); + } + } + + public static class RemoveCommandEvents implements Listener { + @EventHandler(priority = EventPriority.LOWEST) + public void removeEliteEntity(EntityDamageByEntityEvent event) { + if (!removingPlayers.contains(event.getDamager().getUniqueId())) return; + EliteEntity eliteEntity = EntityTracker.getEliteMobEntity(event.getEntity()); + if (eliteEntity == null) return; + if (eliteEntity instanceof RegionalBossEntity) + event.getDamager().sendMessage(ChatColorConverter.convert( + "&8[EliteMobs] &cRemoved a spawn location for boss " + + ((RegionalBossEntity) eliteEntity).getCustomBossesConfigFields().getFilename())); + if (eliteEntity instanceof RegionalBossEntity && + ((CustomBossEntity) eliteEntity).getMinidungeon() != null && + ((CustomBossEntity) eliteEntity).getMinidungeon().getDungeonPackagerConfigFields().getDungeonLocationType() + .equals(DungeonPackagerConfigFields.DungeonLocationType.SCHEMATIC)) + ((CustomBossEntity) eliteEntity).getMinidungeon().removeRelativeLocation((RegionalBossEntity) eliteEntity); + eliteEntity.remove(RemovalReason.REMOVE_COMMAND); + event.setCancelled(true); + } + + @EventHandler(priority = EventPriority.LOWEST) + public void removeNPC(EntityDamageByEntityEvent event) { + if (!removingPlayers.contains(event.getDamager().getUniqueId())) return; + NPCEntity npcEntity = EntityTracker.getNPCEntity(event.getEntity()); + if (npcEntity == null) return; + npcEntity.remove(RemovalReason.REMOVE_COMMAND); + event.setCancelled(true); + } + } + +} + diff --git a/src/main/java/com/magmaguy/elitemobs/commands/admin/SimLootCommand.java b/src/main/java/com/magmaguy/elitemobs/commands/admin/SimLootCommand.java new file mode 100644 index 000000000..8b0d37391 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/commands/admin/SimLootCommand.java @@ -0,0 +1,56 @@ +package com.magmaguy.elitemobs.commands.admin; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.config.ItemSettingsConfig; +import com.magmaguy.elitemobs.items.EliteItemLore; +import com.magmaguy.elitemobs.items.LootTables; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +/** + * Created by MagmaGuy on 08/06/2017. + */ +public class SimLootCommand { + public static void runMultipleTimes(Player player, int level, int timesToRun) { + for (int i = 0; i < timesToRun; i++) + run(player, level); + } + + public static void runMultipleTimes(CommandSender player, int level, int timesToRun, String playerName) { + Player targetPlayer = Bukkit.getPlayer(playerName); + if (targetPlayer == null) { + player.sendMessage(ChatColor.RED + "[EliteMobs] Could not send item to player " + playerName + " - player with this name was not found!"); + return; + } + for (int i = 0; i < timesToRun; i++) + run(targetPlayer, level); + player.sendMessage("[EliteMobs] Finished running simulation command for player " + playerName + " " + timesToRun + " times at level " + level + " ."); + } + + public static void run(Player player, int level) { + try { + ItemStack itemStack = LootTables.generateLoot(level, player.getLocation(), player); + if (itemStack == null) + player.sendMessage(ChatColorConverter.convert(ItemSettingsConfig.getSimlootMessageFailure())); + else { + EliteItemLore eliteItemLore = new EliteItemLore(itemStack, false); + player.sendMessage(ChatColorConverter.convert(ItemSettingsConfig.getSimlootMessageSuccess().replace("$itemName", eliteItemLore.getItemStack().getItemMeta().getDisplayName()))); + } + } catch (Exception ex) { + player.sendMessage(ChatColorConverter.convert(ItemSettingsConfig.getSimlootMessageFailure())); + } + } + + public static void run(CommandSender player, int level, String playerName) { + Player targetPlayer = Bukkit.getPlayer(playerName); + if (targetPlayer == null) { + player.sendMessage(ChatColor.RED + "[EliteMobs] Could not send item to player " + playerName + " - player with this name was not found!"); + return; + } + run(targetPlayer, level); + player.sendMessage("[EliteMobs] Finished running simulation command for player " + playerName + " at level " + level + " ."); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/admin/StatsCommand.java b/src/main/java/com/magmaguy/elitemobs/commands/admin/StatsCommand.java new file mode 100644 index 000000000..a8f0725b9 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/commands/admin/StatsCommand.java @@ -0,0 +1,108 @@ +package com.magmaguy.elitemobs.commands.admin; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.EliteMobs; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.adventurersguild.GuildRank; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.custombosses.RegionalBossEntity; +import com.magmaguy.elitemobs.playerdata.ElitePlayerInventory; +import com.magmaguy.elitemobs.utils.Round; +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; + +import java.util.HashMap; + +/** + * Created by MagmaGuy on 01/05/2017. + */ +public class StatsCommand { + + public static void statsHandler(CommandSender commandSender) { + + int aggressiveCount = 0; + int passiveCount = 0; + + HashMap entitiesCounted = new HashMap<>(); + + for (World world : EliteMobs.validWorldList) + for (LivingEntity livingEntity : world.getLivingEntities()) + if (EntityTracker.isEliteMob(livingEntity)) { + aggressiveCount++; + if (!entitiesCounted.containsKey(livingEntity.getType())) + entitiesCounted.put(livingEntity.getType(), 1); + else + entitiesCounted.put(livingEntity.getType(), entitiesCounted.get(livingEntity.getType()) + 1); + } else if (EntityTracker.isSuperMob(livingEntity)) { + passiveCount++; + if (!entitiesCounted.containsKey(livingEntity.getType())) + entitiesCounted.put(livingEntity.getType(), 1); + else + entitiesCounted.put(livingEntity.getType(), entitiesCounted.get(livingEntity.getType()) + 1); + } + + StringBuilder breakdownString = new StringBuilder("&2Breakdown: &a"); + + for (EntityType entityType : entitiesCounted.keySet()) { + breakdownString.append(entitiesCounted.get(entityType)).append(" ").append(entityType).append("&2, &a"); + } + + double highestThreat = 0; + String highestThreatUser = ""; + double threatAverage = 0; + int highestGuildRank = 0; + String highestGuildUser = ""; + double guildRankAverage = 0; + Player highestGuildRankPlayer = null; + for (Player player : Bukkit.getOnlinePlayers()) { + double currentTier = ElitePlayerInventory.playerInventories.get(player.getUniqueId()).getFullPlayerTier(true); + threatAverage += currentTier; + int currentGuildRank = GuildRank.getActiveGuildRank(player); + guildRankAverage += currentGuildRank; + if (currentTier > highestThreat) { + highestThreat = currentTier; + highestThreatUser = player.getDisplayName(); + } + if (currentGuildRank > highestGuildRank) { + highestGuildRankPlayer = player; + highestGuildRank = currentGuildRank; + highestGuildUser = player.getDisplayName(); + } + } + threatAverage /= Bukkit.getOnlinePlayers().size(); + guildRankAverage /= Bukkit.getOnlinePlayers().size(); + + commandSender.sendMessage(ChatColorConverter.convert( + "§5§m-----------------------------------------------------")); + commandSender.sendMessage(ChatColorConverter.convert( + "&7[EM] §a§lEliteMobs v. " + Bukkit.getPluginManager().getPlugin(MetadataHandler.ELITE_MOBS).getDescription().getVersion() + " stats:")); + commandSender.sendMessage(ChatColorConverter.convert( + "&7[EM] &2There are currently §l§6" + (aggressiveCount + passiveCount) + " §f§2EliteMobs mobs entities in the world, of which &a" + + aggressiveCount + " &2are Elite Mobs and &a" + passiveCount + " &2are Super Mobs.")); + commandSender.sendMessage(ChatColorConverter.convert(breakdownString.toString())); + if (highestGuildRankPlayer == null) return; + commandSender.sendMessage(ChatColorConverter.convert( + "&7[EM] &2Highest online threat tier: &a" + highestThreatUser + " &2at total threat tier &a" + highestThreat)); + commandSender.sendMessage(ChatColorConverter.convert( + "&7[EM] &2Average threat tier: &a" + Round.twoDecimalPlaces(threatAverage))); + commandSender.sendMessage(ChatColorConverter.convert( + "&7[EM] &2Highest adventurer's guild tier: &a" + highestGuildUser + " &2at guild rank &a" + GuildRank.getRankName(GuildRank.getGuildPrestigeRank(highestGuildRankPlayer), highestGuildRank) + " &2(&a" + highestGuildRank + "&2)")); + commandSender.sendMessage(ChatColorConverter.convert( + "&7[EM] &2Average guild rank: &a" + Round.twoDecimalPlaces(guildRankAverage))); + commandSender.sendMessage(ChatColorConverter.convert( + "§5§m-----------------------------------------------------")); + commandSender.sendMessage("Tracked boss count: " + EntityTracker.getEliteMobEntities().size()); + commandSender.sendMessage("Tracked NPC count: " + EntityTracker.getNpcEntities().size()); + commandSender.sendMessage("Tracked visual item count: " + EntityTracker.getItemVisualEffects().size()); + int loadedCounter = 0; + for (RegionalBossEntity regionalBossEntity : RegionalBossEntity.getRegionalBossEntities()) + if (regionalBossEntity.isValid()) + loadedCounter++; + commandSender.sendMessage(ChatColorConverter.convert("&7[EM] &2There are &c" + RegionalBossEntity.getRegionalBossEntities().size() + " &2Regional Bosses installed, of which &c" + loadedCounter + " &2are currently loaded.")); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/VersionHandler.java b/src/main/java/com/magmaguy/elitemobs/commands/admin/VersionCommand.java similarity index 68% rename from src/main/java/com/magmaguy/elitemobs/commands/VersionHandler.java rename to src/main/java/com/magmaguy/elitemobs/commands/admin/VersionCommand.java index a3962ffb4..b32342c74 100644 --- a/src/main/java/com/magmaguy/elitemobs/commands/VersionHandler.java +++ b/src/main/java/com/magmaguy/elitemobs/commands/admin/VersionCommand.java @@ -1,17 +1,18 @@ -package com.magmaguy.elitemobs.commands; +package com.magmaguy.elitemobs.commands.admin; import com.magmaguy.elitemobs.MetadataHandler; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.CommandSender; -public class VersionHandler { +public class VersionCommand { - public static void versionCommand(CommandSender commandSender, String[] args){ + private VersionCommand() { + } + public static void getVersion(CommandSender commandSender) { commandSender.sendMessage(ChatColor.DARK_GREEN + "[EliteMobs]" + ChatColor.WHITE + " version " + ChatColor.GREEN + Bukkit.getPluginManager().getPlugin(MetadataHandler.ELITE_MOBS).getDescription().getVersion()); - } } diff --git a/src/main/java/com/magmaguy/elitemobs/commands/combat/CheckTierCommand.java b/src/main/java/com/magmaguy/elitemobs/commands/combat/CheckTierCommand.java new file mode 100644 index 000000000..1dfce03ab --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/commands/combat/CheckTierCommand.java @@ -0,0 +1,27 @@ +package com.magmaguy.elitemobs.commands.combat; + +import com.magmaguy.elitemobs.adventurersguild.GuildRank; +import com.magmaguy.elitemobs.config.commands.premade.CheckTierConfig; +import com.magmaguy.elitemobs.playerdata.ElitePlayerInventory; +import org.bukkit.entity.Player; + +public class CheckTierCommand { + + public CheckTierCommand(Player player) { + + double gearTier = ElitePlayerInventory.playerInventories.get(player.getUniqueId()).getFullPlayerTier(true); + double guildRank = GuildRank.getActiveGuildRank(player); + if (guildRank == 0) + guildRank = -10; + else + guildRank--; + guildRank = (guildRank * 0.2); + + player.sendMessage(CheckTierConfig.message1.replace("$tier", gearTier + "")); + player.sendMessage(CheckTierConfig.message2.replace("$tier", guildRank + "")); + player.sendMessage(CheckTierConfig.message3.replace("$tier", (gearTier + guildRank) + "")); + + } + + +} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/guiconfig/SignatureItem.java b/src/main/java/com/magmaguy/elitemobs/commands/guiconfig/SignatureItem.java deleted file mode 100644 index 2707d80ca..000000000 --- a/src/main/java/com/magmaguy/elitemobs/commands/guiconfig/SignatureItem.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.commands.guiconfig; - -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.SkullMeta; - -import java.util.ArrayList; -import java.util.List; - -/** - * Created by MagmaGuy on 12/11/2017. - */ -public class SignatureItem { - - public static final ItemStack SIGNATURE_ITEMSTACK = setSignatureItem(); - - private static ItemStack setSignatureItem() { - - ItemStack signature = new ItemStack(Material.SKULL_ITEM, 1, (short) 3); - SkullMeta signatureSkullMeta = (SkullMeta) signature.getItemMeta(); - signatureSkullMeta.setOwner("magmaguy"); - signatureSkullMeta.setDisplayName("EliteMobs by MagmaGuy"); - List signatureList = new ArrayList<>(); - signatureList.add("Support the plugins you enjoy!"); - signatureSkullMeta.setLore(signatureList); - signature.setItemMeta(signatureSkullMeta); - - return signature; - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/guild/AdventurersGuildCommand.java b/src/main/java/com/magmaguy/elitemobs/commands/guild/AdventurersGuildCommand.java new file mode 100644 index 000000000..412016c15 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/commands/guild/AdventurersGuildCommand.java @@ -0,0 +1,80 @@ +package com.magmaguy.elitemobs.commands.guild; + +import com.magmaguy.elitemobs.adventurersguild.GuildRankMenuHandler; +import com.magmaguy.elitemobs.api.PlayerPreTeleportEvent; +import com.magmaguy.elitemobs.api.PlayerTeleportEvent; +import com.magmaguy.elitemobs.config.AdventurersGuildConfig; +import com.magmaguy.elitemobs.config.CombatTagConfig; +import com.magmaguy.elitemobs.utils.EventCaller; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.Player; + +public class AdventurersGuildCommand { + + public static void adventurersGuildCommand(Player player) { + if (adventurersGuildTeleport(player)) return; + if (player.hasPermission("elitemobs.adventurersguild.command")) + GuildRankMenuHandler.initializeGuildRankMenu(player); + else + player.sendMessage("Missing permission: elitemobs.adventurersguild.command / elitemobs.adventurersguild.teleport"); + } + + public static boolean adventurersGuildTeleport(Player player) { + if (!player.hasPermission("elitemobs.adventurersguild.teleport")) return false; + if (!AdventurersGuildConfig.isAgTeleport()) return false; + if (AdventurersGuildConfig.getGuildWorldLocation() == null) + defineTeleportLocation(); + if (AdventurersGuildConfig.getGuildWorldLocation() == null) return false; + + if (CombatTagConfig.isEnableCombatTag()) + new EventCaller(new PlayerPreTeleportEvent(player, AdventurersGuildConfig.getGuildWorldLocation())); + else + new EventCaller(new PlayerTeleportEvent(player, AdventurersGuildConfig.getGuildWorldLocation())); + + return true; + + } + + public static Location defineTeleportLocation() { + + for (World world : Bukkit.getWorlds()) + if (world.getName().equals(AdventurersGuildConfig.getGuildWorldName())) { + double x = 0, y = 0, z = 0; + float yaw = 0, pitch = 0; + int counter = 0; + + for (String substring : AdventurersGuildConfig.getGuildLocationString().split(",")) { + switch (counter) { + case 0: + x = Double.parseDouble(substring); + break; + case 1: + y = Double.parseDouble(substring); + break; + case 2: + z = Double.parseDouble(substring); + break; + case 3: + yaw = Float.parseFloat(substring); + break; + case 4: + pitch = Float.parseFloat(substring); + break; + } + counter++; + + } + + Location location = new Location(world, x, y, z, yaw, pitch); + AdventurersGuildConfig.setGuildWorldLocation(location); + return location; + + } + + return null; + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/quests/QuestCommand.java b/src/main/java/com/magmaguy/elitemobs/commands/quests/QuestCommand.java new file mode 100644 index 000000000..1c7432204 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/commands/quests/QuestCommand.java @@ -0,0 +1,60 @@ +package com.magmaguy.elitemobs.commands.quests; + +import com.magmaguy.elitemobs.playerdata.database.PlayerData; +import com.magmaguy.elitemobs.quests.CustomQuest; +import com.magmaguy.elitemobs.quests.Quest; +import com.magmaguy.elitemobs.quests.QuestTracking; +import com.magmaguy.elitemobs.quests.playercooldowns.PlayerQuestCooldowns; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.UUID; + +public class QuestCommand { + + private QuestCommand() { + } + + public static void completeQuest(String questID, Player player) { + try { + Quest.completeQuest(UUID.fromString(questID), player); + } catch (Exception ex) { + player.sendMessage(ChatColor.RED + "[EliteMobs] Invalid quest ID!"); + } + } + + // /em quest join questFilename + public static void joinQuest(String questID, Player player) { + CustomQuest.startQuest(questID, player); + } + + public static void trackQuest(String questID, Player player) { + QuestTracking.toggleTracking(player, questID); + } + + // /em quest leave questFilename + public static void leaveQuest(Player player, String questID) { + Quest.stopPlayerQuest(player, questID); + } + + public static void resetQuests(CommandSender commandSender, String playerString) { + Player player = Bukkit.getPlayer(playerString); + if (player == null) { + commandSender.sendMessage("[EliteMobs] Error - player name not valid!"); + return; + } + PlayerQuestCooldowns.resetPlayerQuestCooldowns(player); + commandSender.sendMessage("[EliteMobs] Successfully reset quests for player " + playerString); + } + + public static void completeQuest(Player player){ + for (Quest quest : new ArrayList(PlayerData.getQuests(player.getUniqueId()))){ + quest.getQuestObjectives().setForceOver(true); + Quest.completeQuest(quest.getQuestID(), player); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/setup/SetupMenu.java b/src/main/java/com/magmaguy/elitemobs/commands/setup/SetupMenu.java new file mode 100644 index 000000000..9267b2c3c --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/commands/setup/SetupMenu.java @@ -0,0 +1,275 @@ +package com.magmaguy.elitemobs.commands.setup; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.api.PlayerTeleportEvent; +import com.magmaguy.elitemobs.commands.guild.AdventurersGuildCommand; +import com.magmaguy.elitemobs.config.AdventurersGuildConfig; +import com.magmaguy.elitemobs.dungeons.Minidungeon; +import com.magmaguy.elitemobs.thirdparty.worldguard.WorldGuardCompatibility; +import com.magmaguy.elitemobs.utils.DiscordLinks; +import com.magmaguy.elitemobs.utils.EventCaller; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import com.magmaguy.elitemobs.utils.WarningMessage; +import com.magmaguy.elitemobs.worlds.CustomWorldLoading; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.inventory.Inventory; + +import java.util.*; + +public class SetupMenu { + + public static Map setupMenus = new HashMap<>(); + + Inventory inventory; + Player player; + ArrayList validSlots = new ArrayList<>(Arrays.asList(10, 11, 12, 13, 14, 15, 16, 19, 20, 21, 22, 23, + 24, 25, 28, 29, 30, 31, 32, 33, 34, 37, 38, 39, 40, 41, 42, 43)); + HashMap minidungeonHashMap = new HashMap<>(); + boolean adventurersGuildIsDownloaded = false; + + public SetupMenu(Player player) { + this.inventory = Bukkit.createInventory(player, 54, "Setup menu"); + this.player = player; + //reserve adventurer's guild + adventurersGuildWorldStatus(); + //iterate through dungeons + dungeonStatuses(); + setupMenus.put(inventory, this); + player.openInventory(inventory); + } + + private void adventurersGuildWorldStatus() { + String state = "Adventurer's Guild world is"; + String lore; + Material material; + if (CustomWorldLoading.adventurersGuildWorldExists()) + adventurersGuildIsDownloaded = true; + + if (!adventurersGuildIsDownloaded) { + material = Material.RED_STAINED_GLASS_PANE; + lore = ChatColor.RED + "Not downloaded! Click to download!"; + } else { + if (!AdventurersGuildConfig.isGuildWorldIsEnabled()) { + material = Material.ORANGE_STAINED_GLASS_PANE; + lore = ChatColor.RED + "Not setup! Click to install!"; + } else { + material = Material.GREEN_STAINED_GLASS_PANE; + lore = ChatColor.GREEN + "Working correctly! Click to uninstall!"; + } + } + inventory.setItem(validSlots.get(0), ItemStackGenerator.generateItemStack(material, state, new ArrayList<>(Arrays.asList(lore)))); + } + + private void dungeonStatuses() { + //continue counting from used inventory slots + int counter = 1; + for (Minidungeon minidungeon : Minidungeon.getMinidungeons().values()) { + + if (!Bukkit.getPluginManager().isPluginEnabled("WorldGuard")) + inventory.setItem(validSlots.get(counter), ItemStackGenerator.generateItemStack(Material.RED_STAINED_GLASS_PANE, + ChatColorConverter.convert("&4You need WorldGuard to install Minidungeons correctly!"))); + else + + switch (minidungeon.getDungeonPackagerConfigFields().getDungeonLocationType()) { + case WORLD: + addWorldDungeon(minidungeon, counter); + break; + case SCHEMATIC: + addSchematicDungeon(minidungeon, counter); + break; + default: + new WarningMessage("Dungeon " + minidungeon.getDungeonPackagerConfigFields().getFilename() + " does not have a valid location type and therefore can't be set up automatically!"); + break; + } + minidungeonHashMap.put(validSlots.get(counter), minidungeon); + counter++; + + } + } + + private void addWorldDungeon(Minidungeon minidungeon, int counter) { + + String itemName = minidungeon.getDungeonPackagerConfigFields().getName(); + List lore = new ArrayList<>(); + + addSize(lore, minidungeon); + //boss count can't be calculated ahead of time here, unfortunately + addInstallationString(lore, minidungeon); + + lore = ChatColorConverter.convert(lore); + inventory.setItem(validSlots.get(counter), ItemStackGenerator.generateItemStack(getMaterial(minidungeon), itemName, lore)); + } + + private void addSchematicDungeon(Minidungeon minidungeon, int counter) { + if (!Bukkit.getPluginManager().isPluginEnabled("WorldEdit")) { + inventory.setItem(validSlots.get(counter), ItemStackGenerator.generateItemStack(Material.RED_STAINED_GLASS_PANE, ChatColorConverter.convert("&4You need WorldEdit to use this!"))); + return; + } + + String itemName = minidungeon.getDungeonPackagerConfigFields().getName(); + + List lore = new ArrayList<>(); + if (minidungeon.getDungeonPackagerConfigFields().getCustomInfo() != null) + lore.addAll(minidungeon.getDungeonPackagerConfigFields().getCustomInfo()); + addSize(lore, minidungeon); + addBossCount(lore, minidungeon); + addInstallationString(lore, minidungeon); + + lore = ChatColorConverter.convert(lore); + + inventory.setItem(validSlots.get(counter), ItemStackGenerator.generateItemStack(getMaterial(minidungeon), itemName, lore)); + } + + private Material getMaterial(Minidungeon minidungeon) { + if (minidungeon.isInstalled()) + return Material.GREEN_STAINED_GLASS_PANE; + if (minidungeon.isDownloaded() && minidungeon.isBossesDownloaded()) + return Material.YELLOW_STAINED_GLASS_PANE; + if (minidungeon.isDownloaded() && !minidungeon.isBossesDownloaded()) + return Material.ORANGE_STAINED_GLASS_PANE; + return Material.RED_STAINED_GLASS_PANE; + } + + private void addSize(List lore, Minidungeon minidungeon) { + lore.add("&fSize: " + minidungeon.getDungeonPackagerConfigFields().getDungeonSizeCategory().toString()); + } + + private void addBossCount(List lore, Minidungeon minidungeon) { + try { + lore.add("&fRegional boss count: " + minidungeon.getRelativeBossLocations().getBossCount()); + } catch (Exception ex) { + //todo: fix this + //new WarningMessage("Failed to determine regional boss count! Are the relative dungeon locations correct?"); + } + } + + private void addInstallationString(List lore, Minidungeon minidungeon) { + String status = "&fStatus: "; + if (minidungeon.isInstalled()) { + lore.add(status + "&2already installed!"); + lore.add("&cClick to uninstall!"); + return; + } + if (!minidungeon.isDownloaded()) { + lore.add(status + "&4not downloaded!"); + lore.add("&4Download this at"); + lore.add("&9" + minidungeon.getDungeonPackagerConfigFields().getDownloadLink() + " &f!"); + return; + } + if (!minidungeon.isBossesDownloaded()) { + lore.add("&4Minidungeon boss files are not downloaded!"); + lore.add("&4Download this at"); + lore.add("&9" + minidungeon.getDungeonPackagerConfigFields().getDownloadLink() + " &f!"); + return; + } + lore.add(status + "&aready to install!"); + lore.add("&2Click to install!"); + } + + + public static class SetupMenuListeners implements Listener { + @EventHandler(ignoreCancelled = true) + public void onInventoryInteraction(InventoryClickEvent event) { + SetupMenu setupMenu = setupMenus.get(event.getInventory()); + if (setupMenu == null) return; + event.setCancelled(true); + Player player = (Player) event.getWhoClicked(); + //for permissions mode + //for adventurer's guild world + if (event.getSlot() == 10) { + //case where Adventurer's Guild Hub isn't downloaded + if (!setupMenu.adventurersGuildIsDownloaded) { + player.closeInventory(); + player.sendMessage("----------------------------------------------------"); + player.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &2Adventurer's Guild Hub download link: https://magmaguy.itch.io/")); + player.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &aOnce downloaded, follow this setup guide: &9&nhttps://youtu.be/boRg2X4qhw4")); + player.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &2Need help? " + DiscordLinks.mainLink)); + player.sendMessage("----------------------------------------------------"); + } else { + //case for install + if (!AdventurersGuildConfig.isGuildWorldIsEnabled()) { + try { + player.closeInventory(); + player.sendMessage("----------------------------------------------------"); + CustomWorldLoading.startupWorldInitialization(); + AdventurersGuildCommand.defineTeleportLocation(); + AdventurersGuildConfig.toggleGuildInstall(); + if (Bukkit.getPluginManager().isPluginEnabled("WorldGuard")) { + WorldGuardCompatibility.protectWorldMinidugeonArea(AdventurersGuildCommand.defineTeleportLocation()); + player.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &2The Adventurer's Guild Hub has been protected against griefing and mob spawning (among others)!")); + } else + player.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &4It is highly recommended you install WorldGuard to protect the Adventurer's Guild Hub World! Reinstall the hub through /em setup after installing WorldGuard in order to automatically protect the area!")); + PlayerTeleportEvent playerTeleportEvent = new PlayerTeleportEvent(player, AdventurersGuildConfig.getGuildWorldLocation()); + new EventCaller(playerTeleportEvent); + if (!playerTeleportEvent.isCancelled()) + player.teleport(AdventurersGuildConfig.getGuildWorldLocation()); + player.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &2Successfully installed Adventurer's Guild Hub! Do &a/ag &2to go there and talk to the transporter or open the Teleports page in /em to go back!")); + player.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &2Need help? &9&n" + DiscordLinks.mainLink)); + player.sendMessage("----------------------------------------------------"); + } catch (Exception e) { + player.closeInventory(); + player.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &4Failed to install Adventurer's Guild Hub! Report this to the dev!")); + player.sendMessage("----------------------------------------------------"); + e.printStackTrace(); + } + //case for uninstall + } else { + try { + player.closeInventory(); + Bukkit.unloadWorld(AdventurersGuildConfig.getGuildWorldLocation().getWorld(), true); + AdventurersGuildConfig.setGuildWorldLocation(null); + AdventurersGuildConfig.toggleGuildInstall(); + player.sendMessage("----------------------------------------------------"); + player.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &2Successfully uninstalled Adventurer's Guild Hub!")); + player.sendMessage("----------------------------------------------------"); + } catch (Exception e) { + player.closeInventory(); + player.sendMessage("----------------------------------------------------"); + player.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &4Failed to uninstall Adventurer's Guild Hub! Report this to the dev!")); + player.sendMessage("----------------------------------------------------"); + e.printStackTrace(); + } + } + } + return; + } + //for minidungeons + Minidungeon minidungeon = setupMenu.minidungeonHashMap.get(event.getSlot()); + if (minidungeon != null) { + if (!minidungeon.isDownloaded()) { + player.sendMessage("----------------------------------------------------"); + player.sendMessage(ChatColorConverter.convert("&4Download this at &9" + minidungeon.getDungeonPackagerConfigFields().getDownloadLink() + " &4!")); + player.sendMessage("----------------------------------------------------"); + player.closeInventory(); + setupMenus.remove(event.getInventory()); + return; + } + if (!minidungeon.isBossesDownloaded()) { + player.sendMessage("----------------------------------------------------"); + player.sendMessage(ChatColorConverter.convert("&4You are missing the boss files for this minidungeon!")); + player.sendMessage(ChatColorConverter.convert("&4Download this at &9" + minidungeon.getDungeonPackagerConfigFields().getDownloadLink() + " &4!")); + player.sendMessage("----------------------------------------------------"); + player.closeInventory(); + setupMenus.remove(event.getInventory()); + return; + } + minidungeon.buttonToggleBehavior(player); + setupMenus.remove(event.getInventory()); + player.closeInventory(); + } + } + + @EventHandler(ignoreCancelled = true) + public void onInventoryClose(InventoryCloseEvent event) { + setupMenus.remove(event.getInventory()); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/shops/CustomShopHandler.java b/src/main/java/com/magmaguy/elitemobs/commands/shops/CustomShopHandler.java deleted file mode 100644 index 2a34f505f..000000000 --- a/src/main/java/com/magmaguy/elitemobs/commands/shops/CustomShopHandler.java +++ /dev/null @@ -1,152 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.commands.shops; - -import com.magmaguy.elitemobs.commands.guiconfig.SignatureItem; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.EconomySettingsConfig; -import com.magmaguy.elitemobs.economy.EconomyHandler; -import com.magmaguy.elitemobs.economy.UUIDFilter; -import com.magmaguy.elitemobs.items.CustomItemConstructor; -import com.magmaguy.elitemobs.items.ItemWorthCalculator; -import com.magmaguy.elitemobs.items.ObfuscatedSignatureLoreData; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; - -import java.util.List; -import java.util.Random; - -/** - * Created by MagmaGuy on 20/06/2017. - */ -public class CustomShopHandler implements Listener { - - public static final String SHOP_NAME = ConfigValues.economyConfig.getString(EconomySettingsConfig.CUSTOM_SHOP_NAME); - - public void initializeShop(Player player) { - - Inventory shopInventory = Bukkit.createInventory(player, 54, SHOP_NAME); - - populateShop(shopInventory); - - player.openInventory(shopInventory); - - } - - private void populateShop(Inventory shopInventory) { - - SharedShopElements.shopHeader(shopInventory); - shopContents(shopInventory); - - } - - private static List validSlots = (List) ConfigValues.economyConfig.getList(EconomySettingsConfig.CUSTOM_SHOP_VALID_SLOTS); - - private void shopContents(Inventory shopInventory) { - - //Anything after 8 is populated - Random random = new Random(); - - for (int i : validSlots) { - - int itemEntryIndex = random.nextInt(CustomItemConstructor.customItemList.size()); - - shopInventory.setItem(i, CustomItemConstructor.customItemList.get(itemEntryIndex)); - - } - - } - - @EventHandler - public void onClick(InventoryClickEvent event) { - - if (!SharedShopElements.inventoryNullPointerPreventer(event)) { - - return; - - } - - if (!event.getInventory().getName().equals(SHOP_NAME)) return; - - //reroll loot button - if (event.getCurrentItem().getItemMeta().getDisplayName().equals(SignatureItem.SIGNATURE_ITEMSTACK.getItemMeta().getDisplayName())) { - - populateShop(event.getInventory()); - event.setCancelled(true); - return; - - } - - if (!ObfuscatedSignatureLoreData.obfuscatedSignatureDetector(event.getCurrentItem())) { - - event.setCancelled(true); - return; - - } - - Player player = (Player) event.getWhoClicked(); - ItemStack itemStack = event.getCurrentItem(); - String itemDisplayName = event.getCurrentItem().getItemMeta().getDisplayName(); - - double itemValue = ItemWorthCalculator.determineItemWorth(itemStack); - - //These slots are for buying items - if (validSlots.contains(event.getSlot()) && event.getClickedInventory().getName().equalsIgnoreCase(SHOP_NAME)) { - - boolean inventoryHasFreeSlots = false; - for (ItemStack iteratedStack : player.getInventory()) { - - if (iteratedStack == null) { - - inventoryHasFreeSlots = true; - break; - - } - - } - - if (!inventoryHasFreeSlots) { - - player.sendMessage("Your inventory is full! You can't buy items until you get some free space."); - player.closeInventory(); - - } else if (EconomyHandler.checkCurrency(UUIDFilter.guessUUI(player.getName())) >= itemValue) { - //player has enough money - EconomyHandler.subtractCurrency(UUIDFilter.guessUUI(player.getName()), itemValue); - player.getInventory().addItem(itemStack); - populateShop(event.getInventory()); - - SharedShopElements.buyMessage(player, itemDisplayName, itemValue); - - } else { - - player.closeInventory(); - SharedShopElements.insufficientFundsMessage(player, itemValue); - - } - - } - - event.setCancelled(true); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/shops/ItemSaleEvent.java b/src/main/java/com/magmaguy/elitemobs/commands/shops/ItemSaleEvent.java deleted file mode 100644 index 8d3845a43..000000000 --- a/src/main/java/com/magmaguy/elitemobs/commands/shops/ItemSaleEvent.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.commands.shops; - -import com.magmaguy.elitemobs.economy.EconomyHandler; -import com.magmaguy.elitemobs.economy.UUIDFilter; -import com.magmaguy.elitemobs.items.ItemWorthCalculator; -import com.magmaguy.elitemobs.items.ObfuscatedSignatureLoreData; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.inventory.ItemStack; - -public class ItemSaleEvent implements Listener { - - @EventHandler - public void playerSellEvent(InventoryClickEvent event) { - - if (!SharedShopElements.sellInventoryNullPointerPreventer(event)) { - - return; - - } - - if (!event.getInventory().getName().equals(ShopHandler.SHOP_NAME) && - !event.getInventory().getName().equals(CustomShopHandler.SHOP_NAME)) { - - return; - - } - - if (event.getClickedInventory().getName().equals(ShopHandler.SHOP_NAME) || - event.getClickedInventory().getName().equals(CustomShopHandler.SHOP_NAME)) { - - return; - - } - - if (!ObfuscatedSignatureLoreData.obfuscatedSignatureDetector(event.getCurrentItem())) { - - event.setCancelled(true); - return; - - } - - Player player = (Player) event.getWhoClicked(); - ItemStack itemStack = event.getCurrentItem(); - String itemDisplayName = itemStack.getItemMeta().getDisplayName(); - - double amountDeduced = ItemWorthCalculator.determineResaleWorth(itemStack); - - EconomyHandler.addCurrency(UUIDFilter.guessUUI(player.getName()), amountDeduced); - - if (event.getCurrentItem().getAmount() == 1) { - - event.setCurrentItem(new ItemStack(Material.AIR)); - - } else if (event.getCurrentItem().getAmount() > 1) { - - int newAmount = event.getCurrentItem().getAmount() - 1; - - event.getCurrentItem().setAmount(newAmount); - - } - - SharedShopElements.sellMessage(player, itemDisplayName, amountDeduced); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/shops/SharedShopElements.java b/src/main/java/com/magmaguy/elitemobs/commands/shops/SharedShopElements.java deleted file mode 100644 index 9d9e7a128..000000000 --- a/src/main/java/com/magmaguy/elitemobs/commands/shops/SharedShopElements.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.commands.shops; - -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.commands.guiconfig.SignatureItem; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.EconomySettingsConfig; -import com.magmaguy.elitemobs.economy.EconomyHandler; -import com.magmaguy.elitemobs.economy.UUIDFilter; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.scheduler.BukkitRunnable; - -public class SharedShopElements { - - public static void shopHeader(Inventory shopInventory) { - - ItemStack signature = SignatureItem.SIGNATURE_ITEMSTACK; - - shopInventory.setItem(ConfigValues.economyConfig.getInt(EconomySettingsConfig.SIGNATURE_ITEM_LOCATION_SHOPS), signature); - - } - - public static boolean inventoryNullPointerPreventer(InventoryClickEvent event) { - - //Check if economy is enabled - if (!ConfigValues.economyConfig.getBoolean(EconomySettingsConfig.ENABLE_ECONOMY)) return false; - //Check if current item is valid - if (event.getCurrentItem() == null) return false; - if (event.getCurrentItem().getType().equals(Material.AIR)) return false; - if (event.getCurrentItem().getItemMeta() == null) return false; - return event.getCurrentItem().getItemMeta().hasLore(); - - } - - public static boolean sellInventoryNullPointerPreventer(InventoryClickEvent event) { - - //Check if economy is enabled - if (!ConfigValues.economyConfig.getBoolean(EconomySettingsConfig.ENABLE_ECONOMY)) return false; - //Check if current item is valid - if (event.getCurrentItem() == null) return false; - return !event.getCurrentItem().getType().equals(Material.AIR); - } - - public static void buyMessage(Player player, String itemDisplayName, double itemValue) { - - new BukkitRunnable() { - - @Override - public void run() { - - player.sendMessage(ChatColor.GREEN + "You have bought " + itemDisplayName + " for " + ChatColor.DARK_GREEN + itemValue + " " + ChatColor.GREEN + ConfigValues.economyConfig.getString(EconomySettingsConfig.CURRENCY_NAME)); - player.sendMessage(ChatColor.GREEN + "You have " + ChatColor.DARK_GREEN + EconomyHandler.checkCurrency(UUIDFilter.guessUUI(player.getName())) + " " + ChatColor.GREEN + ConfigValues.economyConfig.getString(EconomySettingsConfig.CURRENCY_NAME)); - - } - - - }.runTaskLater(Bukkit.getPluginManager().getPlugin(MetadataHandler.ELITE_MOBS), 2); - - } - - public static void insufficientFundsMessage(Player player, double itemValue) { - - new BukkitRunnable() { - - @Override - public void run() { - - player.sendMessage(ChatColor.RED + "You don't have enough " + ConfigValues.economyConfig.getString(EconomySettingsConfig.CURRENCY_NAME) + "!"); - player.sendMessage(ChatColor.GREEN + "You have " + ChatColor.DARK_GREEN + EconomyHandler.checkCurrency(UUIDFilter.guessUUI(player.getName())) + " " + ChatColor.GREEN + ConfigValues.economyConfig.getString(EconomySettingsConfig.CURRENCY_NAME)); - player.sendMessage(ChatColor.GREEN + "That item cost " + ChatColor.DARK_GREEN + itemValue + " " + ChatColor.GREEN + ConfigValues.economyConfig.getString(EconomySettingsConfig.CURRENCY_NAME) + "."); - - } - - - }.runTaskLater(Bukkit.getPluginManager().getPlugin(MetadataHandler.ELITE_MOBS), 2); - - player.closeInventory(); - - } - - public static void sellMessage(Player player, String itemDisplayName, double amountDeduced) { - - player.sendMessage("You have sold " + itemDisplayName + " for " + amountDeduced + " " + ConfigValues.economyConfig.getString(EconomySettingsConfig.CURRENCY_NAME)); - - new BukkitRunnable() { - - @Override - public void run() { - - player.sendMessage("You have " + EconomyHandler.checkCurrency(UUIDFilter.guessUUI(player.getName())) + " " + ConfigValues.economyConfig.getString(EconomySettingsConfig.CURRENCY_NAME)); - - } - - - }.runTaskLater(Bukkit.getPluginManager().getPlugin(MetadataHandler.ELITE_MOBS), 2); - - } - - -} diff --git a/src/main/java/com/magmaguy/elitemobs/commands/shops/ShopHandler.java b/src/main/java/com/magmaguy/elitemobs/commands/shops/ShopHandler.java deleted file mode 100644 index 10b24e2e3..000000000 --- a/src/main/java/com/magmaguy/elitemobs/commands/shops/ShopHandler.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.commands.shops; - -import com.magmaguy.elitemobs.commands.guiconfig.SignatureItem; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.EconomySettingsConfig; -import com.magmaguy.elitemobs.economy.EconomyHandler; -import com.magmaguy.elitemobs.economy.UUIDFilter; -import com.magmaguy.elitemobs.items.ItemWorthCalculator; -import com.magmaguy.elitemobs.items.ObfuscatedSignatureLoreData; -import com.magmaguy.elitemobs.items.itemconstructor.ItemConstructor; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; - -import java.util.List; -import java.util.Random; - -/** - * Created by MagmaGuy on 17/06/2017. - */ -public class ShopHandler implements Listener { - - public static final String SHOP_NAME = ConfigValues.economyConfig.getString(EconomySettingsConfig.SHOP_NAME); - - public void initializeShop(Player player) { - - Inventory shopInventory = Bukkit.createInventory(player, 54, SHOP_NAME); - - populateShop(shopInventory); - - player.openInventory(shopInventory); - - } - - private void populateShop(Inventory shopInventory) { - - SharedShopElements.shopHeader(shopInventory); - shopContents(shopInventory); - - } - - private static List validSlots = (List) ConfigValues.economyConfig.getList(EconomySettingsConfig.SHOP_VALID_SLOTS); - - private void shopContents(Inventory shopInventory) { - - Random random = new Random(); - - for (int i : validSlots) { - - int balancedMax = ConfigValues.economyConfig.getInt(EconomySettingsConfig.HIGHEST_PROCEDURALLY_SIMULATED_LOOT) - - ConfigValues.economyConfig.getInt(EconomySettingsConfig.LOWEST_PROCEDURALLY_SIMULATED_LOOT); - int balancedMin = ConfigValues.economyConfig.getInt(EconomySettingsConfig.LOWEST_PROCEDURALLY_SIMULATED_LOOT); - - int randomTier = random.nextInt(balancedMax) + balancedMin; - - shopInventory.setItem(i, ItemConstructor.constructItem(randomTier, null)); - - } - - } - - @EventHandler - public void onClick(InventoryClickEvent event) { - - if (!SharedShopElements.inventoryNullPointerPreventer(event)) - return; - - if (!event.getInventory().getName().equals(SHOP_NAME)) return; - - //reroll loot button - if (event.getCurrentItem().getItemMeta().getDisplayName().equals(SignatureItem.SIGNATURE_ITEMSTACK.getItemMeta().getDisplayName())) { - - populateShop(event.getInventory()); - event.setCancelled(true); - return; - - } - - if (!ObfuscatedSignatureLoreData.obfuscatedSignatureDetector(event.getCurrentItem())) { - - event.setCancelled(true); - return; - - } - - Player player = (Player) event.getWhoClicked(); - ItemStack itemStack = event.getCurrentItem(); - String itemDisplayName = itemStack.getItemMeta().getDisplayName(); - - double itemValue = ItemWorthCalculator.determineItemWorth(itemStack); - - boolean inventoryHasFreeSlots = false; - for (ItemStack iteratedStack : player.getInventory().getStorageContents()) { - - if (iteratedStack == null) { - - inventoryHasFreeSlots = true; - break; - - } - - } - - //These slots are for buying items - if (event.getClickedInventory().getName().equalsIgnoreCase(SHOP_NAME) && validSlots.contains(event.getSlot())) { - - if (!inventoryHasFreeSlots) { - - player.sendMessage("Your inventory is full! You can't buy items until you get some free space."); - player.closeInventory(); - - } else if (EconomyHandler.checkCurrency(UUIDFilter.guessUUI(player.getName())) >= itemValue) { - //player has enough money - EconomyHandler.subtractCurrency(UUIDFilter.guessUUI(player.getName()), itemValue); - player.getInventory().addItem(itemStack); - populateShop(event.getInventory()); - - SharedShopElements.buyMessage(player, itemDisplayName, itemValue); - - } else { - - player.closeInventory(); - SharedShopElements.insufficientFundsMessage(player, itemValue); - - } - - } - - event.setCancelled(true); - - } - - -} diff --git a/src/main/java/com/magmaguy/elitemobs/config/AdventurersGuildConfig.java b/src/main/java/com/magmaguy/elitemobs/config/AdventurersGuildConfig.java index 919bf63f8..7c38171bf 100644 --- a/src/main/java/com/magmaguy/elitemobs/config/AdventurersGuildConfig.java +++ b/src/main/java/com/magmaguy/elitemobs/config/AdventurersGuildConfig.java @@ -1,25 +1,481 @@ package com.magmaguy.elitemobs.config; -import org.bukkit.configuration.Configuration; +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.commands.guild.AdventurersGuildCommand; +import lombok.Getter; +import lombok.Setter; +import org.bukkit.Location; +import org.bukkit.configuration.file.FileConfiguration; + +import java.io.File; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; public class AdventurersGuildConfig { + @Getter + private static final String[][] rankNames = new String[11][21]; + @Getter + private static final String[][] shortRankNames = new String[11][21]; + @Getter + private static boolean addMaxHealth; + @Getter + private static boolean addCrit; + @Getter + private static boolean addDodge; + @Getter + private static boolean guildWorldIsEnabled; + @Getter + private static String guildWorldName; + @Getter + private static String guildLocationString; + @Getter + @Setter + private static Location guildWorldLocation; + @Getter + private static boolean agTeleport; + @Getter + private static boolean guildLootLimiter; + @Getter + private static String lootLimiterMessage; + @Getter + private static List onRankUpCommand; + @Getter + private static List onPrestigeUpCommand; + @Getter + private static double dodge1; + @Getter + private static double dodge2; + @Getter + private static double dodge3; + @Getter + private static double crit1; + @Getter + private static double crit2; + @Getter + private static double crit3; + @Getter + private static double health1; + @Getter + private static double health2; + @Getter + private static double health3; + @Getter + private static double health4; + @Getter + private static String adventurersGuildMenuName; + @Getter + private static int baseKillsForRankUp; + @Getter + private static int additionalKillsForRankUpPerTier; + @Getter + private static String prestigeUnlockMessageTitle; + @Getter + private static String prestigeUnlockMessageSubtitle; + @Getter + private static List worldsWithoutAGBonuses; + @Getter + private static double peacefulModeEliteChanceDecrease; + + private static File file; + private static FileConfiguration fileConfiguration; + + private AdventurersGuildConfig() { + } + + public static void toggleGuildInstall() { + guildWorldIsEnabled = !guildWorldIsEnabled; + fileConfiguration.set("guildHubIsEnabledv2", guildWorldIsEnabled); + save(); + } + + public static void save() { + ConfigurationEngine.fileSaverOnlyDefaults(fileConfiguration, file); + } + + public static void initializeConfig() { + file = ConfigurationEngine.fileCreator("AdventurersGuild.yml"); + fileConfiguration = ConfigurationEngine.fileConfigurationCreator(file); + addMaxHealth = ConfigurationEngine.setBoolean(fileConfiguration, "Add max health when unlocking higher guild ranks", true); + addCrit = ConfigurationEngine.setBoolean(fileConfiguration, "Add critical chance when unlocking higher guild ranks", true); + addDodge = ConfigurationEngine.setBoolean(fileConfiguration, "Add dodge chance when unlocking higher guild ranks", true); + guildWorldIsEnabled = ConfigurationEngine.setBoolean(fileConfiguration, "guildHubIsEnabledv2", false); + guildWorldName = ConfigurationEngine.setString(fileConfiguration, "Adventurer's Guild world name v3", "em_adventurers_guild"); + guildLocationString = ConfigurationEngine.setString(fileConfiguration, "Guild world coordinates", "208.5,88,236.5,-80,0"); + guildWorldLocation = null; + agTeleport = ConfigurationEngine.setBoolean(fileConfiguration, "userCommandsTeleportToAdventurersGuild", true); + adventurersGuildMenuName = ConfigurationEngine.setString(fileConfiguration, "adventurersGuildMenuName", "&6&lAdventurer's Hub"); + + //iterate through all prestige tiers + for (int prestigeRank = 0; prestigeRank < 11; prestigeRank++) + for (int normalRank = 0; normalRank < 11 + prestigeRank; normalRank++) { + String rankName = ""; + String shortRankName = ""; + switch (normalRank) { + case 0: + if (prestigeRank == 0) { + rankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank, "&8Commoner - disables elites!"); + shortRankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank + " short placeholder", "&6&l✧&e" + romanNumerals(normalRank)); + } else { + rankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank, prestigeColors(prestigeRank) + "Prestige " + prestigeRank + " &8Commoner"); + shortRankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank + " short placeholder", prestigeColors(prestigeRank) + "⚜" + romanNumerals(prestigeRank) + "&6&l✧&e" + romanNumerals(normalRank)); + } + rankNames[prestigeRank][normalRank] = rankName; + shortRankNames[prestigeRank][normalRank] = shortRankName; + break; + case 1: + if (prestigeRank == 0) { + rankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank, "&fRookie"); + shortRankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank + " short placeholder", "&6&l✧&e" + romanNumerals(normalRank)); + } else { + rankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank, prestigeColors(prestigeRank) + "Prestige " + prestigeRank + " &fRookie"); + shortRankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank + " short placeholder", prestigeColors(prestigeRank) + "⚜" + romanNumerals(prestigeRank) + "&6&l✧&e" + romanNumerals(normalRank)); + } + rankNames[prestigeRank][normalRank] = rankName; + shortRankNames[prestigeRank][normalRank] = shortRankName; + break; + case 2: + if (prestigeRank == 0) { + rankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank, "&fNovice"); + shortRankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank + " short placeholder", "&6&l✧&e" + romanNumerals(normalRank)); + } else { + rankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank, prestigeColors(prestigeRank) + "Prestige " + prestigeRank + " &fNovice"); + shortRankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank + " short placeholder", prestigeColors(prestigeRank) + "⚜" + romanNumerals(prestigeRank) + "&6&l✧&e" + romanNumerals(normalRank)); + } + rankNames[prestigeRank][normalRank] = rankName; + shortRankNames[prestigeRank][normalRank] = shortRankName; + break; + case 3: + if (prestigeRank == 0) { + rankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank, "&fApprentice"); + shortRankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank + " short placeholder", "&6&l✧&e" + romanNumerals(normalRank)); + } else { + rankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank, prestigeColors(prestigeRank) + "Prestige " + prestigeRank + " &fApprentice"); + shortRankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank + " short placeholder", prestigeColors(prestigeRank) + "⚜" + romanNumerals(prestigeRank) + "&6&l✧&e" + romanNumerals(normalRank)); + } + rankNames[prestigeRank][normalRank] = rankName; + shortRankNames[prestigeRank][normalRank] = shortRankName; + break; + case 4: + if (prestigeRank == 0) { + rankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank, "&2Adventurer"); + shortRankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank + " short placeholder", "&6&l✧&e" + romanNumerals(normalRank)); + } else { + rankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank, prestigeColors(prestigeRank) + "Prestige " + prestigeRank + " &2Adventurer"); + shortRankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank + " short placeholder", prestigeColors(prestigeRank) + "⚜" + romanNumerals(prestigeRank) + "&6&l✧&e" + romanNumerals(normalRank)); + } + rankNames[prestigeRank][normalRank] = rankName; + shortRankNames[prestigeRank][normalRank] = shortRankName; + break; + case 5: + if (prestigeRank == 0) { + rankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank, "&2Journeyman"); + shortRankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank + " short placeholder", "&6&l✧&e" + romanNumerals(normalRank)); + } else { + rankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank, prestigeColors(prestigeRank) + "Prestige " + prestigeRank + " &2Journeyman"); + shortRankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank + " short placeholder", prestigeColors(prestigeRank) + "⚜" + romanNumerals(prestigeRank) + "&6&l✧&e" + romanNumerals(normalRank)); + } + rankNames[prestigeRank][normalRank] = rankName; + shortRankNames[prestigeRank][normalRank] = shortRankName; + break; + case 6: + if (prestigeRank == 0) { + rankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank, "&2Adept"); + shortRankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank + " short placeholder", "&6&l✧&e" + romanNumerals(normalRank)); + } else { + rankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank, prestigeColors(prestigeRank) + "Prestige " + prestigeRank + " &2Adept"); + shortRankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank + " short placeholder", prestigeColors(prestigeRank) + "⚜" + romanNumerals(prestigeRank) + "&6&l✧&e" + romanNumerals(normalRank)); + } + rankNames[prestigeRank][normalRank] = rankName; + shortRankNames[prestigeRank][normalRank] = shortRankName; + break; + case 7: + if (prestigeRank == 0) { + rankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank, "&1Veteran"); + shortRankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank + " short placeholder", "&6&l✧&e" + romanNumerals(normalRank)); + } else { + rankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank, prestigeColors(prestigeRank) + "Prestige " + prestigeRank + " &1Veteran"); + shortRankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank + " short placeholder", prestigeColors(prestigeRank) + "⚜" + romanNumerals(prestigeRank) + "&6&l✧&e" + romanNumerals(normalRank)); + } + rankNames[prestigeRank][normalRank] = rankName; + shortRankNames[prestigeRank][normalRank] = shortRankName; + break; + case 8: + if (prestigeRank == 0) { + rankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank, "&1Elite"); + shortRankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank + " short placeholder", "&6&l✧&e" + romanNumerals(normalRank)); + } else { + rankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank, prestigeColors(prestigeRank) + "Prestige " + prestigeRank + " &1Elite"); + shortRankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank + " short placeholder", prestigeColors(prestigeRank) + "⚜" + romanNumerals(prestigeRank) + "&6&l✧&e" + romanNumerals(normalRank)); + } + rankNames[prestigeRank][normalRank] = rankName; + shortRankNames[prestigeRank][normalRank] = shortRankName; + break; + case 9: + if (prestigeRank == 0) { + rankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank, "&lMaster"); + shortRankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank + " short placeholder", "&6&l✧&e" + romanNumerals(normalRank)); + } else { + rankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank, prestigeColors(prestigeRank) + "Prestige " + prestigeRank + " &5Master"); + shortRankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank + " short placeholder", prestigeColors(prestigeRank) + "⚜" + romanNumerals(prestigeRank) + "&6&l✧&e" + romanNumerals(normalRank)); + } + rankNames[prestigeRank][normalRank] = rankName; + shortRankNames[prestigeRank][normalRank] = shortRankName; + break; + case 10: + if (prestigeRank == 0) { + rankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank, "&5Hero"); + shortRankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank + " short placeholder", "&6&l✧&e" + romanNumerals(normalRank)); + } else { + shortRankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank + " short placeholder", prestigeColors(prestigeRank) + "⚜" + romanNumerals(prestigeRank) + "&6&l✧&e" + romanNumerals(normalRank)); + rankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank, prestigeColors(prestigeRank) + "Prestige " + prestigeRank + " &5Hero"); + } + rankNames[prestigeRank][normalRank] = rankName; + shortRankNames[prestigeRank][normalRank] = shortRankName; + break; + case 11: + rankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank, prestigeColors(prestigeRank) + "Prestige " + prestigeRank + " &5Legend"); + shortRankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank + " short placeholder", prestigeColors(prestigeRank) + "⚜" + romanNumerals(prestigeRank) + "&6&l✧&e" + romanNumerals(normalRank)); + rankNames[prestigeRank][normalRank] = rankName; + shortRankNames[prestigeRank][normalRank] = shortRankName; + break; + case 12: + rankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank, prestigeColors(prestigeRank) + "Prestige " + prestigeRank + " &5Myth"); + shortRankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank + " short placeholder", prestigeColors(prestigeRank) + "⚜" + romanNumerals(prestigeRank) + "&6&l✧&e" + romanNumerals(normalRank)); + rankNames[prestigeRank][normalRank] = rankName; + shortRankNames[prestigeRank][normalRank] = shortRankName; + break; + case 13: + rankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank, prestigeColors(prestigeRank) + "Prestige " + prestigeRank + " &5Immortal"); + shortRankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank + " short placeholder", prestigeColors(prestigeRank) + "⚜" + romanNumerals(prestigeRank) + "&6&l✧&e" + romanNumerals(normalRank)); + rankNames[prestigeRank][normalRank] = rankName; + shortRankNames[prestigeRank][normalRank] = shortRankName; + break; + case 14: + rankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank, prestigeColors(prestigeRank) + "Prestige " + prestigeRank + " &5Chosen"); + shortRankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank + " short placeholder", prestigeColors(prestigeRank) + "⚜" + romanNumerals(prestigeRank) + "&6&l✧&e" + romanNumerals(normalRank)); + rankNames[prestigeRank][normalRank] = rankName; + shortRankNames[prestigeRank][normalRank] = shortRankName; + break; + case 15: + rankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank, prestigeColors(prestigeRank) + "Prestige " + prestigeRank + " &5Ascendant"); + shortRankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank + " short placeholder", prestigeColors(prestigeRank) + "⚜" + romanNumerals(prestigeRank) + "&6&l✧&e" + romanNumerals(normalRank)); + rankNames[prestigeRank][normalRank] = rankName; + shortRankNames[prestigeRank][normalRank] = shortRankName; + break; + case 16: + rankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank, prestigeColors(prestigeRank) + "Prestige " + prestigeRank + " &5Titan"); + shortRankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank + " short placeholder", prestigeColors(prestigeRank) + "⚜" + romanNumerals(prestigeRank) + "&6&l✧&e" + romanNumerals(normalRank)); + rankNames[prestigeRank][normalRank] = rankName; + shortRankNames[prestigeRank][normalRank] = shortRankName; + break; + case 17: + rankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank, prestigeColors(prestigeRank) + "Prestige " + prestigeRank + " &5Demigod"); + shortRankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank + " short placeholder", prestigeColors(prestigeRank) + "⚜" + romanNumerals(prestigeRank) + "&6&l✧&e" + romanNumerals(normalRank)); + rankNames[prestigeRank][normalRank] = rankName; + shortRankNames[prestigeRank][normalRank] = shortRankName; + break; + case 18: + rankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank, prestigeColors(prestigeRank) + "Prestige " + prestigeRank + " &5Deity"); + shortRankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank + " short placeholder", prestigeColors(prestigeRank) + "⚜" + romanNumerals(prestigeRank) + "&6&l✧&e" + romanNumerals(normalRank)); + rankNames[prestigeRank][normalRank] = rankName; + shortRankNames[prestigeRank][normalRank] = shortRankName; + break; + case 19: + rankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank, prestigeColors(prestigeRank) + "Prestige " + prestigeRank + " &5Godhunter"); + shortRankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank + " short placeholder", prestigeColors(prestigeRank) + "⚜" + romanNumerals(prestigeRank) + "&6&l✧&e" + romanNumerals(normalRank)); + rankNames[prestigeRank][normalRank] = rankName; + shortRankNames[prestigeRank][normalRank] = shortRankName; + break; + case 20: + rankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank, prestigeColors(prestigeRank) + "Prestige " + prestigeRank + " &5Godslayer"); + shortRankName = ConfigurationEngine.setString(fileConfiguration, + "Prestige " + prestigeRank + " rank " + normalRank + " short placeholder", prestigeColors(prestigeRank) + "⚜" + romanNumerals(prestigeRank) + "&6&l✧&e" + romanNumerals(normalRank)); + rankNames[prestigeRank][normalRank] = rankName; + shortRankNames[prestigeRank][normalRank] = shortRankName; + break; + default: + throw new IllegalStateException("Unexpected value: " + normalRank); + } - public static final String CONFIG_NAME = "AdventurersGuild.yml"; + } - public static final String ENABLE_ADVENTURERS_GUILD = "Enable adventurer's guild"; + guildLootLimiter = ConfigurationEngine.setBoolean(fileConfiguration, "limitLootBasedOnGuildTier", true); + lootLimiterMessage = ConfigurationEngine.setString(fileConfiguration, "lootLimiterMessage", "&7[EM] &cYou must unlock the next guild rank through /ag to loot better items!"); + onRankUpCommand = ConfigurationEngine.setList(fileConfiguration, "onRankUpCommand", Collections.emptyList()); + onPrestigeUpCommand = ConfigurationEngine.setList(fileConfiguration, "onPrestigeUpCommand", Collections.emptyList()); + dodge1 = ConfigurationEngine.setDouble(fileConfiguration, "dodgePrestige3Bonus", 3); + dodge2 = ConfigurationEngine.setDouble(fileConfiguration, "dodgePrestige6Bonus", 6); + dodge3 = ConfigurationEngine.setDouble(fileConfiguration, "dodgePrestige9Bonus", 10); + crit1 = ConfigurationEngine.setDouble(fileConfiguration, "critPrestige2Bonus", 3); + crit2 = ConfigurationEngine.setDouble(fileConfiguration, "critPrestige5Bonus", 6); + crit3 = ConfigurationEngine.setDouble(fileConfiguration, "critPrestige8Bonus", 10); + health1 = ConfigurationEngine.setDouble(fileConfiguration, "healthPrestige1Bonus", 2); + health2 = ConfigurationEngine.setDouble(fileConfiguration, "healthPrestige4Bonus", 2.5); + health3 = ConfigurationEngine.setDouble(fileConfiguration, "healthPrestige7Bonus", 3); + health4 = ConfigurationEngine.setDouble(fileConfiguration, "healthPrestige10Bonus", 4); - CustomConfigLoader customConfigLoader = new CustomConfigLoader(); - Configuration configuration = customConfigLoader.getCustomConfig(CONFIG_NAME); + baseKillsForRankUp = ConfigurationEngine.setInt(fileConfiguration, "baseKillsForRankUp", 100); + additionalKillsForRankUpPerTier = ConfigurationEngine.setInt(fileConfiguration, "additionalKillsForRankUpPerTier", 50); - public void initializeConfig(){ + prestigeUnlockMessageTitle = ConfigurationEngine.setString(fileConfiguration, "prestigeUnlockMessageTitle", "$player"); + prestigeUnlockMessageSubtitle = ConfigurationEngine.setString(fileConfiguration, "prestigeUnlockMessageSubtitle", "&2has unlocked $tier&2!"); - configuration.addDefault(ENABLE_ADVENTURERS_GUILD, true); + //initializes the AG location + AdventurersGuildCommand.defineTeleportLocation(); - configuration.options().copyDefaults(true); - UnusedNodeHandler.clearNodes(configuration); - customConfigLoader.saveDefaultCustomConfig(CONFIG_NAME); - customConfigLoader.saveCustomConfig(CONFIG_NAME); + peacefulModeEliteChanceDecrease = ConfigurationEngine.setDouble(fileConfiguration, "peacefulModeEliteChanceDecrease", 0.2); + + worldsWithoutAGBonuses = ConfigurationEngine.setList(fileConfiguration, "worldsWithoutAGBonuses", new ArrayList()); + + save(); + } + + public static String getRankName(int prestigeTier, int rankTier) { + return ChatColorConverter.convert(rankNames[prestigeTier][rankTier]); + } + + public static String getShortenedRankName(int prestigeTier, int rankTier) { + return ChatColorConverter.convert(shortRankNames[prestigeTier][rankTier]); + } + + private static String prestigeColors(int prestigeTier) { + switch (prestigeTier) { + case 1: + return "&e"; + case 2: + return "&2"; + case 3: + return "&a"; + case 4: + return "&3"; + case 5: + return "&b"; + case 6: + return "&4"; + case 7: + return "&c"; + case 8: + return "&9"; + case 9: + return "&d"; + case 10: + return "&5"; + default: + return "error"; + } + } + private static String romanNumerals(int prestigeTier) { + switch (prestigeTier) { + case 1: + return "Ⅰ"; + case 2: + return "ⅠⅠ"; + case 3: + return "ⅠⅠⅠ"; + case 4: + return "ⅠⅤ"; + case 5: + return "Ⅴ"; + case 6: + return "ⅤⅠ"; + case 7: + return "ⅤⅠⅠ"; + case 8: + return "ⅤⅠⅠⅠ"; + case 9: + return "ⅠⅩ"; + case 10: + return "Ⅹ"; + case 11: + return "ⅩⅠ"; + case 12: + return "ⅩⅠⅠ"; + case 13: + return "ⅩⅠⅠⅠ"; + case 14: + return "ⅩⅠⅤ"; + case 15: + return "ⅩⅤ"; + case 16: + return "ⅩⅤⅠ"; + case 17: + return "ⅩⅤⅠⅠ"; + case 18: + return "ⅩⅤⅠⅠⅠ"; + case 19: + return "ⅩⅠⅩ"; + case 20: + return "ⅩⅩ"; + case 0: + return "0"; + default: + return "error"; + } } } diff --git a/src/main/java/com/magmaguy/elitemobs/config/AntiExploitConfig.java b/src/main/java/com/magmaguy/elitemobs/config/AntiExploitConfig.java new file mode 100644 index 000000000..df4839830 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/AntiExploitConfig.java @@ -0,0 +1,64 @@ +package com.magmaguy.elitemobs.config; + +import lombok.Getter; +import org.bukkit.configuration.file.FileConfiguration; + +import java.io.File; + +public class AntiExploitConfig { + @Getter + private static String antiExploitMessage; + @Getter + private static boolean darkroomAntiExploit1; + @Getter + private static boolean darkroomAntiExploit2; + @Getter + private static boolean darkroomAntiExploit3; + @Getter + private static boolean largeDarkroomAntiExploit1; + @Getter + private static boolean largeDarkroomAntiExploit2; + @Getter + private static boolean largeDarkroomAntiExploit3; + @Getter + private static boolean endermanHeightAntiExploit; + @Getter + private static boolean mountAntiExploit; + @Getter + private static boolean towerAntiExploit; + @Getter + private static boolean ambientDamageExploit; + @Getter + private static boolean honeyBlockExploit; + @Getter + private static boolean noItemPickup; + @Getter + private static int antiExploitThreshold; + + private AntiExploitConfig() { + } + + public static void initializeConfig() { + File file = ConfigurationEngine.fileCreator("AntiExploit.yml"); + FileConfiguration fileConfiguration = ConfigurationEngine.fileConfigurationCreator(file); + + antiExploitMessage = ConfigurationEngine.setString(fileConfiguration, "AntiExploit message", + "&c[EM AntiExploit] &7Nearby elite won't drop special loot."); + darkroomAntiExploit1 = ConfigurationEngine.setBoolean(fileConfiguration, "Enable darkroom antiexploit 1", true); + darkroomAntiExploit2 = ConfigurationEngine.setBoolean(fileConfiguration, "Enable darkroom antiexploit 2", true); + darkroomAntiExploit3 = ConfigurationEngine.setBoolean(fileConfiguration, "Enable darkroom antiexploit 3", true); + largeDarkroomAntiExploit1 = ConfigurationEngine.setBoolean(fileConfiguration, "Enable large darkroom antiexploit 1", true); + largeDarkroomAntiExploit2 = ConfigurationEngine.setBoolean(fileConfiguration, "Enable large darkroom antiexploit 2", true); + largeDarkroomAntiExploit3 = ConfigurationEngine.setBoolean(fileConfiguration, "Enable large darkroom antiexploit 3", true); + endermanHeightAntiExploit = ConfigurationEngine.setBoolean(fileConfiguration, "Enable enderman height antiexploit", true); + mountAntiExploit = ConfigurationEngine.setBoolean(fileConfiguration, "Enable mount antiexploit", true); + towerAntiExploit = ConfigurationEngine.setBoolean(fileConfiguration, "Enable tower antiexploit", true); + noItemPickup = ConfigurationEngine.setBoolean(fileConfiguration, "preventItemPickupByMobs", true); + ambientDamageExploit = ConfigurationEngine.setBoolean(fileConfiguration, "Enable ambient damage antiexploit", true); + honeyBlockExploit = ConfigurationEngine.setBoolean(fileConfiguration, "Enable honey block antiexploit", true); + antiExploitThreshold = ConfigurationEngine.setInt(fileConfiguration, "antiExploitThreshold", 10); + + ConfigurationEngine.fileSaverOnlyDefaults(fileConfiguration, file); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/ArenasConfig.java b/src/main/java/com/magmaguy/elitemobs/config/ArenasConfig.java new file mode 100644 index 000000000..eaff03bf6 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/ArenasConfig.java @@ -0,0 +1,79 @@ +package com.magmaguy.elitemobs.config; + +import lombok.Getter; +import org.bukkit.configuration.file.FileConfiguration; + +import java.io.File; + +public class ArenasConfig { + @Getter + private static String notEnoughPlayersMessage; + @Getter + private static String startingTitle; + @Getter + private static String startingSubtitle; + @Getter + private static String arenaFullMessage; + @Getter + private static String arenasOngoingMessage; + @Getter + private static String arenaStartHintMessage; + @Getter + private static String arenaQuitHintMessage; + @Getter + private static String arenaJoinPlayerMessage; + @Getter + private static String arenaJoinSpectatorMessage; + @Getter + private static String waveTitle; + @Getter + private static String waveSubtitle; + @Getter + private static String victoryTitle; + @Getter + private static String victorySubtitle; + @Getter + private static String defeatTitle; + @Getter + private static String defeatSubtitle; + @Getter + private static String victoryBroadcast; + @Getter + private static String joinPlayerTitle; + @Getter + private static String joinPlayerSubtitle; + @Getter + private static String joinSpectatorTitle; + @Getter + private static String joinSpectatorSubtitle; + + private ArenasConfig() { + } + + public static void initializeConfig() { + File file = ConfigurationEngine.fileCreator("Arenas.yml"); + FileConfiguration fileConfiguration = ConfigurationEngine.fileConfigurationCreator(file); + + notEnoughPlayersMessage = ConfigurationEngine.setString(fileConfiguration, "notEnoughPlayersMessage", "&8[EliteMobs] &cYou need at least $amount to start the match!"); + startingTitle = ConfigurationEngine.setString(fileConfiguration, "startingMessage", "&2Starting!"); + startingSubtitle = ConfigurationEngine.setString(fileConfiguration, "startingSubtitle", "&2in $count..."); + arenaFullMessage = ConfigurationEngine.setString(fileConfiguration, "arenaFullMessage", "&4[EliteMobs] &cArena is full! You can spectate instead while you wait for it to finish!"); + arenasOngoingMessage = ConfigurationEngine.setString(fileConfiguration, "arenasOngoingMessage", "&4[EliteMobs] &cCan't join the arena now - a match is currently happening! You can spectate instead while you wait for it to finish!"); + arenaStartHintMessage = ConfigurationEngine.setString(fileConfiguration, "arenaStartHintMessage", "&2[EliteMobs] &aYou can start the arena by doing &2/em start"); + arenaQuitHintMessage = ConfigurationEngine.setString(fileConfiguration, "arenaQuitHintMessage", "&4[EliteMobs] &cYou can leave the arena by doing &4/em quit"); + arenaJoinPlayerMessage = ConfigurationEngine.setString(fileConfiguration, "arenaJoinPlayerMessage", "&2[EliteMobs] &aYou can start the arena by doing &2/em start &aif there are at least &2$count &aplayers in it! \nYou can leave the arena by doing &c/em quit"); + arenaJoinSpectatorMessage = ConfigurationEngine.setString(fileConfiguration, "arenaJoinSpectatorMessage", "&2[EliteMobs] &aYou can leave the arena at any time using &2/em quit"); + waveTitle = ConfigurationEngine.setString(fileConfiguration, "waveTitle", "&aWave &2$wave"); + waveSubtitle = ConfigurationEngine.setString(fileConfiguration, "waveSubtitle", ""); + victoryTitle = ConfigurationEngine.setString(fileConfiguration, "victoryTitle", "&2Victory!"); + victorySubtitle = ConfigurationEngine.setString(fileConfiguration, "victorySubtitle", "&aCompleted &2$wave &awaves!"); + defeatTitle = ConfigurationEngine.setString(fileConfiguration, "defeatTitle", "&4Defeat!"); + defeatSubtitle = ConfigurationEngine.setString(fileConfiguration, "defeatSubtitle", "&cReached wave &4$wave&c!"); + victoryBroadcast = ConfigurationEngine.setString(fileConfiguration, "victoryBroadcast", "Arena $arenaName was conquered by $players!"); + joinPlayerTitle = ConfigurationEngine.setString(fileConfiguration, "joinPlayerTitle", "&aStart with &2/em start &a!"); + joinPlayerSubtitle = ConfigurationEngine.setString(fileConfiguration, "joinPlayerSubtitle", "&cLeave with &4/em quit &c!"); + joinSpectatorTitle = ConfigurationEngine.setString(fileConfiguration, "joinSpectatorTitle", "&aNow spectating!"); + joinSpectatorSubtitle = ConfigurationEngine.setString(fileConfiguration, "joinSpectatorSubtitle", "&cLeave with &4/em quit &c!"); + ConfigurationEngine.fileSaverOnlyDefaults(fileConfiguration, file); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/CombatTagConfig.java b/src/main/java/com/magmaguy/elitemobs/config/CombatTagConfig.java index dc84f734c..6749d5195 100644 --- a/src/main/java/com/magmaguy/elitemobs/config/CombatTagConfig.java +++ b/src/main/java/com/magmaguy/elitemobs/config/CombatTagConfig.java @@ -1,27 +1,30 @@ package com.magmaguy.elitemobs.config; -import org.bukkit.configuration.Configuration; +import lombok.Getter; +import org.bukkit.configuration.file.FileConfiguration; -public class CombatTagConfig { - - public static final String CONFIG_NAME = "CombatTag.yml"; - - public static final String ENABLE_COMBAT_TAG = "Enable combat tag"; - public static final String COMBAT_TAG_MESSAGE = "Combat tag message"; +import java.io.File; - CustomConfigLoader customConfigLoader = new CustomConfigLoader(); - private Configuration configuration = customConfigLoader.getCustomConfig(CONFIG_NAME); - - public void initializeConfig(){ +public class CombatTagConfig { + @Getter + private static boolean enableCombatTag; + @Getter + private static String combatTagMessage; + @Getter + private static boolean enableTeleportTimer; + + private CombatTagConfig() { + } - configuration.addDefault(ENABLE_COMBAT_TAG, true); - configuration.addDefault(COMBAT_TAG_MESSAGE, "&c[EliteMobs] Combat tag activated!"); + public static void initializeConfig() { + File file = ConfigurationEngine.fileCreator("CombatTag.yml"); + FileConfiguration fileConfiguration = ConfigurationEngine.fileConfigurationCreator(file); - customConfigLoader.getCustomConfig(CONFIG_NAME).options().copyDefaults(true); - UnusedNodeHandler.clearNodes(configuration); - customConfigLoader.saveDefaultCustomConfig(CONFIG_NAME); - customConfigLoader.saveCustomConfig(CONFIG_NAME); + enableCombatTag = ConfigurationEngine.setBoolean(fileConfiguration, "Enable combat tag", true); + combatTagMessage = ConfigurationEngine.setString(fileConfiguration, "Combat tag message", "&c[EliteMobs] Combat tag activated!"); + enableTeleportTimer = ConfigurationEngine.setBoolean(fileConfiguration, "Enable adventurers guild teleport timer", true); + ConfigurationEngine.fileSaverOnlyDefaults(fileConfiguration, file); } } diff --git a/src/main/java/com/magmaguy/elitemobs/config/ConfigValues.java b/src/main/java/com/magmaguy/elitemobs/config/ConfigValues.java deleted file mode 100644 index 68a35cd75..000000000 --- a/src/main/java/com/magmaguy/elitemobs/config/ConfigValues.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.config; - -import com.magmaguy.elitemobs.MetadataHandler; -import org.bukkit.Bukkit; -import org.bukkit.configuration.Configuration; - -/** - * Created by MagmaGuy on 05/05/2017. - */ -public class ConfigValues { - - public static Configuration defaultConfig, itemsCustomLootListConfig, mobPowerConfig, translationConfig, - itemsProceduralSettingsConfig, economyConfig, playerCacheConfig, eventsConfig, itemsCustomLootSettingsConfig, - validMobsConfig, validWorldsConfig, itemsUniqueConfig, mobCombatSettingsConfig, itemsDropSettingsConfig, - playerMoneyData, playerRankData, playerMaxRankData, combatTagConfig, adventurersGuildConfig, - customEnchantmentsConfig; - - public static void initializeCachedConfigurations() { - - CustomConfigLoader customConfigLoader = new CustomConfigLoader(); - - defaultConfig = Bukkit.getPluginManager().getPlugin(MetadataHandler.ELITE_MOBS).getConfig(); - - customConfigLoader = new CustomConfigLoader(); - itemsCustomLootListConfig = customConfigLoader.getCustomConfig(ItemsCustomLootListConfig.CONFIG_NAME, true); - - customConfigLoader = new CustomConfigLoader(); - mobPowerConfig = customConfigLoader.getCustomConfig(MobPowersConfig.CONFIG_NAME); - - customConfigLoader = new CustomConfigLoader(); - itemsCustomLootSettingsConfig = customConfigLoader.getCustomConfig(ItemsCustomLootSettingsConfig.CONFIG_NAME); - - customConfigLoader = new CustomConfigLoader(); - translationConfig = customConfigLoader.getCustomConfig(TranslationConfig.CONFIG_NAME); - - customConfigLoader = new CustomConfigLoader(); - itemsProceduralSettingsConfig = customConfigLoader.getCustomConfig(ItemsProceduralSettingsConfig.CONFIG_NAME); - - customConfigLoader = new CustomConfigLoader(); - economyConfig = customConfigLoader.getCustomConfig(EconomySettingsConfig.CONFIG_NAME); - - customConfigLoader = new CustomConfigLoader(); - playerCacheConfig = customConfigLoader.getCustomConfig(PlayerCacheData.CONFIG_NAME, true); - - customConfigLoader = new CustomConfigLoader(); - playerMoneyData = customConfigLoader.getCustomConfig(PlayerMoneyData.CONFIG_NAME, true); - - customConfigLoader = new CustomConfigLoader(); - playerRankData = customConfigLoader.getCustomConfig(PlayerGuildRank.CONFIG_NAME, true); - - customConfigLoader = new CustomConfigLoader(); - playerMaxRankData = customConfigLoader.getCustomConfig(PlayerMaxGuildRank.CONFIG_NAME, true); - - customConfigLoader = new CustomConfigLoader(); - eventsConfig = customConfigLoader.getCustomConfig(EventsConfig.CONFIG_NAME); - - customConfigLoader = new CustomConfigLoader(); - validMobsConfig = customConfigLoader.getCustomConfig(ValidMobsConfig.CONFIG_NAME); - - customConfigLoader = new CustomConfigLoader(); - validWorldsConfig = customConfigLoader.getCustomConfig(ValidWorldsConfig.CONFIG_NAME); - - customConfigLoader = new CustomConfigLoader(); - itemsUniqueConfig = customConfigLoader.getCustomConfig(ItemsUniqueConfig.CONFIG_NAME); - - customConfigLoader = new CustomConfigLoader(); - mobCombatSettingsConfig = customConfigLoader.getCustomConfig(MobCombatSettingsConfig.CONFIG_NAME); - - customConfigLoader = new CustomConfigLoader(); - itemsDropSettingsConfig = customConfigLoader.getCustomConfig(ItemsDropSettingsConfig.CONFIG_NAME); - - customConfigLoader = new CustomConfigLoader(); - combatTagConfig = customConfigLoader.getCustomConfig(CombatTagConfig.CONFIG_NAME); - - customConfigLoader = new CustomConfigLoader(); - adventurersGuildConfig = customConfigLoader.getCustomConfig(AdventurersGuildConfig.CONFIG_NAME); - - customConfigLoader = new CustomConfigLoader(); - customEnchantmentsConfig = customConfigLoader.getCustomConfig(CustomEnchantmentsConfig.CONFIG_NAME); - - } - - public static void intializeConfigurations() { - - DefaultConfig defaultConfig = new DefaultConfig(); - defaultConfig.loadConfiguration(); - - MobPowersConfig mobPowersConfig = new MobPowersConfig(); - mobPowersConfig.initializeConfig(); - - ItemsCustomLootListConfig itemsCustomLootListConfig = new ItemsCustomLootListConfig(); - itemsCustomLootListConfig.intializeConfig(); - - ItemsCustomLootSettingsConfig itemsCustomLootSettingsConfig = new ItemsCustomLootSettingsConfig(); - itemsCustomLootSettingsConfig.initializeConfig(); - - TranslationConfig translationConfig = new TranslationConfig(); - translationConfig.initializeConfig(); - - ItemsProceduralSettingsConfig itemsProceduralSettingsConfig = new ItemsProceduralSettingsConfig(); - itemsProceduralSettingsConfig.intializeConfig(); - - EconomySettingsConfig economySettingsConfig = new EconomySettingsConfig(); - economySettingsConfig.initializeConfig(); - - PlayerMoneyData playerMoneyData = new PlayerMoneyData(); - playerMoneyData.intializeConfig(); - - PlayerCacheData playerCacheData = new PlayerCacheData(); - playerCacheData.initializeConfig(); - - EventsConfig eventsConfig = new EventsConfig(); - eventsConfig.initializeConfig(); - - ValidWorldsConfig validWorldsConfig = new ValidWorldsConfig(); - validWorldsConfig.initializeConfig(); - - ValidMobsConfig validMobsConfig = new ValidMobsConfig(); - validMobsConfig.initializeConfig(); - - ItemsUniqueConfig itemsUniqueConfig = new ItemsUniqueConfig(); - itemsUniqueConfig.initializeConfig(); - - MobCombatSettingsConfig mobCombatSettingsConfig = new MobCombatSettingsConfig(); - mobCombatSettingsConfig.initializeConfig(); - - ItemsDropSettingsConfig itemsDropSettingsConfig = new ItemsDropSettingsConfig(); - itemsDropSettingsConfig.initializeConfig(); - - PlayerGuildRank playerGuildRank = new PlayerGuildRank(); - playerGuildRank.intializeConfig(); - - PlayerMaxGuildRank playerMaxGuildRank = new PlayerMaxGuildRank(); - playerMaxGuildRank.intializeConfig(); - - CombatTagConfig combatTagConfig = new CombatTagConfig(); - combatTagConfig.initializeConfig(); - - AdventurersGuildConfig adventurersGuildConfig = new AdventurersGuildConfig(); - adventurersGuildConfig.initializeConfig(); - - CustomEnchantmentsConfig customEnchantmentsConfig = new CustomEnchantmentsConfig(); - customEnchantmentsConfig.initializeConfig(); - - } - -} \ No newline at end of file diff --git a/src/main/java/com/magmaguy/elitemobs/config/ConfigurationEngine.java b/src/main/java/com/magmaguy/elitemobs/config/ConfigurationEngine.java new file mode 100644 index 000000000..fbed738db --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/ConfigurationEngine.java @@ -0,0 +1,145 @@ +package com.magmaguy.elitemobs.config; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import com.magmaguy.elitemobs.utils.WarningMessage; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.SkullMeta; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +public class ConfigurationEngine { + + public static File fileCreator(String path, String fileName) { + File file = new File(MetadataHandler.PLUGIN.getDataFolder().getPath() + "/" + path + "/", fileName); + return fileCreator(file); + } + + public static File fileCreator(String fileName) { + File file = new File(MetadataHandler.PLUGIN.getDataFolder().getPath(), fileName); + return fileCreator(file); + } + + public static File fileCreator(File file) { + + if (!file.exists()) + try { + file.getParentFile().mkdirs(); + file.createNewFile(); + } catch (IOException ex) { + Bukkit.getLogger().warning("[EliteMobs] Error generating the plugin file: " + file.getName()); + } + + return file; + + } + + public static FileConfiguration fileConfigurationCreator(File file) { + return YamlConfiguration.loadConfiguration(file); + } + + public static void fileSaverCustomValues(FileConfiguration fileConfiguration, File file) { + fileConfiguration.options().copyDefaults(true); + + try { + fileConfiguration.save(file); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public static void fileSaverOnlyDefaults(FileConfiguration fileConfiguration, File file) { + fileConfiguration.options().copyDefaults(true); + UnusedNodeHandler.clearNodes(fileConfiguration); + + try { + fileConfiguration.save(file); + } catch (IOException e) { + e.printStackTrace(); + } + + } + + public static Boolean setBoolean(FileConfiguration fileConfiguration, String key, boolean defaultValue) { + fileConfiguration.addDefault(key, defaultValue); + return fileConfiguration.getBoolean(key); + } + + public static String setString(FileConfiguration fileConfiguration, String key, String defaultValue) { + fileConfiguration.addDefault(key, defaultValue); + return ChatColorConverter.convert(fileConfiguration.getString(key)); + } + + public static int setInt(FileConfiguration fileConfiguration, String key, int defaultValue) { + fileConfiguration.addDefault(key, defaultValue); + return fileConfiguration.getInt(key); + } + + public static double setDouble(FileConfiguration fileConfiguration, String key, double defaultValue) { + fileConfiguration.addDefault(key, defaultValue); + return fileConfiguration.getDouble(key); + } + + public static List setList(FileConfiguration fileConfiguration, String key, List defaultValue) { + fileConfiguration.addDefault(key, defaultValue); + return fileConfiguration.getList(key); + } + + public static ItemStack setItemStack(FileConfiguration fileConfiguration, String key, ItemStack itemStack) { + fileConfiguration.addDefault(key + ".material", itemStack.getType().toString()); + if (itemStack.hasItemMeta() && itemStack.getItemMeta().hasDisplayName()) + fileConfiguration.addDefault(key + ".name", itemStack.getItemMeta().getDisplayName()); + if (itemStack.hasItemMeta() && itemStack.getItemMeta().hasLore()) + fileConfiguration.addDefault(key + ".lore", itemStack.getItemMeta().getLore()); + if (itemStack.getType().equals(Material.PLAYER_HEAD)) + fileConfiguration.addDefault(key + ".owner", ((SkullMeta) itemStack.getItemMeta()).getOwner()); + Material material; + try { + material = Material.valueOf(fileConfiguration.getString(key + ".material")); + } catch (Exception ex) { + new WarningMessage("Material type " + fileConfiguration.getString(key + ".material") + " is not valid! Correct it to make a valid item."); + return null; + } + String name = ""; + try { + name = fileConfiguration.getString(key + ".name"); + } catch (Exception ex) { + new WarningMessage("Item name " + fileConfiguration.getString(key + ".name") + " is not valid! Correct it to make a valid item."); + } + List lore = new ArrayList<>(); + try { + lore = fileConfiguration.getStringList(key + ".lore"); + } catch (Exception ex) { + new WarningMessage("Item lore " + fileConfiguration.getString(key + ".lore") + " is not valid! Correct it to make a valid item."); + } + ItemStack fileItemStack = ItemStackGenerator.generateItemStack(material, name, lore); + if (material == Material.PLAYER_HEAD) + ((SkullMeta) itemStack.getItemMeta()).setOwningPlayer(Bukkit.getOfflinePlayer(fileConfiguration.getString(key + ".owner"))); + return fileItemStack; + } + + public static boolean writeValue(Object value, File file, FileConfiguration fileConfiguration, String path) { + fileConfiguration.set(path, value); + try { + fileSaverCustomValues(fileConfiguration, file); + } catch (Exception exception) { + new WarningMessage("Failed to write value for " + path + " in file " + file.getName()); + return false; + } + return true; + } + + public static void removeValue(File file, FileConfiguration fileConfiguration, String path) { + writeValue(null, file, fileConfiguration, path); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/ConfigurationExporter.java b/src/main/java/com/magmaguy/elitemobs/config/ConfigurationExporter.java new file mode 100644 index 000000000..63995aee9 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/ConfigurationExporter.java @@ -0,0 +1,209 @@ +package com.magmaguy.elitemobs.config; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.utils.InfoMessage; +import com.magmaguy.elitemobs.utils.SpigotMessage; +import com.magmaguy.elitemobs.utils.WarningMessage; +import com.magmaguy.elitemobs.utils.ZipFile; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.security.DigestInputStream; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.Properties; + +public class ConfigurationExporter { + private ConfigurationExporter() { + } + + public static void initializeConfigs() { + Path configurationsPath = Paths.get(MetadataHandler.PLUGIN.getDataFolder().getAbsolutePath()); + if (!Files.isDirectory(Paths.get(configurationsPath.normalize() + "" + File.separatorChar + "exports"))) { + try { + Files.createDirectory(Paths.get(configurationsPath.normalize() + "" + File.separatorChar + "exports")); + } catch (Exception exception) { + new WarningMessage("Failed to create exports directory! Tell the dev!"); + exception.printStackTrace(); + } + return; + } + + try { + new File(Paths.get(MetadataHandler.PLUGIN.getDataFolder().getCanonicalPath() + File.separatorChar + "exports").toString()); + } catch (Exception ex) { + new WarningMessage("Failed to get imports folder! Report this to the dev!"); + } + + } + + public static void createResourcePack(CommandSender commandSender) { + if (!Bukkit.getPluginManager().isPluginEnabled("ModelEngine")) { + commandSender.sendMessage(ChatColorConverter.convert("&8[EliteMobs]&c Could not generate resource pack because ModelEngine is not installed! Install ModelEngine to use this feature.")); + return; + } + + File modelEngineResourcePackFile = new File(MetadataHandler.PLUGIN.getDataFolder().getParentFile().toString() + File.separatorChar + "ModelEngine" + File.separatorChar + "resource pack"); + if (!modelEngineResourcePackFile.exists()) { + commandSender.sendMessage(ChatColorConverter.convert("&8[EliteMobs]&c Could not generate resource pack because ModelEngine is not installed! Install ModelEngine to use this feature.")); + return; + } + + + try { + if (!Paths.get(MetadataHandler.PLUGIN.getDataFolder() + "" + File.separatorChar + "exports" + File.separatorChar + "elitemobs_resource_pack").toFile().exists()) + Files.createDirectory(Paths.get(MetadataHandler.PLUGIN.getDataFolder() + "" + File.separatorChar + "exports" + File.separatorChar + "elitemobs_resource_pack")); + } catch (Exception ex) { + commandSender.sendMessage(ChatColorConverter.convert("&8[EliteMobs]&c Failed to generate target directory plugins/EliteMobs/exports/elitemobs_resource_pack required for storing the resource pack! Report this to the dev!")); + return; + } + + copyDirectory(modelEngineResourcePackFile, Paths.get(MetadataHandler.PLUGIN.getDataFolder() + "" + File.separatorChar + "exports" + File.separatorChar + "elitemobs_resource_pack")); + commandSender.sendMessage(ChatColorConverter.convert("&8[EliteMobs]&f Copied all files from Model Engine to " + MetadataHandler.PLUGIN.getDataFolder() + "" + File.separatorChar + "exports" + File.separatorChar + "elitemobs_resource_pack")); + + if (ZipFile.zip(new File(MetadataHandler.PLUGIN.getDataFolder() + "" + File.separatorChar + "exports" + File.separatorChar + "elitemobs_resource_pack"), + MetadataHandler.PLUGIN.getDataFolder() + "" + File.separatorChar + "exports" + File.separatorChar + "elitemobs_resource_pack.zip")) + commandSender.sendMessage(ChatColorConverter.convert("&8[EliteMobs]&f Packaged texture pack into " + + MetadataHandler.PLUGIN.getDataFolder() + "" + File.separatorChar + "exports" + File.separatorChar + "elitemobs_resource_pack.zip") + + " , ready to distribute!"); + else { + commandSender.sendMessage(ChatColorConverter.convert("&8[EliteMobs]&c Failed to package the resource pack into a zipped file! Report this to the dev!")); + return; + } + + if (commandSender instanceof Player) { + ((Player) commandSender).spigot().sendMessage(SpigotMessage.commandHoverMessage(ChatColorConverter.convert("Done! &2You can click here to update your server.properties with the new SHA1 value of this texture pack!"), + "Click runs the /em updateresourcepack command!", "/em updateresourcepack")); + commandSender.sendMessage("If you want to do it manually, your SHA1 code is " + generateResourcePackSHA1(commandSender)); + } else { + commandSender.sendMessage("Done! You can run the command /em updateresourcepack in order to put the right SHA1 value into server.properties. Don't forget to upload the texture place to some place where players can get it!"); + commandSender.sendMessage("If you want to do it manually, your SHA1 code is " + generateResourcePackSHA1(commandSender)); + } + + } + + private static String generateResourcePackSHA1(CommandSender commandSender) { + File zippedResourcePack = Paths.get(MetadataHandler.PLUGIN.getDataFolder() + "" + File.separatorChar + "exports" + File.separatorChar + "elitemobs_resource_pack.zip").toFile(); + if (!zippedResourcePack.exists()) { + commandSender.sendMessage("[EliteMobs] Failed to generate SHA-1 code, no zipped resource pack found!"); + return null; + } + String sha1 = null; + try { + sha1 = sha1Code(zippedResourcePack); + } catch (Exception ex) { + commandSender.sendMessage("[EliteMobs] Failed to generate SHA-1 code! Report this to the dev!"); + ex.printStackTrace(); + return null; + } + if (sha1 == null) { + commandSender.sendMessage("[EliteMobs] SHA-1 code is null! Report this to the dev!"); + return null; + } + return sha1; + } + + public static String sha1Code(File file) throws IOException, NoSuchAlgorithmException { + FileInputStream fileInputStream = new FileInputStream(file); + MessageDigest digest = MessageDigest.getInstance("SHA-1"); + DigestInputStream digestInputStream = new DigestInputStream(fileInputStream, digest); + byte[] bytes = new byte[1024]; + // read all file content + while (digestInputStream.read(bytes) > 0) + digest = digestInputStream.getMessageDigest(); + byte[] resultByteArry = digest.digest(); + return bytesToHexString(resultByteArry); + } + + public static String bytesToHexString(byte[] bytes) { + StringBuilder sb = new StringBuilder(); + for (byte b : bytes) { + int value = b & 0xFF; + if (value < 16) { + // if value less than 16, then it's hex String will be only + // one character, so we need to append a character of '0' + sb.append("0"); + } + sb.append(Integer.toHexString(value).toUpperCase()); + } + return sb.toString(); + } + + private static void copyDirectory(File directoryToClone, Path targetPath) { + for (File file : directoryToClone.listFiles()) + try { + new InfoMessage("Adding " + file.getCanonicalPath()); + copyFile(file, targetPath); + } catch (Exception exception) { + new WarningMessage("Failed to move directories for " + file.getName() + "! Tell the dev!"); + exception.printStackTrace(); + } + } + + private static void copyFile(File file, Path targetPath) { + try { + if (file.isDirectory()) { + if (!Paths.get(targetPath + "" + File.separatorChar + file.getName()).toFile().exists()) + Files.createDirectory(Paths.get(targetPath + "" + File.separatorChar + file.getName())); + for (File iteratedFile : file.listFiles()) + copyFile(iteratedFile, Paths.get(targetPath + "" + File.separatorChar + file.getName())); + } else { + if (!Paths.get(targetPath + "" + File.separatorChar + file.getName()).toFile().exists() || + !targetPath.toString().contains("pack.png") && !targetPath.toString().contains("pack.mcmeta")) + Files.copy(file.toPath(), Paths.get(targetPath + "" + File.separatorChar + file.getName()), StandardCopyOption.REPLACE_EXISTING); + else + new InfoMessage("File " + targetPath + "" + File.separatorChar + file.getName() + " already existed and should not be overwritten, skipping!"); + } + } catch (Exception exception) { + new WarningMessage("Failed to copy directories for " + file.getName() + "! Tell the dev!"); + exception.printStackTrace(); + } + } + + public static void overwriteSHA1(CommandSender commandSender) { + File serverProperties = null; + try { + serverProperties = new File(Paths.get(MetadataHandler.PLUGIN.getDataFolder().getParentFile().getCanonicalFile().getParentFile().toString() + File.separatorChar + "server.properties").toString()); + if (!serverProperties.exists()) { + commandSender.sendMessage("[EliteMobs] Could not find server.properties file correctly! You will have to set the SHA-1 value manually!"); + return; + } + } catch (Exception exception) { + new WarningMessage("[EliteMobs] Could not find server.properties file correctly! You will have to set the SHA-1 value manually."); + exception.printStackTrace(); + return; + } + + String sha1 = generateResourcePackSHA1(commandSender); + if (sha1 == null) return; + try { + FileInputStream in = new FileInputStream(serverProperties); + Properties props = new Properties(); + props.load(in); + in.close(); + + FileOutputStream out = new FileOutputStream(serverProperties); + props.setProperty("resource-pack-sha1", sha1); + props.store(out, null); + out.close(); + } catch (Exception ex) { + commandSender.sendMessage("[EliteMobs] Failed to save SHA1 value " + sha1 + " ! You will have to do this manually."); + } + commandSender.sendMessage(ChatColor.GREEN + "[EliteMobs] Successfully set the value resource-pack-sha1=" + sha1 + " in server.properties!"); + commandSender.sendMessage(ChatColor.RED + "[EliteMobs] Don't forget to update the downloadable resource pack at your online location of choice!" + + " If you don't update the version people download things won't work correctly!"); + commandSender.sendMessage(ChatColor.GREEN + "[EliteMobs] The server.properties modification will work starting with the next restart!"); + + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/ConfigurationImporter.java b/src/main/java/com/magmaguy/elitemobs/config/ConfigurationImporter.java new file mode 100644 index 000000000..0ac62df11 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/ConfigurationImporter.java @@ -0,0 +1,195 @@ +package com.magmaguy.elitemobs.config; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.thirdparty.modelengine.CustomModel; +import com.magmaguy.elitemobs.utils.InfoMessage; +import com.magmaguy.elitemobs.utils.SpigotMessage; +import com.magmaguy.elitemobs.utils.WarningMessage; +import com.magmaguy.elitemobs.utils.ZipFile; +import org.apache.commons.io.FileUtils; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; + +public class ConfigurationImporter { + private ConfigurationImporter() { + } + + public static void initializeConfigs() { + Path configurationsPath = Paths.get(MetadataHandler.PLUGIN.getDataFolder().getAbsolutePath()); + if (!Files.isDirectory(Paths.get(configurationsPath.normalize() + "" + File.separatorChar + "imports"))) { + try { + Files.createDirectory(Paths.get(configurationsPath.normalize() + "" + File.separatorChar + "imports")); + } catch (Exception exception) { + new WarningMessage("Failed to create import directory! Tell the dev!"); + exception.printStackTrace(); + } + return; + } + + File importsFile = null; + try { + importsFile = new File(Paths.get(MetadataHandler.PLUGIN.getDataFolder().getCanonicalPath() + File.separatorChar + "imports").toString()); + } catch (Exception ex) { + new WarningMessage("Failed to get imports folder! Report this to the dev!"); + return; + } + + if (importsFile.listFiles().length == 0) + return; + boolean importedModels = false; + + for (File zippedFile : importsFile.listFiles()) { + File unzippedFile; + try { + if (zippedFile.getName().contains(".zip")) + unzippedFile = ZipFile.unzip(zippedFile.getName()); + else unzippedFile = zippedFile; + } catch (Exception e) { + new WarningMessage("Failed to unzip config file " + zippedFile.getName() + " ! Tell the dev!"); + e.printStackTrace(); + continue; + } + try { + for (File file : unzippedFile.listFiles()) { + switch (file.getName()) { + case "custombosses": + moveDirectory(file, Paths.get(configurationsPath.normalize() + "" + File.separatorChar + "custombosses")); + break; + case "customitems": + moveDirectory(file, Paths.get(configurationsPath.normalize() + "" + File.separatorChar + "customitems")); + break; + case "customtreasurechests": + moveDirectory(file, Paths.get(configurationsPath.normalize() + "" + File.separatorChar + "customtreasurechests")); + break; + case "dungeonpackages": + moveDirectory(file, Paths.get(configurationsPath.normalize() + "" + File.separatorChar + "dungeonpackages")); + break; + case "customevents": + moveDirectory(file, Paths.get(configurationsPath.normalize() + "" + File.separatorChar + "customevents")); + break; + case "customspawns": + moveDirectory(file, Paths.get(configurationsPath.normalize() + "" + File.separatorChar + "customspawns")); + break; + case "customquests": + moveDirectory(file, Paths.get(configurationsPath.normalize() + "" + File.separatorChar + "customquests")); + break; + case "npcs": + moveDirectory(file, Paths.get(configurationsPath.normalize() + "" + File.separatorChar + "npcs")); + break; + case "wormholes": + moveDirectory(file, Paths.get(configurationsPath.normalize() + "" + File.separatorChar + "wormholes")); + break; + case "worldcontainer": + moveWorlds(file); + break; + case "ModelEngine": + if (Bukkit.getPluginManager().isPluginEnabled("ModelEngine")) { + moveDirectory(file, Paths.get(file.getParentFile().getParentFile().getParentFile().getParentFile().toString() + File.separatorChar + "ModelEngine" + File.separatorChar + "blueprints")); + importedModels = true; + } else new WarningMessage("You need ModelEngine to install custom models!"); + break; + case "schematics": + if (Bukkit.getPluginManager().isPluginEnabled("FastAsyncWorldEdit")) { + moveDirectory(file, Paths.get(file.getParentFile().getParentFile().getParentFile().getParentFile().toString() + File.separatorChar + "FastAsyncWorldEdit" + File.separatorChar + "schematics")); + } else if (Bukkit.getPluginManager().isPluginEnabled("WorldEdit")) { + moveDirectory(file, Paths.get(file.getParentFile().getParentFile().getParentFile().getParentFile().toString() + File.separatorChar + "WorldEdit" + File.separatorChar + "schematics")); + } else + new WarningMessage("You need WorldGuard or FastAsyncWorldEdit to install schematic-based minidungeons!"); + break; + default: + new WarningMessage("Directory " + file.getName() + " for zipped file " + zippedFile.getName() + " was not a recognized directory for the file import system! Was the zipped file packaged correctly?"); + } + deleteDirectory(file); + } + } catch (Exception e) { + new WarningMessage("Failed to move files from " + zippedFile.getName() + " ! Tell the dev!"); + e.printStackTrace(); + continue; + } + try { + unzippedFile.delete(); + zippedFile.delete(); + } catch (Exception ex) { + new WarningMessage("Failed to delete zipped file " + zippedFile.getName() + "! Tell the dev!"); + ex.printStackTrace(); + } + } + + if (importedModels) { + CustomModel.reloadModels(); + for (Player player : Bukkit.getOnlinePlayers()) + if (player.hasPermission("elitemobs.*")) + player.spigot().sendMessage(SpigotMessage.commandHoverMessage( + ChatColorConverter.convert("&8[EliteMobs] &fEliteMobs just detected that recently imported files had Custom Models in them! " + + "&2Click here to generate the EliteMobs resource pack for those models!"), + "Clicking will run the command /em generateresourcepack", + "/em generateresourcepack")); + } + + } + + private static void deleteDirectory(File file) { + if (file == null) + return; + if (file.isDirectory()) + for (File iteratedFile : file.listFiles()) + if (iteratedFile != null) + deleteDirectory(iteratedFile); + new InfoMessage("Cleaning up " + file.getPath()); + file.delete(); + } + + private static void moveWorlds(File worldcontainerFile) { + for (File file : worldcontainerFile.listFiles()) + try { + File destinationFile = new File(Paths.get(Bukkit.getWorldContainer().getCanonicalPath() + File.separatorChar + file.getName()).normalize().toString()); + if (destinationFile.exists()) { + new InfoMessage("Overriding existing directory " + destinationFile.getPath()); + if (Bukkit.getWorld(file.getName()) != null) { + Bukkit.unloadWorld(file.getName(), false); + new WarningMessage("Unloaded world " + file.getName() + " for safe replacement!"); + } + deleteDirectory(destinationFile); + } + FileUtils.moveDirectory(file, destinationFile); + } catch (Exception exception) { + new WarningMessage("Failed to move worlds for " + file.getName() + "! Tell the dev!"); + exception.printStackTrace(); + } + } + + private static void moveDirectory(File unzippedDirectory, Path targetPath) { + for (File file : unzippedDirectory.listFiles()) + try { + new InfoMessage("Adding " + file.getCanonicalPath()); + moveFile(file, targetPath); + } catch (Exception exception) { + new WarningMessage("Failed to move directories for " + file.getName() + "! Tell the dev!"); + exception.printStackTrace(); + } + } + + private static void moveFile(File file, Path targetPath) { + try { + if (file.isDirectory()) { + if (Paths.get(targetPath + "" + File.separatorChar + file.getName()).toFile().exists()) + for (File iteratedFile : file.listFiles()) + moveFile(iteratedFile, Paths.get(targetPath + "" + File.separatorChar + file.getName())); + else + Files.move(file.toPath(), Paths.get(targetPath + "" + File.separatorChar + file.getName()), StandardCopyOption.REPLACE_EXISTING); + } else + Files.move(file.toPath(), Paths.get(targetPath + "" + File.separatorChar + file.getName()), StandardCopyOption.REPLACE_EXISTING); + } catch (Exception exception) { + new WarningMessage("Failed to move directories for " + file.getName() + "! Tell the dev!"); + exception.printStackTrace(); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/CustomConfig.java b/src/main/java/com/magmaguy/elitemobs/config/CustomConfig.java new file mode 100644 index 000000000..2ead0ea97 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/CustomConfig.java @@ -0,0 +1,175 @@ +package com.magmaguy.elitemobs.config; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.utils.WarningMessage; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; +import org.reflections.Reflections; + +import java.io.File; +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.*; + +public class CustomConfig { + + //This stores configurations long term, ? is the specific extended custom config field + private final HashMap customConfigFieldsHashMap = new HashMap<>(); + //This is only used for loading configurations in to check if the machine has all of the default files + private final List customConfigFieldsArrayList = new ArrayList<>(); + private final String folderName; + private final Class customConfigFields; + + /** + * Initializes all configurations and stores them in a list for later access + */ + public CustomConfig(String folderName, String packageName, Class customConfigFields) { + this.folderName = folderName; + this.customConfigFields = customConfigFields; + + //Set defaults through reflections by getting everything that extends specific CustomConfigFields within specific package scopes + Reflections reflections = new Reflections(packageName); + + Set classSet = new HashSet<>(reflections.getSubTypesOf(customConfigFields)); + classSet.forEach(aClass -> { + try { + customConfigFieldsArrayList.add(aClass.newInstance()); + } catch (Exception ex) { + new WarningMessage("Failed to generate plugin default classes for " + folderName + " ! This is very bad, warn the developer!"); + ex.printStackTrace(); + } + }); + + //Check if the directory doesn't exist + try { + if (!Files.isDirectory(Paths.get(MetadataHandler.PLUGIN.getDataFolder().getPath() + File.separatorChar + folderName))) { + generateFreshConfigurations(); + return; + } + } catch (Exception ex) { + new WarningMessage("Failed to generate plugin default files for " + folderName + " ! This is very bad, warn the developer!"); + ex.printStackTrace(); + return; + } + + //Runs if the directory exists + //Check if all the defaults exist + directoryCrawler(MetadataHandler.PLUGIN.getDataFolder().getPath() + File.separatorChar + folderName); + + try { + //Generate missing default config files, might've been deleted or might have been added in newer version + if (!customConfigFieldsArrayList.isEmpty()) + generateFreshConfigurations(); + } catch (Exception ex) { + new WarningMessage("Failed to finish generating default plugin files for " + folderName + " ! This is very bad, warn the developer!"); + ex.printStackTrace(); + return; + } + + } + + private void directoryCrawler(String path) { + for (File file : Objects.requireNonNull((new File(path)).listFiles())) { + if (file.isFile()) + fileInitializer(file); + else if (file.isDirectory()) + directoryCrawler(file.getPath()); + } + } + + private void fileInitializer(File file) { + + boolean isPremade = false; + for (Object object : customConfigFieldsArrayList) { + try { + Method getFilename = CustomConfigFields.class.getDeclaredMethod("getFilename"); + if (file.getName().equalsIgnoreCase((String) getFilename.invoke(object))) { + customConfigFieldsArrayList.remove(object); + initialize((CustomConfigFields) object); + isPremade = true; + break; + } + } catch (Exception ex) { + new WarningMessage("Failed to read plugin files for " + folderName + " ! This is very bad, warn the developer!"); + isPremade = true; + ex.printStackTrace(); + } + } + if (!isPremade) + initialize(file); + + } + + public HashMap getCustomConfigFieldsHashMap() { + return customConfigFieldsHashMap; + } + + /** + * Adds entry to custom config fields. This is done directly by the custom config fields as they are iterated through. + * + * @param filename Name of the file , using the format filename.yml + * @param customConfigFields Custom Config Fields, should be from an extended subclass + */ + public void addCustomConfigFields(String filename, CustomConfigFields customConfigFields) { + customConfigFieldsHashMap.put(filename, customConfigFields); + } + + /** + * Called when the appropriate configurations directory does not exist + */ + private void generateFreshConfigurations() { + for (Object customConfigFields : customConfigFieldsArrayList) + initialize((CustomConfigFields) customConfigFields); + } + + /** + * Initializes a single instance of a premade configuration using the default values. Writes defaults. + */ + private void initialize(CustomConfigFields customConfigFields) { + //Create configuration file from defaults if it does not exist + File file = ConfigurationEngine.fileCreator(folderName, customConfigFields.getFilename()); + //Get config file + FileConfiguration fileConfiguration = ConfigurationEngine.fileConfigurationCreator(file); + + //Associate config + customConfigFields.setFile(file); + customConfigFields.setFileConfiguration(fileConfiguration); + + //Parse actual fields and load into RAM to be used + customConfigFields.processConfigFields(); + + //Save all configuration values as they exist + ConfigurationEngine.fileSaverCustomValues(fileConfiguration, file); + + //if (customConfigFields.isEnabled) + //Store for use by the plugin + addCustomConfigFields(file.getName(), customConfigFields); + } + + /** + * Called when a user-made file is detected. + */ + private void initialize(File file) { + //Load file configuration from file + try { + FileConfiguration fileConfiguration = YamlConfiguration.loadConfiguration(file); + //Instantiate the correct CustomConfigFields instance + Constructor constructor = customConfigFields.getConstructor(String.class, boolean.class); + CustomConfigFields instancedCustomConfigFields = (CustomConfigFields) constructor.newInstance(file.getName(), true); + instancedCustomConfigFields.setFileConfiguration(fileConfiguration); + instancedCustomConfigFields.setFile(file); + //Parse actual fields and load into RAM to be used + instancedCustomConfigFields.processConfigFields(); + //if (instancedCustomConfigFields.isEnabled) + //Store for use by the plugin + addCustomConfigFields(file.getName(), instancedCustomConfigFields); + } catch (Exception ex) { + new WarningMessage("Bad constructor for file " + file.getName()); + ex.printStackTrace(); + } + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/CustomConfigConstructor.java b/src/main/java/com/magmaguy/elitemobs/config/CustomConfigConstructor.java deleted file mode 100644 index 10f18ba99..000000000 --- a/src/main/java/com/magmaguy/elitemobs/config/CustomConfigConstructor.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.config; - -/** - * Created by MagmaGuy on 01/05/2017. - */ - -import com.magmaguy.elitemobs.MetadataHandler; -import org.bukkit.Bukkit; -import org.bukkit.configuration.InvalidConfigurationException; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.plugin.Plugin; - -import java.io.File; -import java.io.IOException; -import java.io.InputStreamReader; - -public class CustomConfigConstructor extends YamlConfiguration { - - Plugin plugin = Bukkit.getPluginManager().getPlugin(MetadataHandler.ELITE_MOBS); - private File file; - private String defaults; - - /** - * Creates new PluginFile, without defaults - * - * @param fileName - Name of the file - */ - public CustomConfigConstructor(String fileName) { - this(fileName, null); - } - - /** - * Creates new PluginFile, with defaults - * - * @param fileName - Name of the file - * @param defaultsName - Name of the defaults - */ - public CustomConfigConstructor(String fileName, String defaultsName) { - this.defaults = defaultsName; - File newFile = new File(plugin.getDataFolder().getPath()+"/data"); - Bukkit.getLogger().info("ATTENTION: " + newFile.toString()); - this.file = new File(newFile, fileName); - reload(); - } - - /** - * Reload configuration - */ - public void reload() { - - if (!file.exists()) { - - try { - file.getParentFile().mkdirs(); - file.createNewFile(); - - } catch (IOException exception) { - exception.printStackTrace(); - plugin.getLogger().severe("Error while creating file " + file.getName()); - } - - } - - try { - load(file); - - if (defaults != null) { - InputStreamReader reader = new InputStreamReader(plugin.getResource(defaults)); - FileConfiguration defaultsConfig = YamlConfiguration.loadConfiguration(reader); - - setDefaults(defaultsConfig); - options().copyDefaults(true); - - reader.close(); - save(); - } - - } catch (IOException exception) { - exception.printStackTrace(); - plugin.getLogger().severe("Error while loading file " + file.getName()); - - } catch (InvalidConfigurationException exception) { - exception.printStackTrace(); - plugin.getLogger().severe("Error while loading file " + file.getName()); - - } - - } - - /** - * Save configuration - */ - public void save() { - - try { - options().indent(2); - save(file); - - } catch (IOException exception) { - exception.printStackTrace(); - plugin.getLogger().severe("Error while saving file " + file.getName()); - } - - } - -} \ No newline at end of file diff --git a/src/main/java/com/magmaguy/elitemobs/config/CustomConfigFields.java b/src/main/java/com/magmaguy/elitemobs/config/CustomConfigFields.java new file mode 100644 index 000000000..1989dcbbe --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/CustomConfigFields.java @@ -0,0 +1,354 @@ +package com.magmaguy.elitemobs.config; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.utils.ConfigurationLocation; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import com.magmaguy.elitemobs.utils.WarningMessage; +import org.bukkit.*; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.LeatherArmorMeta; +import org.bukkit.inventory.meta.SkullMeta; +import org.bukkit.util.Vector; + +import java.io.File; +import java.util.*; + +public class CustomConfigFields implements CustomConfigFieldsInterface { + + protected String filename; + protected boolean isEnabled; + protected FileConfiguration fileConfiguration; + protected File file; + + /** + * Used by plugin-generated files (defaults) + * + * @param filename + * @param isEnabled + */ + public CustomConfigFields(String filename, boolean isEnabled) { + this.filename = filename.contains(".yml") ? filename : filename + ".yml"; + this.isEnabled = isEnabled; + } + + public String getFilename() { + return filename; + } + + public boolean isEnabled() { + return isEnabled; + } + + public void setEnabled(boolean enabled) { + isEnabled = enabled; + } + + public FileConfiguration getFileConfiguration() { + return fileConfiguration; + } + + public void setFileConfiguration(FileConfiguration fileConfiguration) { + this.fileConfiguration = fileConfiguration; + } + + public File getFile() { + return file; + } + + public void setFile(File file) { + this.file = file; + } + + @Override + public void processConfigFields() { + + } + + protected boolean configHas(String configKey) { + return fileConfiguration.contains(configKey); + } + + protected String processString(String path, String value, String pluginDefault, boolean forceWriteDefault) { + if (!configHas(path)) { + if (forceWriteDefault || !Objects.equals(value, pluginDefault)) + fileConfiguration.addDefault(path, value); + return value; + } + try { + return ChatColorConverter.convert(fileConfiguration.getString(path)); + } catch (Exception ex) { + new WarningMessage("File " + filename + " has an incorrect entry for " + path); + new WarningMessage("Entry: " + value); + } + return value; + } + + public List processStringList(String path, List value, List pluginDefault, boolean forceWriteDefault) { + if (!configHas(path)) { + if (forceWriteDefault || value != pluginDefault) + fileConfiguration.addDefault(path, value); + return value; + } + try { + List list = new ArrayList<>(); + for (String string : fileConfiguration.getStringList(path)) + list.add(ChatColorConverter.convert(string)); + return list; + } catch (Exception ex) { + new WarningMessage("File " + filename + " has an incorrect entry for " + path); + new WarningMessage("Entry: " + value); + } + return value; + } + + /** + * This not only gets a list of worlds, but gets a list of already loaded worlds. This might cause issues if the worlds + * aren't loaded when the code for getting worlds runs. + * + * @param path Configuration path + * @param pluginDefault Default value - should be null or empty + * @return Worlds from the list that are loaded at the time this runs, probably on startup + */ + protected List processWorldList(String path, List value, List pluginDefault, boolean forceWriteDefault) { + if (!configHas(path)) { + if (value != null && (forceWriteDefault || value != pluginDefault)) + processStringList(path, worldListToStringListConverter(value), worldListToStringListConverter(pluginDefault), forceWriteDefault); + return value; + } + try { + List validWorldStrings = processStringList(path, worldListToStringListConverter(pluginDefault), worldListToStringListConverter(value), forceWriteDefault); + List validWorlds = new ArrayList<>(); + if (!validWorldStrings.isEmpty()) + for (String string : validWorldStrings) { + World world = Bukkit.getWorld(string); + if (world != null) + validWorlds.add(world); + } + return validWorlds; + } catch (Exception ex) { + new WarningMessage("File " + filename + " has an incorrect entry for " + path); + new WarningMessage("Entry: " + value); + } + return value; + } + + private List worldListToStringListConverter(List pluginDefault) { + if (pluginDefault == null) return null; + List newList = new ArrayList<>(); + pluginDefault.forEach((element) -> newList.add(element.getName())); + return newList; + } + + + protected > List processEnumList(String path, List value, List pluginDefault, Class enumClass, boolean forceWriteDefault) { + if (!configHas(path)) { + if (forceWriteDefault || value != pluginDefault) + processStringList(path, enumListToStringListConverter(value), enumListToStringListConverter(pluginDefault), forceWriteDefault); + return value; + } + try { + List newList = new ArrayList<>(); + List stringList = processStringList(path, enumListToStringListConverter(value), enumListToStringListConverter(pluginDefault), forceWriteDefault); + stringList.forEach(string -> { + try { + newList.add(Enum.valueOf(enumClass, string.toUpperCase())); + } catch (Exception ex) { + new WarningMessage(filename + " : " + "Value " + string + " is not a valid for " + path + " ! This may be due to your server version, or due to an invalid value!"); + } + }); + return newList; + } catch ( + Exception ex) { + ex.printStackTrace(); + new WarningMessage("File " + filename + " has an incorrect entry for " + path); + new WarningMessage("Entry: " + value); + } + return value; + } + + private > List enumListToStringListConverter(List list) { + if (list == null) return Collections.emptyList(); + List newList = new ArrayList<>(); + list.forEach(element -> newList.add(element.toString())); + return newList; + } + + protected int processInt(String path, int value, int pluginDefault, boolean forceWriteDefault) { + if (!configHas(path)) { + if (forceWriteDefault || value != pluginDefault) fileConfiguration.addDefault(path, value); + return value; + } + try { + return fileConfiguration.getInt(path); + } catch (Exception ex) { + new WarningMessage("File " + filename + " has an incorrect entry for " + path); + new WarningMessage("Entry: " + value); + } + return value; + } + + protected long processLong(String path, long value, long pluginDefault, boolean forceWriteDefault) { + if (!configHas(path)) { + if (forceWriteDefault || value != pluginDefault) fileConfiguration.addDefault(path, value); + return value; + } + try { + return fileConfiguration.getLong(path); + } catch (Exception ex) { + new WarningMessage("File " + filename + " has an incorrect entry for " + path); + new WarningMessage("Entry: " + value); + } + return value; + } + + + protected double processDouble(String path, double value, double pluginDefault, boolean forceWriteDefault) { + if (!configHas(path)) { + if (forceWriteDefault || value != pluginDefault) fileConfiguration.addDefault(path, value); + return value; + } + try { + return fileConfiguration.getDouble(path); + } catch (Exception ex) { + new WarningMessage("File " + filename + " has an incorrect entry for " + path); + new WarningMessage("Entry: " + value); + } + return value; + } + + protected Double processDouble(String path, Double value, Double pluginDefault, boolean forceWriteDefault) { + if (!configHas(path)) { + if (forceWriteDefault || !Objects.equals(value, pluginDefault)) fileConfiguration.addDefault(path, value); + return value; + } + try { + return fileConfiguration.getDouble(path); + } catch (Exception ex) { + new WarningMessage("File " + filename + " has an incorrect entry for " + path); + new WarningMessage("Entry: " + value); + } + return value; + } + + protected boolean processBoolean(String path, boolean value, boolean pluginDefault, boolean forceWriteDefault) { + if (!configHas(path)) { + if (forceWriteDefault || value != pluginDefault) fileConfiguration.addDefault(path, value); + return value; + } + try { + return fileConfiguration.getBoolean(path); + } catch (Exception ex) { + new WarningMessage("File " + filename + " has an incorrect entry for " + path); + new WarningMessage("Entry: " + value); + } + return value; + } + + public > T processEnum(String path, T value, T pluginDefault, Class enumClass, boolean forceWriteDefault) { + if (!configHas(path)) { + if (forceWriteDefault || value != pluginDefault) { + String valueString = null; + if (value != null) + valueString = value.toString().toUpperCase(); + String pluginDefaultString = null; + if (pluginDefault != null) + pluginDefaultString = pluginDefault.toString().toUpperCase(); + processString(path, valueString, pluginDefaultString, forceWriteDefault); + } + return value; + } + try { + return (T) Enum.valueOf(enumClass, fileConfiguration.getString(path).toUpperCase()); + } catch (Exception ex) { + new WarningMessage("File " + filename + " has an incorrect entry for " + path); + new WarningMessage("Entry: " + value); + } + return value; + } + + public ItemStack processItemStack(String path, ItemStack value, ItemStack pluginDefault, boolean forceWriteDefault) { + if (!configHas(path)) { + if (forceWriteDefault || value != pluginDefault) + processString(path, itemStackDeserializer(value), itemStackDeserializer(pluginDefault), forceWriteDefault); + return value; + } + try { + String materialString = processString(path, itemStackDeserializer(value), itemStackDeserializer(pluginDefault), forceWriteDefault); + if (materialString == null) + return null; + if (materialString.matches("[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}")) { + ItemStack playerHead = new ItemStack(Material.PLAYER_HEAD); + SkullMeta skullMeta = (SkullMeta) playerHead.getItemMeta(); + skullMeta.setOwningPlayer(Bukkit.getOfflinePlayer(UUID.fromString(materialString))); + playerHead.setItemMeta(skullMeta); + return playerHead; + } + if (materialString.contains(":")) { + ItemStack itemStack = ItemStackGenerator.generateItemStack(Material.getMaterial(materialString.split(":")[0])); + if (materialString.split(":")[0].contains("leather_") || materialString.split(":")[0].contains("LEATHER_")) { + LeatherArmorMeta leatherArmorMeta = (LeatherArmorMeta) itemStack.getItemMeta(); + leatherArmorMeta.setColor(Color.fromRGB(Integer.parseInt(materialString.split(":")[1]))); + itemStack.setItemMeta(leatherArmorMeta); + } else { + ItemMeta itemMeta = itemStack.getItemMeta(); + itemMeta.setCustomModelData(Integer.parseInt(materialString.split(":")[1])); + itemStack.setItemMeta(itemMeta); + } + return itemStack; + } else + return ItemStackGenerator.generateItemStack(Material.getMaterial(materialString)); + } catch (Exception ex) { + new WarningMessage("File " + filename + " has an incorrect entry for " + path); + new WarningMessage("Entry: " + value); + } + return value; + } + + private String itemStackDeserializer(ItemStack itemStack) { + if (itemStack == null) return null; + return itemStack.getType().toString(); + } + + protected Location processLocation(String path, Location value, String pluginDefault, boolean forceWriteDefault) { + if (!configHas(path)) { + if (forceWriteDefault || !Objects.equals(value, pluginDefault)) + fileConfiguration.addDefault(path, ConfigurationLocation.deserialize(value)); + return value; + } + try { + return ConfigurationLocation.serialize(fileConfiguration.getString(path)); + } catch (Exception ex) { + new WarningMessage("File " + filename + " has an incorrect entry for " + path); + new WarningMessage("Entry: " + value); + } + return null; + } + + protected Vector processVector(String path, Vector value, Vector pluginDefault, boolean forceWriteDefault) { + if (!configHas(path)) { + if (forceWriteDefault || !Objects.equals(value, pluginDefault)) + if (pluginDefault != null) { + String vectorString = value.getX() + "," + value.getY() + "," + value.getZ(); + fileConfiguration.addDefault(path, vectorString); + } + return value; + } + try { + String string = fileConfiguration.getString(path); + if (string == null) return null; + String[] strings = string.split(","); + if (strings.length < 3) { + new WarningMessage("File " + filename + " has an incorrect entry for " + path); + return null; + } + return new Vector(Double.parseDouble(strings[0]), Double.parseDouble(strings[1]), Double.parseDouble(strings[2])); + } catch (Exception ex) { + new WarningMessage("File " + filename + " has an incorrect entry for " + path); + new WarningMessage("Entry: " + value); + } + return null; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/CustomConfigFieldsInterface.java b/src/main/java/com/magmaguy/elitemobs/config/CustomConfigFieldsInterface.java new file mode 100644 index 000000000..54c1d999f --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/CustomConfigFieldsInterface.java @@ -0,0 +1,5 @@ +package com.magmaguy.elitemobs.config; + +public interface CustomConfigFieldsInterface { + void processConfigFields(); +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/CustomConfigLoader.java b/src/main/java/com/magmaguy/elitemobs/config/CustomConfigLoader.java deleted file mode 100644 index 0c3c6e048..000000000 --- a/src/main/java/com/magmaguy/elitemobs/config/CustomConfigLoader.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.config; - -import com.magmaguy.elitemobs.MetadataHandler; -import org.bukkit.Bukkit; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.plugin.Plugin; - -import java.io.*; -import java.util.logging.Level; - -/** - * Created by MagmaGuy on 01/05/2017. - */ -public class CustomConfigLoader { - - Plugin plugin = Bukkit.getPluginManager().getPlugin(MetadataHandler.ELITE_MOBS); - private FileConfiguration customConfig = null; - private File customConfigFile = null; - - public FileConfiguration getCustomConfig(String configName) { - - return getCustomConfig(configName, false); - - } - - public FileConfiguration getCustomConfig(String configName, boolean isDataFile) { - - if (customConfig == null) { - - reloadCustomConfig(configName, isDataFile); - - } - - return customConfig; - } - - public void reloadCustomConfig(String configName, boolean isDataFile) { - - if (customConfigFile == null && !isDataFile) { - - customConfigFile = new File(plugin.getDataFolder(), configName); - - } - - if (customConfigFile == null && isDataFile) { - - customConfigFile = new File(plugin.getDataFolder(), "data/" + configName); - - if (!customConfigFile.exists()) customConfigFile.getParentFile().mkdirs(); - - } - - customConfig = YamlConfiguration.loadConfiguration(customConfigFile); - - // Look for defaults in the jar - Reader defConfigStream = null; - - try { - - defConfigStream = new InputStreamReader(plugin.getResource(configName), "UTF8"); - - } catch (UnsupportedEncodingException e) { - - e.printStackTrace(); - } - - if (defConfigStream != null) { - - YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(customConfigFile); - - customConfig = defConfig; - - } - - } - - public void saveCustomConfig(String configName) { - - if (customConfig == null || customConfigFile == null) { - - return; - - } - - try { - - getCustomConfig(configName).save(customConfigFile); - - } catch (IOException ex) { - - Bukkit.getLogger().log(Level.SEVERE, "Could not save config to " + customConfigFile, ex); - - } - - } - - public void saveCustomConfig(String configName, boolean isDataFile) { - - if (customConfig == null || customConfigFile == null) { - - return; - - } - - if (!isDataFile) return; - - try { - - getCustomConfig(configName).save(customConfigFile); - - } catch (IOException ex) { - - Bukkit.getLogger().log(Level.SEVERE, "Could not save config to " + customConfigFile, ex); - - } - - } - - public void saveDefaultCustomConfig(String configName) { - - if (customConfigFile == null) { - - customConfigFile = new File(plugin.getDataFolder(), configName); - - } - - if (!customConfigFile.exists()) { - - plugin.saveResource(configName, false); - - } - - } - - public void saveDefaultCustomConfig(String configName, boolean isDataFile) { - - if (customConfigFile == null && isDataFile) { - - customConfigFile = new File(plugin.getDataFolder(), "data/" + configName); - - } - - if (!customConfigFile.exists()) { - - plugin.saveResource(configName, false); - - } - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/config/CustomEnchantmentsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/CustomEnchantmentsConfig.java deleted file mode 100644 index 67e54c361..000000000 --- a/src/main/java/com/magmaguy/elitemobs/config/CustomEnchantmentsConfig.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.magmaguy.elitemobs.config; - -import org.bukkit.configuration.Configuration; - -public class CustomEnchantmentsConfig{ - - public static final String CONFIG_NAME = "CustomEnchantments.yml"; - private CustomConfigLoader customConfigLoader = new CustomConfigLoader(); - private Configuration configuration = customConfigLoader.getCustomConfig(CONFIG_NAME); - - public static String HUNTER_NAME = "HunterEnchantment enchantment name"; - public static String HUNTER_SPAWN_BONUS = "Percentual elite mob increase in spawn rate around the player per hunter enchantment level"; - public static String FLAMETHROWER_NAME = "FlamethrowerEnchantment enchantment name"; - - public void initializeConfig() { - - configuration.addDefault(HUNTER_NAME, "HunterEnchantment"); - configuration.addDefault(HUNTER_SPAWN_BONUS, 2); - configuration.addDefault(FLAMETHROWER_NAME, "FlamethrowerEnchantment"); - - customConfigLoader.getCustomConfig(CONFIG_NAME).options().copyDefaults(true); - UnusedNodeHandler.clearNodes(configuration); - customConfigLoader.saveDefaultCustomConfig(CONFIG_NAME); - customConfigLoader.saveCustomConfig(CONFIG_NAME); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/config/DefaultConfig.java b/src/main/java/com/magmaguy/elitemobs/config/DefaultConfig.java index 81b45ffeb..31a06dae3 100644 --- a/src/main/java/com/magmaguy/elitemobs/config/DefaultConfig.java +++ b/src/main/java/com/magmaguy/elitemobs/config/DefaultConfig.java @@ -1,77 +1,100 @@ -/* - * 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 . - */ - package com.magmaguy.elitemobs.config; -import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.utils.ConfigurationLocation; +import com.magmaguy.elitemobs.utils.WarningMessage; +import lombok.Getter; import org.bukkit.Bukkit; -import org.bukkit.configuration.Configuration; +import org.bukkit.Location; +import org.bukkit.configuration.file.FileConfiguration; + +import java.io.File; /** * Created by MagmaGuy on 08/06/2017. */ public class DefaultConfig { - - public static final String ALWAYS_SHOW_NAMETAGS = "Always show Elite Mob nametags"; - public static final String SUPERMOB_STACK_AMOUNT = "SuperMob (passive EliteMobs) stack amount"; - public static final String MMORPG_COLORS = "Use MMORPG colors for item ranks"; - public static final String CREEPER_PASSIVE_DAMAGE_PREVENTER = "Prevent creepers from killing passive mobs"; - public static final String ENABLE_PERMISSION_TITLES = "Use titles to warn players they are missing a permission"; - public static final String ENABLE_POWER_SCOREBOARDS = "Use scoreboards to display mob powers using permissions"; - public static final String HIDE_ENCHANTMENTS_ATTRIBUTE = "Hide enchantment attributes on plugin-generated items"; - public static final String PREVENT_ITEM_PICKUP = "Prevent item pickup from all aggressive mobs"; - public static final String PREVENT_ELITE_MOB_CONVERSION_OF_NAMED_MOBS = "Make aggressive named mobs unable to become Elite Mobs"; - public static final String PREVENT_MOUNT_EXPLOIT = "Prevent Minecraft living entity mount exploit for Elite Mobs"; - public static final String STRICT_SPAWNING_RULES = "Strict spawning rules mode for better compatibility with other plugins"; - public static final String PREVENT_TOWER_EXPLOIT = "Prevent tower exploit"; - public static final String PREVENT_DARKROOM_EXPLOIT = "Prevent dark room spawner exploit"; - - public static void reloadConfig() { - - Bukkit.getPluginManager().getPlugin("EliteMobs").reloadConfig(); - + @Getter + private static boolean alwaysShowNametags; + @Getter + private static int superMobStackAmount; + @Getter + private static boolean preventCreeperDamageToPassiveMobs; + @Getter + private static boolean doPermissionTitles; + @Getter + private static boolean preventEliteMobConversionOfNamedMobs; + @Getter + private static boolean doStrictSpawningRules; + @Getter + private static double nightmareWorldSpawnBonus; + @Getter + private static boolean emLeadsToStatusMenu; + @Getter + private static boolean otherCommandsLeadToEMStatusMenu; + @Getter + private static boolean setupDone; + @Getter + private static Location defaultSpawnLocation; + @Getter + private static boolean doExplosionRegen; + @Getter + private static boolean preventVanillaReinforcementsForEliteEntities; + @Getter + private static boolean doRegenerateContainers; + @Getter + private static int defaultTransitiveBlockLimiter; + @Getter + private static boolean onlyUseBedrockMenus; + @Getter + private static int characterLimitForBookMenuPages; + + private static File file = null; + private static FileConfiguration fileConfiguration = null; + private DefaultConfig() { } - public void loadConfiguration() { - - Configuration configuration = Bukkit.getPluginManager().getPlugin(MetadataHandler.ELITE_MOBS).getConfig(); - - configuration.addDefault(SUPERMOB_STACK_AMOUNT, 50); - configuration.addDefault(MMORPG_COLORS, true); - configuration.addDefault(CREEPER_PASSIVE_DAMAGE_PREVENTER, true); - configuration.addDefault(ENABLE_PERMISSION_TITLES, true); - configuration.addDefault(ENABLE_POWER_SCOREBOARDS, false); - configuration.addDefault(ALWAYS_SHOW_NAMETAGS, true); - configuration.addDefault(HIDE_ENCHANTMENTS_ATTRIBUTE, false); - configuration.addDefault(PREVENT_ITEM_PICKUP, false); - configuration.addDefault(PREVENT_ELITE_MOB_CONVERSION_OF_NAMED_MOBS, true); - configuration.addDefault(STRICT_SPAWNING_RULES, false); - configuration.addDefault(PREVENT_MOUNT_EXPLOIT, true); - configuration.addDefault(PREVENT_TOWER_EXPLOIT, true); - configuration.addDefault(PREVENT_DARKROOM_EXPLOIT, true); - - configuration.options().copyDefaults(true); - - UnusedNodeHandler.clearNodes(configuration); + public static void toggleSetupDone() { + setupDone = !setupDone; + fileConfiguration.set("setupDoneV3", setupDone); + save(); + } - //save the config when changed - Bukkit.getPluginManager().getPlugin(MetadataHandler.ELITE_MOBS).saveConfig(); - Bukkit.getPluginManager().getPlugin(MetadataHandler.ELITE_MOBS).saveDefaultConfig(); + public static void save() { + ConfigurationEngine.fileSaverOnlyDefaults(fileConfiguration, file); + } - Bukkit.getLogger().info("EliteMobs config loaded!"); + public static void initializeConfig() { + + file = ConfigurationEngine.fileCreator("config.yml"); + fileConfiguration = ConfigurationEngine.fileConfigurationCreator(file); + alwaysShowNametags = ConfigurationEngine.setBoolean(fileConfiguration, "alwaysShowEliteMobNameTags", false); + superMobStackAmount = Math.max(ConfigurationEngine.setInt(fileConfiguration, "superMobStackAmount", 50), 1); + preventCreeperDamageToPassiveMobs = ConfigurationEngine.setBoolean(fileConfiguration, "preventEliteCreeperDamageToPassiveMobs", true); + doPermissionTitles = ConfigurationEngine.setBoolean(fileConfiguration, "useTitlesForMissingPermissionMessages", true); + preventEliteMobConversionOfNamedMobs = ConfigurationEngine.setBoolean(fileConfiguration, "preventEliteMobConversionOfNamedMobs", true); + doStrictSpawningRules = ConfigurationEngine.setBoolean(fileConfiguration, "enableHighCompatibilityMode", false); + nightmareWorldSpawnBonus = ConfigurationEngine.setDouble(fileConfiguration, "nightmareWorldSpawnBonus", 0.5); + emLeadsToStatusMenu = ConfigurationEngine.setBoolean(fileConfiguration, "emLeadsToStatusMenu", true); + otherCommandsLeadToEMStatusMenu = ConfigurationEngine.setBoolean(fileConfiguration, "otherCommandsLeadToEMStatusMenu", true); + setupDone = ConfigurationEngine.setBoolean(fileConfiguration, "setupDoneV3", false); + preventVanillaReinforcementsForEliteEntities = ConfigurationEngine.setBoolean(fileConfiguration, "preventVanillaReinforcementsForEliteEntities", true); + try { + defaultSpawnLocation = ConfigurationLocation.serialize( + ConfigurationEngine.setString( + fileConfiguration, "defaultSpawnLocation", + ConfigurationLocation.deserialize(Bukkit.getWorlds().get(0).getSpawnLocation()))); + } catch (Exception ex) { + new WarningMessage("There is an issue with your defaultSpawnLocation in the config.yml configuration file! Fix it!"); + } + + doExplosionRegen = ConfigurationEngine.setBoolean(fileConfiguration, "doExplosionRegen", true); + doRegenerateContainers = ConfigurationEngine.setBoolean(fileConfiguration, "doRegenerateContainers", true); + defaultTransitiveBlockLimiter = ConfigurationEngine.setInt(fileConfiguration, "defaultTransitiveBlockLimiter", 500); + onlyUseBedrockMenus = ConfigurationEngine.setBoolean(fileConfiguration, "onlyUseBedrockMenus", false); + characterLimitForBookMenuPages = ConfigurationEngine.setInt(fileConfiguration, "characterLimitForBookMenuPages", 185); + + ConfigurationEngine.fileSaverOnlyDefaults(fileConfiguration, file); } } diff --git a/src/main/java/com/magmaguy/elitemobs/config/DiscordSRVConfig.java b/src/main/java/com/magmaguy/elitemobs/config/DiscordSRVConfig.java new file mode 100644 index 000000000..645deda46 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/DiscordSRVConfig.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config; + +import lombok.Getter; +import org.bukkit.configuration.file.FileConfiguration; + +import java.io.File; + +public class DiscordSRVConfig { + + @Getter + private static String announcementRoomName; + + public static void initializeConfig() { + File file = ConfigurationEngine.fileCreator("DiscordSRV.yml"); + FileConfiguration fileConfiguration = ConfigurationEngine.fileConfigurationCreator(file); + + announcementRoomName = ConfigurationEngine.setString(fileConfiguration, "announcementRoomName", + "YOU_NEED_TO_PUT_THE_NAME_OF_THE_DISCORD_ROOM_YOU_WANT_ELITEMOBS" + + "_ANNOUNCEMENTS_TO_BE_BROADCASTED_IN_AS_YOU_HAVE_IN_YOUR_DISCORDSRV_" + + "CONFIGURATION_FILE_CHECK_ELITEMOBS_WIKI_FOR_DETAILS"); + + ConfigurationEngine.fileSaverOnlyDefaults(fileConfiguration, file); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/EconomySettingsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/EconomySettingsConfig.java index 6863efb39..cb7823070 100644 --- a/src/main/java/com/magmaguy/elitemobs/config/EconomySettingsConfig.java +++ b/src/main/java/com/magmaguy/elitemobs/config/EconomySettingsConfig.java @@ -1,317 +1,188 @@ -/* - * 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 . - */ - package com.magmaguy.elitemobs.config; -import com.magmaguy.elitemobs.mobconstructor.CombatSystem; -import org.bukkit.configuration.Configuration; +import com.magmaguy.elitemobs.combatsystem.CombatSystem; +import com.magmaguy.elitemobs.utils.VersionChecker; +import lombok.Getter; +import org.bukkit.Material; +import org.bukkit.configuration.file.FileConfiguration; -import java.util.Arrays; +import java.io.File; /** * Created by MagmaGuy on 17/06/2017. */ public class EconomySettingsConfig { + @Getter + private static boolean enableEconomy; + @Getter + private static double resaleValue; + @Getter + private static String currencyName; + @Getter + private static boolean useVault; + @Getter + private static boolean enableCurrencyShower; + @Getter + private static double currencyShowerMultiplier; + @Getter + private static String chatCurrencyShowerMessage; + @Getter + private static String actionBarCurrencyShowerMessage; + @Getter + private static String lootShowerMaterial1; + @Getter + private static String lootShowerMaterial5; + @Getter + private static String lootShowerMaterial10; + @Getter + private static String lootShowerMaterial20; + @Getter + private static String lootShowerMaterial50; + @Getter + private static String lootShowerMaterial100; + @Getter + private static String lootShowerMaterial500; + @Getter + private static String lootShowerMaterial1000; + @Getter + private static String adventurersGuildNotificationMessage; + @Getter + private static double defaultMaterialWorth; + @Getter + private static FileConfiguration thisConfiguration; + @Getter + private static double playerToPlayerTaxes; + + private EconomySettingsConfig() { + } - public static final String CONFIG_NAME = "EconomySettings.yml"; - public static final String ENABLE_ECONOMY = "Enable economy"; - public static final String RESALE_VALUE = "Item resale value (percentage)"; - public static final String LOWEST_PROCEDURALLY_SIMULATED_LOOT = "Procedurally Generated Loot.Lowest shop item tier"; - public static final String HIGHEST_PROCEDURALLY_SIMULATED_LOOT = "Procedurally Generated Loot.Highest shop item tier"; - public static final String CURRENCY_NAME = "Currency name"; - public static final String SHOP_NAME = "Shop name"; - public static final String CUSTOM_SHOP_NAME = "Custom shop name"; - public static final String SIGNATURE_ITEM_LOCATION_SHOPS = "Reroll button location for EliteMobs Shops"; - public static final String SHOP_VALID_SLOTS = "Valid chest slots for EliteMobs Shop"; - public static final String CUSTOM_SHOP_VALID_SLOTS = "Valid chest slots for EliteMobs Custom Shop"; - - private static final String MATERIAL_WORTH = "Material worth."; - public static final String DIAMOND_AXE = MATERIAL_WORTH + "DIAMOND_AXE"; - public static final String DIAMOND_BARDING = MATERIAL_WORTH + "DIAMOND_BARDING"; - public static final String DIAMOND_BLOCK = MATERIAL_WORTH + "DIAMOND_BLOCK"; - public static final String DIAMOND_BOOTS = MATERIAL_WORTH + "DIAMOND_BOOTS"; - public static final String DIAMOND_CHESTPLATE = MATERIAL_WORTH + "DIAMOND_CHESTPLATE"; - public static final String DIAMOND_HELMET = MATERIAL_WORTH + "DIAMOND_HELMET"; - public static final String DIAMOND_HOE = MATERIAL_WORTH + "DIAMOND_HOE"; - public static final String DIAMOND_LEGGINGS = MATERIAL_WORTH + "DIAMOND_LEGGINGS"; - public static final String DIAMOND_ORE = MATERIAL_WORTH + "DIAMOND_ORE"; - public static final String DIAMOND_PICKAXE = MATERIAL_WORTH + "DIAMOND_PICKAXE"; - public static final String DIAMOND_SPADE = MATERIAL_WORTH + "DIAMOND_SPADE"; - public static final String DIAMOND_SWORD = MATERIAL_WORTH + "DIAMOND_SWORD"; - public static final String IRON_AXE = MATERIAL_WORTH + "IRON_AXE"; - public static final String IRON_BARDING = MATERIAL_WORTH + "IRON_BARDING"; - public static final String IRON_BLOCK = MATERIAL_WORTH + "IRON_BLOCK"; - public static final String IRON_BOOTS = MATERIAL_WORTH + "IRON_BOOTS"; - public static final String IRON_CHESTPLATE = MATERIAL_WORTH + "IRON_CHESTPLATE"; - public static final String IRON_HELMET = MATERIAL_WORTH + "IRON_HELMET"; - public static final String IRON_HOE = MATERIAL_WORTH + "IRON_HOE"; - public static final String IRON_INGOT = MATERIAL_WORTH + "IRON_INGOT"; - public static final String IRON_LEGGINGS = MATERIAL_WORTH + "IRON_LEGGINGS"; - public static final String IRON_NUGGET = MATERIAL_WORTH + "IRON_NUGGET"; - public static final String IRON_ORE = MATERIAL_WORTH + "IRON_ORE"; - public static final String IRON_PICKAXE = MATERIAL_WORTH + "IRON_PICKAXE"; - public static final String IRON_SPADE = MATERIAL_WORTH + "IRON_SPADE"; - public static final String IRON_SWORD = MATERIAL_WORTH + "IRON_SWORD"; - public static final String SHIELD = MATERIAL_WORTH + "SHIELD"; - public static final String BOW = MATERIAL_WORTH + "BOW"; - public static final String CHAINMAIL_BOOTS = MATERIAL_WORTH + "CHAINMAIL_BOOTS"; - public static final String CHAINMAIL_CHESTPLATE = MATERIAL_WORTH + "CHAINMAIL_CHESTPLATE"; - public static final String CHAINMAIL_HELMET = MATERIAL_WORTH + "CHAINMAIL_HELMET"; - public static final String CHAINMAIL_LEGGINGS = MATERIAL_WORTH + "CHAINMAIL_LEGGINGS"; - public static final String STONE_SWORD = MATERIAL_WORTH + "STONE_SWORD"; - public static final String STONE_SPADE = MATERIAL_WORTH + "STONE_SPADE"; - public static final String STONE_PICKAXE = MATERIAL_WORTH + "STONE_PICKAXE"; - public static final String STONE_AXE = MATERIAL_WORTH + "STONE_AXE"; - public static final String GOLD_AXE = MATERIAL_WORTH + "GOLD_AXE"; - public static final String GOLD_BARDING = MATERIAL_WORTH + "GOLD_BARDING"; - public static final String GOLD_BLOCK = MATERIAL_WORTH + "GOLD_BLOCK"; - public static final String GOLD_BOOTS = MATERIAL_WORTH + "GOLD_BOOTS"; - public static final String GOLD_CHESTPLATE = MATERIAL_WORTH + "GOLD_CHESTPLATE"; - public static final String GOLD_HELMET = MATERIAL_WORTH + "GOLD_HELMET"; - public static final String GOLD_HOE = MATERIAL_WORTH + "GOLD_HOE"; - public static final String GOLD_INGOT = MATERIAL_WORTH + "GOLD_INGOT"; - public static final String GOLD_LEGGINGS = MATERIAL_WORTH + "GOLD_LEGGINGS"; - public static final String GOLD_NUGGET = MATERIAL_WORTH + "GOLD_NUGGET"; - public static final String GOLD_ORE = MATERIAL_WORTH + "GOLD_ORE"; - public static final String GOLD_PICKAXE = MATERIAL_WORTH + "GOLD_PICKAXE"; - public static final String GOLD_SPADE = MATERIAL_WORTH + "GOLD_SPADE"; - public static final String GOLD_SWORD = MATERIAL_WORTH + "GOLD_SWORD"; - public static final String GOLDEN_APPLE = MATERIAL_WORTH + "GOLDEN_APPLE"; - public static final String GOLDEN_CARROT = MATERIAL_WORTH + "GOLDEN_CARROT"; - public static final String LEATHER_BOOTS = MATERIAL_WORTH + "LEATHER_BOOTS"; - public static final String LEATHER_CHESTPLATE = MATERIAL_WORTH + "LEATHER_CHESTPLATE"; - public static final String LEATHER_HELMET = MATERIAL_WORTH + "LEATHER_HELMET"; - public static final String LEATHER_LEGGINGS = MATERIAL_WORTH + "LEATHER_LEGGINGS"; - public static final String WOOD_SWORD = MATERIAL_WORTH + "WOOD_SWORD"; - public static final String WOOD_AXE = MATERIAL_WORTH + "WOOD_AXE"; - public static final String WOOD_PICKAXE = MATERIAL_WORTH + "WOOD_PICKAXE"; - public static final String WOOD_HOE = MATERIAL_WORTH + "WOOD_HOE"; - public static final String OTHER = MATERIAL_WORTH + "OTHER"; - - private static final String ENCHANTMENT_WORTH = "Enchantment worth."; - public static final String ARROW_DAMAGE = ENCHANTMENT_WORTH + "ARROW_DAMAGE"; - public static final String ARROW_FIRE = ENCHANTMENT_WORTH + "ARROW_FIRE"; - public static final String ARROW_INFINITE = ENCHANTMENT_WORTH + "ARROW_INFINITE"; - public static final String ARROW_KNOCKBACK = ENCHANTMENT_WORTH + "ARROW_KNOCKBACK"; - public static final String BINDING_CURSE = ENCHANTMENT_WORTH + "BINDING_CURSE"; - public static final String DAMAGE_ALL = ENCHANTMENT_WORTH + "DAMAGE_ALL"; - public static final String DAMAGE_ARTHROPODS = ENCHANTMENT_WORTH + "DAMAGE_ARTHROPODS"; - public static final String DAMAGE_UNDEAD = ENCHANTMENT_WORTH + "DAMAGE_UNDEAD"; - public static final String DEPTH_STRIDER = ENCHANTMENT_WORTH + "DEPTH_STRIDER"; - public static final String DIG_SPEED = ENCHANTMENT_WORTH + "DIG_SPEED"; - public static final String DURABILITY = ENCHANTMENT_WORTH + "DURABILITY"; - public static final String FIRE_ASPECT = ENCHANTMENT_WORTH + "FIRE_ASPECT"; - public static final String FROST_WALKER = ENCHANTMENT_WORTH + "FROST_WALKER"; - public static final String KNOCKBACK = ENCHANTMENT_WORTH + "KNOCKBACK"; - public static final String LOOT_BONUS_BLOCKS = ENCHANTMENT_WORTH + "LOOT_BONUS_BLOCKS"; - public static final String LOOT_BONUS_MOBS = ENCHANTMENT_WORTH + "LOOT_BONUS_MOBS"; - public static final String LUCK_ENCHANTMENT = ENCHANTMENT_WORTH + "LUCK"; - public static final String LURE = ENCHANTMENT_WORTH + "LURE"; - public static final String MENDING = ENCHANTMENT_WORTH + "MENDING"; - public static final String OXYGEN = ENCHANTMENT_WORTH + "OXYGEN"; - public static final String PROTECTION_ENVIRONMENTAL = ENCHANTMENT_WORTH + "PROTECTION_ENVIRONMENTAL"; - public static final String PROTECTION_EXPLOSIONS = ENCHANTMENT_WORTH + "PROTECTION_EXPLOSIONS"; - public static final String PROTECTION_FALL = ENCHANTMENT_WORTH + "PROTECTION_FALL"; - public static final String PROTECTION_PROJECTILE = ENCHANTMENT_WORTH + "PROTECTION_PROJECTILE"; - public static final String PROTECTION_FIRE = ENCHANTMENT_WORTH + "PROTECTION_FIRE"; - public static final String SILK_TOUCH = ENCHANTMENT_WORTH + "SILK_TOUCH"; - public static final String SWEEPING_EDGE = ENCHANTMENT_WORTH + "SWEEPING_EDGE"; - public static final String THORNS = ENCHANTMENT_WORTH + "THORNS"; - public static final String VANISHING_CURSE = ENCHANTMENT_WORTH + "VANISHING_CURSE"; - public static final String WATER_WORKER = ENCHANTMENT_WORTH + "WATER_WORKER"; - - private static final String POTION_EFFECT_WORTH = "Potion effect worth."; - public static final String ABSORPTION = POTION_EFFECT_WORTH + "ABSORPTION"; - public static final String BLINDNESS = POTION_EFFECT_WORTH + "BLINDNESS"; - public static final String CONFUSION = POTION_EFFECT_WORTH + "CONFUSION"; - public static final String DAMAGE_RESISTANCE = POTION_EFFECT_WORTH + "DAMAGE_RESISTANCE"; - public static final String FAST_DIGGING = POTION_EFFECT_WORTH + "FAST_DIGGING"; - public static final String FIRE_RESISTANCE = POTION_EFFECT_WORTH + "FIRE_RESISTANCE"; - public static final String GLOWING = POTION_EFFECT_WORTH + "GLOWING"; - public static final String HARM = POTION_EFFECT_WORTH + "HARM"; - public static final String HEAL = POTION_EFFECT_WORTH + "HEAL"; - public static final String HEALTH_BOOST = POTION_EFFECT_WORTH + "HEALTH_BOOST"; - public static final String HUNGER = POTION_EFFECT_WORTH + "HUNGER"; - public static final String INCREASE_DAMAGE = POTION_EFFECT_WORTH + "INCREASE_DAMAGE"; - public static final String INVISIBILITY = POTION_EFFECT_WORTH + "INVISIBILITY"; - public static final String JUMP = POTION_EFFECT_WORTH + "JUMP"; - public static final String LEVITATION = POTION_EFFECT_WORTH + "LEVITATION"; - public static final String LUCK_POTION = POTION_EFFECT_WORTH + "LUCK"; - public static final String NIGHT_VISION = POTION_EFFECT_WORTH + "NIGHT_VISION"; - public static final String POISON = POTION_EFFECT_WORTH + "POISON"; - public static final String REGENERATION = POTION_EFFECT_WORTH + "REGENERATION"; - public static final String SATURATION = POTION_EFFECT_WORTH + "SATURATION_NAME"; - public static final String SLOW = POTION_EFFECT_WORTH + "SLOW"; - public static final String SLOW_DIGGING = POTION_EFFECT_WORTH + "SLOW_DIGGING"; - public static final String SPEED = POTION_EFFECT_WORTH + "SPEED"; - public static final String UNLUCK = POTION_EFFECT_WORTH + "UNLUCK"; - public static final String WATER_BREATHING = POTION_EFFECT_WORTH + "WATER_BREATHING"; - public static final String WEAKNESS = POTION_EFFECT_WORTH + "WEAKNESS"; - public static final String WITHER = POTION_EFFECT_WORTH + "WITHER"; - - CustomConfigLoader customConfigLoader = new CustomConfigLoader(); - Configuration configuration = customConfigLoader.getCustomConfig(CONFIG_NAME); - - public void initializeConfig() { - - double diamondLevel = CombatSystem.DIAMOND_TIER_LEVEL + 10; - double ironLevel = CombatSystem.IRON_TIER_LEVEL + 10; - double stoneChainLevel = CombatSystem.STONE_CHAIN_TIER_LEVEL + 10; - double goldWoodLeatherLevel = CombatSystem.GOLD_WOOD_LEATHER_TIER_LEVEL + 10; - - configuration.addDefault(ENABLE_ECONOMY, true); - configuration.addDefault(RESALE_VALUE, 5); - configuration.addDefault(LOWEST_PROCEDURALLY_SIMULATED_LOOT, 1); - configuration.addDefault(HIGHEST_PROCEDURALLY_SIMULATED_LOOT, 5); - configuration.addDefault(CURRENCY_NAME, "Elite Coins"); - configuration.addDefault(SHOP_NAME, "EliteMobs Shop"); - configuration.addDefault(CUSTOM_SHOP_NAME, "EliteMobs Custom Shop"); - configuration.addDefault(SIGNATURE_ITEM_LOCATION_SHOPS, 4); - configuration.addDefault(SHOP_VALID_SLOTS, Arrays.asList(9, 10, 11, 12, 13, 14, 15, 16, 17, 18, - 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, - 46, 47, 48, 49, 50, 51, 52, 53)); - configuration.addDefault(CUSTOM_SHOP_VALID_SLOTS, Arrays.asList(9, 10, 11, 12, 13, 14, 15, 16, 17, 18, - 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, - 46, 47, 48, 49, 50, 51, 52, 53)); - - configuration.addDefault(DIAMOND_AXE, diamondLevel); - configuration.addDefault(DIAMOND_BARDING, diamondLevel); - configuration.addDefault(DIAMOND_BLOCK, diamondLevel); - configuration.addDefault(DIAMOND_BOOTS, diamondLevel); - configuration.addDefault(DIAMOND_CHESTPLATE, diamondLevel); - configuration.addDefault(DIAMOND_HELMET, diamondLevel); - configuration.addDefault(DIAMOND_HOE, diamondLevel); - configuration.addDefault(DIAMOND_LEGGINGS, diamondLevel); - configuration.addDefault(DIAMOND_ORE, diamondLevel); - configuration.addDefault(DIAMOND_PICKAXE, diamondLevel); - configuration.addDefault(DIAMOND_SPADE, diamondLevel); - configuration.addDefault(DIAMOND_SWORD, diamondLevel); - configuration.addDefault(IRON_AXE, ironLevel); - configuration.addDefault(IRON_BARDING, ironLevel); - configuration.addDefault(IRON_BLOCK, ironLevel); - configuration.addDefault(IRON_BOOTS, ironLevel); - configuration.addDefault(IRON_CHESTPLATE, ironLevel); - configuration.addDefault(IRON_HELMET, ironLevel); - configuration.addDefault(IRON_HOE, ironLevel); - configuration.addDefault(IRON_INGOT, ironLevel); - configuration.addDefault(IRON_LEGGINGS, ironLevel); - configuration.addDefault(IRON_NUGGET, ironLevel); - configuration.addDefault(IRON_ORE, ironLevel); - configuration.addDefault(IRON_PICKAXE, ironLevel); - configuration.addDefault(IRON_SPADE, ironLevel); - configuration.addDefault(IRON_SWORD, ironLevel); - configuration.addDefault(SHIELD, ironLevel); - configuration.addDefault(BOW, ironLevel); - configuration.addDefault(CHAINMAIL_BOOTS, stoneChainLevel); - configuration.addDefault(CHAINMAIL_CHESTPLATE, stoneChainLevel); - configuration.addDefault(CHAINMAIL_HELMET, stoneChainLevel); - configuration.addDefault(CHAINMAIL_LEGGINGS, stoneChainLevel); - configuration.addDefault(STONE_SWORD, stoneChainLevel); - configuration.addDefault(STONE_AXE, stoneChainLevel); - configuration.addDefault(STONE_PICKAXE, stoneChainLevel); - configuration.addDefault(STONE_SPADE, stoneChainLevel); - configuration.addDefault(GOLD_AXE, goldWoodLeatherLevel); - configuration.addDefault(GOLD_BARDING, goldWoodLeatherLevel); - configuration.addDefault(GOLD_BLOCK, goldWoodLeatherLevel); - configuration.addDefault(GOLD_BOOTS, goldWoodLeatherLevel); - configuration.addDefault(GOLD_CHESTPLATE, goldWoodLeatherLevel); - configuration.addDefault(GOLD_HELMET, goldWoodLeatherLevel); - configuration.addDefault(GOLD_HOE, goldWoodLeatherLevel); - configuration.addDefault(GOLD_INGOT, goldWoodLeatherLevel); - configuration.addDefault(GOLD_LEGGINGS, goldWoodLeatherLevel); - configuration.addDefault(GOLD_NUGGET, goldWoodLeatherLevel); - configuration.addDefault(GOLD_ORE, goldWoodLeatherLevel); - configuration.addDefault(GOLD_PICKAXE, goldWoodLeatherLevel); - configuration.addDefault(GOLD_SPADE, goldWoodLeatherLevel); - configuration.addDefault(GOLD_SWORD, goldWoodLeatherLevel); - configuration.addDefault(GOLDEN_APPLE, goldWoodLeatherLevel); - configuration.addDefault(GOLDEN_CARROT, goldWoodLeatherLevel); - configuration.addDefault(LEATHER_BOOTS, goldWoodLeatherLevel); - configuration.addDefault(LEATHER_CHESTPLATE, goldWoodLeatherLevel); - configuration.addDefault(LEATHER_HELMET, goldWoodLeatherLevel); - configuration.addDefault(LEATHER_LEGGINGS, goldWoodLeatherLevel); - configuration.addDefault(WOOD_SWORD, goldWoodLeatherLevel); - configuration.addDefault(WOOD_AXE, goldWoodLeatherLevel); - configuration.addDefault(WOOD_PICKAXE, goldWoodLeatherLevel); - configuration.addDefault(WOOD_HOE, goldWoodLeatherLevel); - configuration.addDefault(OTHER, 1); - - configuration.addDefault(ARROW_DAMAGE, diamondLevel); - configuration.addDefault(ARROW_FIRE, diamondLevel / 2); - configuration.addDefault(ARROW_INFINITE, diamondLevel / 2); - configuration.addDefault(ARROW_KNOCKBACK, diamondLevel / 2); - configuration.addDefault(BINDING_CURSE, -1); - configuration.addDefault(DAMAGE_ALL, diamondLevel); - configuration.addDefault(DAMAGE_ARTHROPODS, diamondLevel / 2); - configuration.addDefault(DAMAGE_UNDEAD, diamondLevel / 2); - configuration.addDefault(DEPTH_STRIDER, 1); - configuration.addDefault(DIG_SPEED, diamondLevel); - configuration.addDefault(DURABILITY, diamondLevel); - configuration.addDefault(FIRE_ASPECT, diamondLevel / 2); - configuration.addDefault(FROST_WALKER, 1); - configuration.addDefault(KNOCKBACK, diamondLevel / 2); - configuration.addDefault(LOOT_BONUS_BLOCKS, diamondLevel); - configuration.addDefault(LOOT_BONUS_MOBS, diamondLevel / 2); - configuration.addDefault(LUCK_ENCHANTMENT, 1); - configuration.addDefault(LURE, 1); - configuration.addDefault(MENDING, diamondLevel * 2); - configuration.addDefault(OXYGEN, 1); - configuration.addDefault(PROTECTION_ENVIRONMENTAL, diamondLevel); - configuration.addDefault(PROTECTION_EXPLOSIONS, diamondLevel / 2); - configuration.addDefault(PROTECTION_FALL, diamondLevel / 2); - configuration.addDefault(PROTECTION_FIRE, diamondLevel / 2); - configuration.addDefault(PROTECTION_PROJECTILE, diamondLevel); - configuration.addDefault(SILK_TOUCH, diamondLevel); - configuration.addDefault(SWEEPING_EDGE, diamondLevel); - configuration.addDefault(THORNS, diamondLevel); - configuration.addDefault(VANISHING_CURSE, -1); - configuration.addDefault(WATER_WORKER, 1); + public static void initializeConfig() { + + File file = ConfigurationEngine.fileCreator("EconomySettings.yml"); + FileConfiguration fileConfiguration = ConfigurationEngine.fileConfigurationCreator(file); + + double netheriteLevel = CombatSystem.NETHERITE_TIER_LEVEL + 10D; + double tridentLevel = CombatSystem.TRIDENT_TIER_LEVEL + 10D; + double diamondLevel = CombatSystem.DIAMOND_TIER_LEVEL + 10D; + double ironLevel = CombatSystem.IRON_TIER_LEVEL + 10D; + double stoneChainLevel = CombatSystem.STONE_CHAIN_TIER_LEVEL + 10D; + double goldWoodLeatherLevel = CombatSystem.GOLD_WOOD_LEATHER_TIER_LEVEL + 10D; + + enableEconomy = ConfigurationEngine.setBoolean(fileConfiguration, "enableEconomy", true); + resaleValue = ConfigurationEngine.setDouble(fileConfiguration, "itemResaleValue", 5); + currencyName = ConfigurationEngine.setString(fileConfiguration, "currencyName", "Elite Coins"); + useVault = ConfigurationEngine.setBoolean(fileConfiguration, "useVault - not recommended", false); + enableCurrencyShower = ConfigurationEngine.setBoolean(fileConfiguration, "enableCurrencyShower", true); + currencyShowerMultiplier = ConfigurationEngine.setDouble(fileConfiguration, "currencyShowerTierMultiplier", 1D); + chatCurrencyShowerMessage = ConfigurationEngine.setString(fileConfiguration, "chatCurrencyShowerMessage", "&7[EM] You've picked up &a$amount $currency_name!"); + actionBarCurrencyShowerMessage = ConfigurationEngine.setString(fileConfiguration, "actionbarCurrencyShowerMessage", "&7[EM] You've picked up &a$amount $currency_name!"); + lootShowerMaterial1 = ConfigurationEngine.setString(fileConfiguration, "lootShowerMaterial.1", Material.GOLD_NUGGET.name()); + ConfigurationEngine.setInt(fileConfiguration, "lootShowerData.1", 1); + lootShowerMaterial5 = ConfigurationEngine.setString(fileConfiguration, "lootShowerMaterial.5", Material.GOLD_INGOT.name()); + ConfigurationEngine.setInt(fileConfiguration, "lootShowerData.5", 1); + lootShowerMaterial10 = ConfigurationEngine.setString(fileConfiguration, "lootShowerMaterial.10", Material.GOLD_BLOCK.name()); + ConfigurationEngine.setInt(fileConfiguration, "lootShowerData.10", 1); + lootShowerMaterial20 = ConfigurationEngine.setString(fileConfiguration, "lootShowerMaterial.20", Material.EMERALD.name()); + ConfigurationEngine.setInt(fileConfiguration, "lootShowerData.20", 1); + lootShowerMaterial50 = ConfigurationEngine.setString(fileConfiguration, "lootShowerMaterial.50", Material.EMERALD_BLOCK.name()); + ConfigurationEngine.setInt(fileConfiguration, "lootShowerData.50", 1); + lootShowerMaterial100 = ConfigurationEngine.setString(fileConfiguration, "lootShowerMaterial.100", Material.DIAMOND.name()); + ConfigurationEngine.setInt(fileConfiguration, "lootShowerData.100", 1); + lootShowerMaterial500 = ConfigurationEngine.setString(fileConfiguration, "lootShowerMaterial.500", Material.DIAMOND_BLOCK.name()); + ConfigurationEngine.setInt(fileConfiguration, "lootShowerData.500", 1); + lootShowerMaterial1000 = ConfigurationEngine.setString(fileConfiguration, "lootShowerMaterial.1000", Material.NETHER_STAR.name()); + ConfigurationEngine.setInt(fileConfiguration, "lootShowerData.1000", 1); + adventurersGuildNotificationMessage = ConfigurationEngine.setString(fileConfiguration, "adventurersGuildNotificationMessages", "&7[EM] Extra spending money? Try &a/em !"); + + addMaterial(fileConfiguration, Material.DIAMOND_AXE, diamondLevel); + addMaterial(fileConfiguration, Material.DIAMOND_BOOTS, diamondLevel); + addMaterial(fileConfiguration, Material.DIAMOND_CHESTPLATE, diamondLevel); + addMaterial(fileConfiguration, Material.DIAMOND_LEGGINGS, diamondLevel); + addMaterial(fileConfiguration, Material.DIAMOND_HELMET, diamondLevel); + addMaterial(fileConfiguration, Material.DIAMOND_PICKAXE, diamondLevel); + addMaterial(fileConfiguration, Material.DIAMOND_SHOVEL, diamondLevel); + addMaterial(fileConfiguration, Material.DIAMOND_SWORD, diamondLevel); + addMaterial(fileConfiguration, Material.DIAMOND_HOE, diamondLevel); + + addMaterial(fileConfiguration, Material.IRON_AXE, ironLevel); + addMaterial(fileConfiguration, Material.IRON_BOOTS, ironLevel); + addMaterial(fileConfiguration, Material.IRON_LEGGINGS, ironLevel); + addMaterial(fileConfiguration, Material.IRON_CHESTPLATE, ironLevel); + addMaterial(fileConfiguration, Material.IRON_HELMET, ironLevel); + addMaterial(fileConfiguration, Material.IRON_PICKAXE, ironLevel); + addMaterial(fileConfiguration, Material.IRON_SHOVEL, ironLevel); + addMaterial(fileConfiguration, Material.IRON_HOE, ironLevel); + addMaterial(fileConfiguration, Material.IRON_SWORD, ironLevel); + addMaterial(fileConfiguration, Material.SHIELD, ironLevel); + addMaterial(fileConfiguration, Material.BOW, ironLevel); + + addMaterial(fileConfiguration, Material.CHAINMAIL_BOOTS, stoneChainLevel); + addMaterial(fileConfiguration, Material.CHAINMAIL_LEGGINGS, stoneChainLevel); + addMaterial(fileConfiguration, Material.CHAINMAIL_CHESTPLATE, stoneChainLevel); + addMaterial(fileConfiguration, Material.CHAINMAIL_HELMET, stoneChainLevel); + + addMaterial(fileConfiguration, Material.STONE_SWORD, stoneChainLevel); + addMaterial(fileConfiguration, Material.STONE_AXE, stoneChainLevel); + addMaterial(fileConfiguration, Material.STONE_PICKAXE, stoneChainLevel); + addMaterial(fileConfiguration, Material.STONE_SHOVEL, stoneChainLevel); + addMaterial(fileConfiguration, Material.STONE_HOE, stoneChainLevel); + + addMaterial(fileConfiguration, Material.GOLDEN_AXE, goldWoodLeatherLevel); + addMaterial(fileConfiguration, Material.GOLDEN_BOOTS, goldWoodLeatherLevel); + addMaterial(fileConfiguration, Material.GOLDEN_LEGGINGS, goldWoodLeatherLevel); + addMaterial(fileConfiguration, Material.GOLDEN_CHESTPLATE, goldWoodLeatherLevel); + addMaterial(fileConfiguration, Material.GOLDEN_HELMET, goldWoodLeatherLevel); + addMaterial(fileConfiguration, Material.GOLDEN_SWORD, goldWoodLeatherLevel); + addMaterial(fileConfiguration, Material.GOLDEN_SHOVEL, goldWoodLeatherLevel); + addMaterial(fileConfiguration, Material.GOLDEN_PICKAXE, goldWoodLeatherLevel); + addMaterial(fileConfiguration, Material.GOLDEN_HOE, goldWoodLeatherLevel); + addMaterial(fileConfiguration, Material.GOLDEN_APPLE, diamondLevel); + addMaterial(fileConfiguration, Material.ENCHANTED_GOLDEN_APPLE, diamondLevel); + + addMaterial(fileConfiguration, Material.LEATHER_BOOTS, goldWoodLeatherLevel); + addMaterial(fileConfiguration, Material.LEATHER_LEGGINGS, goldWoodLeatherLevel); + addMaterial(fileConfiguration, Material.LEATHER_CHESTPLATE, goldWoodLeatherLevel); + addMaterial(fileConfiguration, Material.LEATHER_HELMET, goldWoodLeatherLevel); + + addMaterial(fileConfiguration, Material.WOODEN_SWORD, goldWoodLeatherLevel); + addMaterial(fileConfiguration, Material.WOODEN_AXE, goldWoodLeatherLevel); + addMaterial(fileConfiguration, Material.WOODEN_HOE, goldWoodLeatherLevel); + addMaterial(fileConfiguration, Material.WOODEN_PICKAXE, goldWoodLeatherLevel); + + addMaterial(fileConfiguration, Material.TRIDENT, tridentLevel); + addMaterial(fileConfiguration, Material.ELYTRA, diamondLevel); + addMaterial(fileConfiguration, Material.TURTLE_HELMET, goldWoodLeatherLevel); + + if (!VersionChecker.serverVersionOlderThan(16, 0)) { + addMaterial(fileConfiguration, Material.NETHERITE_AXE, netheriteLevel); + addMaterial(fileConfiguration, Material.NETHERITE_PICKAXE, netheriteLevel); + addMaterial(fileConfiguration, Material.NETHERITE_SHOVEL, netheriteLevel); + addMaterial(fileConfiguration, Material.NETHERITE_HOE, netheriteLevel); + addMaterial(fileConfiguration, Material.NETHERITE_SWORD, netheriteLevel); + addMaterial(fileConfiguration, Material.NETHERITE_HELMET, netheriteLevel); + addMaterial(fileConfiguration, Material.NETHERITE_CHESTPLATE, netheriteLevel); + addMaterial(fileConfiguration, Material.NETHERITE_LEGGINGS, netheriteLevel); + addMaterial(fileConfiguration, Material.NETHERITE_BOOTS, netheriteLevel); + } + + defaultMaterialWorth = ConfigurationEngine.setDouble(fileConfiguration, "materialWorth.defaultMaterialWorth", 1); + playerToPlayerTaxes = ConfigurationEngine.setDouble(fileConfiguration, "playerToPlayerPaymentTaxes", 0.2); + + ConfigurationEngine.fileSaverOnlyDefaults(fileConfiguration, file); + thisConfiguration = fileConfiguration; - configuration.addDefault(ABSORPTION, (diamondLevel) * 10); - configuration.addDefault(BLINDNESS, (diamondLevel / 2) * 10); - configuration.addDefault(CONFUSION, (diamondLevel / 2) * 10); - configuration.addDefault(DAMAGE_RESISTANCE, (diamondLevel) * 10); - configuration.addDefault(FAST_DIGGING, (diamondLevel) * 10); - configuration.addDefault(FIRE_RESISTANCE, (diamondLevel / 2) * 10); - configuration.addDefault(GLOWING, (1) * 10); - configuration.addDefault(HARM, (diamondLevel) * 10); - configuration.addDefault(HEAL, (diamondLevel) * 10); - configuration.addDefault(HEALTH_BOOST, (diamondLevel) * 10); - configuration.addDefault(HUNGER, (1) * 10); - configuration.addDefault(INCREASE_DAMAGE, (diamondLevel) * 10); - configuration.addDefault(INVISIBILITY, (diamondLevel / 2) * 10); - configuration.addDefault(JUMP, (diamondLevel / 2) * 10); - configuration.addDefault(LEVITATION, (diamondLevel / 2) * 10); - configuration.addDefault(LUCK_POTION, (1) * 10); - configuration.addDefault(NIGHT_VISION, (1) * 10); - configuration.addDefault(POISON, (diamondLevel / 2) * 10); - configuration.addDefault(REGENERATION, (diamondLevel) * 10); - configuration.addDefault(SATURATION, (diamondLevel / 2) * 10); - configuration.addDefault(SLOW, (diamondLevel / 2) * 10); - configuration.addDefault(SLOW_DIGGING, (1) * 10); - configuration.addDefault(SPEED, (diamondLevel / 2) * 10); - configuration.addDefault(UNLUCK, (1) * 10); - configuration.addDefault(WATER_BREATHING, (1) * 10); - configuration.addDefault(WEAKNESS, (diamondLevel) * 10); - configuration.addDefault(WITHER, (diamondLevel / 2) * 10); + } - configuration.options().copyDefaults(true); - UnusedNodeHandler.clearNodes(configuration); - customConfigLoader.saveDefaultCustomConfig(CONFIG_NAME); - customConfigLoader.saveCustomConfig(CONFIG_NAME); + private static void addMaterial(FileConfiguration fileConfiguration, Material material, double value) { + ConfigurationEngine.setDouble(fileConfiguration, "materialWorth." + material.name(), value); + } + public static double getMaterialWorth(Material material) { + try { + return thisConfiguration.getDouble("materialWorth." + material.name()); + } catch (Exception ex) { + return defaultMaterialWorth; + } } } diff --git a/src/main/java/com/magmaguy/elitemobs/config/EventsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/EventsConfig.java index 81ba5fa0b..cfe59f536 100644 --- a/src/main/java/com/magmaguy/elitemobs/config/EventsConfig.java +++ b/src/main/java/com/magmaguy/elitemobs/config/EventsConfig.java @@ -1,120 +1,34 @@ -/* - * 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 . - */ - package com.magmaguy.elitemobs.config; -import org.bukkit.configuration.Configuration; - -public class EventsConfig { - - public static final String CONFIG_NAME = "events.yml"; - public static final String ENABLE_EVENTS = "Enable events"; - public static final String MINIMUM_ONLINE_PLAYERS = "Minimum amount of online players for event to trigger"; - public static final String MAXIMUM_ONLINE_PLAYERS = "Maximum amount of online players after which the event frequency won't increase"; - public static final String MINIMUM_EVENT_FREQUENCY = "Minimum event frequency (minutes)"; - public static final String MAXIMUM_EVENT_FREQUENCY = "Maximum event frequency (minutes)"; - private static final String ENABLED_EVENTS = "Enabled events."; - public static final String TREASURE_GOBLIN_SMALL_ENABLED = ENABLED_EVENTS + "Small treasure goblin"; - public static final String DEAD_MOON_ENABLED = ENABLED_EVENTS + "Dead moon"; - public static final String KRAKEN_ENABLED = ENABLED_EVENTS + "Kraken"; - public static final String BALROG_ENABLED = ENABLED_EVENTS + "Balrog"; - public static final String FAE_ENABLED = ENABLED_EVENTS + "Fae"; - public static final String TREASURE_GOBLIN_NAME = "Name of mob in Treasure Goblin events"; - public static final String SMALL_TREASURE_GOBLIN_EVENT_ANNOUNCEMENT_TEXT = "Small treasure goblin event announcement text"; - public static final String SMALL_TREASURE_GOBLIN_EVENT_PLAYER_END_TEXT = "Small treasure goblin killed by players message"; - public static final String SMALL_TREASURE_GOBLIN_EVENT_OTHER_END_TEXT = "Small treasure goblin nondescript death message"; - public static final String SMALL_TREASURE_GOBLIN_REWARD = "Treasure goblin extra loot drop amount"; - public static final String DEAD_MOON_EVENT_ANNOUNCEMENT_TEXT = "Dead Moon event announcement text"; - public static final String DEAD_MOON_EVENT_PLAYER_END_TEXT = "Zombie King killed by players message"; - public static final String DEAD_MOON_EVENT_OTHER_END_TEXT = "Zombie King nondescript death message"; - private static final String DEAD_MOON_NAMES = "Dead moon names."; - public static final String DEAD_MOON_THE_RETURNED_NAME = DEAD_MOON_NAMES + "Name of The Returned"; - public static final String DEAD_MOON_ZOMBIE_KING_NAME = DEAD_MOON_NAMES + "Name of the Zombie King"; - private static final String EVENT_WEIGHT = "Event weight."; - public static final String SMALL_TREASURE_GOBLIN_EVENT_WEIGHT = EVENT_WEIGHT + "Small treasure goblin"; - public static final String DEAD_MOON_EVENT_WEIGHT = EVENT_WEIGHT + "Blood moon"; - public static final String EVENT_TIMEOUT_TIME = "Time before boss mob escapes the map"; - public static final String EVENT_TIMEOUT_MESSAGE = "Message for when boss mobs gets culled"; - public static final String SPIRIT_WALK_HIT_INTERVAL = "Number of hits before spirit walk gets activated"; - public static final String ZOMBIE_KING_FLAMETHROWER_INTERVAL = "Time interval between zombie king flamethrower attacks"; - public static final String ZOMBIE_KING_UNHOLY_SMITE_INTERVAL = "Time interval between zombie king unholy smite attacks"; - public static final String ZOMBIE_KING_SUMMON_MINIONS_INTERVAL = "Time interval between zombie king minion summons"; - public static final String TREASURE_GOBLIN_GOLD_SHOTGUN_INTERVAL = "Time interval between treasure goblin gold shotgun shots"; - public static final String TREASURE_GOBLIN_RADIAL_EXPLOSION = "Time interval between treasure goblin radial explosions"; - public static final String KRAKEN_CHANCE_ON_FISH = "Kraken on fish chance"; - public static final String KRAKEN_NAME = "Name of mob in Kraken event"; - public static final String BALROG_CHANCE_ON_MINE = "Balrog chance on mine"; - public static final String BALROG_NAME = "Name of mob in Balrog event"; - public static final String BALROG_TRASH_MOB_NAME = "Name of trash mobs in Balrog event"; - public static final String FAE_NAME = "Name of mob in Fae event"; - public static final String FAE_CHANCE_ON_CHOP = "Fae chance on chop"; - public static final String ANNOUNCEMENT_BROADCAST_WORLD_ONLY = "Only broadcast event message in event world"; - public static final String DEADMOON_ANNOUNCEMENT_MESSAGE = "Deadmoon announcement message"; - public static final String DEADMOON_END_MESSAGE = "Deadmoon end message"; +import lombok.Getter; +import org.bukkit.configuration.file.FileConfiguration; - CustomConfigLoader customConfigLoader = new CustomConfigLoader(); - Configuration configuration = customConfigLoader.getCustomConfig(CONFIG_NAME); +import java.io.File; - public void initializeConfig() { +public class EventsConfig { + @Getter + private + static boolean announcementBroadcastWorldOnly; + @Getter + private static int actionEventMinimumCooldown; + @Getter + private static boolean actionEventsEnabled; + @Getter + private static boolean timedEventsEnabled; + + private EventsConfig() { + } - configuration.addDefault(ENABLE_EVENTS, true); - configuration.addDefault(MINIMUM_ONLINE_PLAYERS, 2); - configuration.addDefault(MAXIMUM_ONLINE_PLAYERS, 100); - configuration.addDefault(MINIMUM_EVENT_FREQUENCY, 45); - configuration.addDefault(MAXIMUM_EVENT_FREQUENCY, 10); - configuration.addDefault(TREASURE_GOBLIN_SMALL_ENABLED, true); - configuration.addDefault(DEAD_MOON_ENABLED, true); - configuration.addDefault(TREASURE_GOBLIN_NAME, "&eTreasure Goblin"); - configuration.addDefault(SMALL_TREASURE_GOBLIN_EVENT_ANNOUNCEMENT_TEXT, "&7&m-----------------------------------------------------\n&7[&aEvent&7] &fA &ctreasure goblin &fhas appeared in&c $world &fat&c $location \n &fMake sure to take a hunting party with you!\n&7&m-----------------------------------------------------"); - configuration.addDefault(SMALL_TREASURE_GOBLIN_EVENT_PLAYER_END_TEXT, "A Treasure Goblin has been slain by $player!"); - configuration.addDefault(SMALL_TREASURE_GOBLIN_EVENT_OTHER_END_TEXT, "A Treasure Goblin has been slain!"); - configuration.addDefault(SMALL_TREASURE_GOBLIN_REWARD, 10); - configuration.addDefault(DEAD_MOON_EVENT_ANNOUNCEMENT_TEXT, "&7&m-----------------------------------------------------\n&7[&aEvent&7] &fA &cZombie King &fhas appeared in&c $world &fat&c $location \n &fMake sure to take a hunting party with you!\n&7&m-----------------------------------------------------"); - configuration.addDefault(DEAD_MOON_EVENT_PLAYER_END_TEXT, "The Zombie King has been slain by $player!"); - configuration.addDefault(DEAD_MOON_EVENT_OTHER_END_TEXT, "The Zombie King has been slain!"); - configuration.addDefault(DEAD_MOON_THE_RETURNED_NAME, "&2The Returned"); - configuration.addDefault(DEAD_MOON_ZOMBIE_KING_NAME, "&4Zombie King"); - configuration.addDefault(SMALL_TREASURE_GOBLIN_EVENT_WEIGHT, 40); - configuration.addDefault(DEAD_MOON_EVENT_WEIGHT, 20); - configuration.addDefault(EVENT_TIMEOUT_TIME, 30); - configuration.addDefault(EVENT_TIMEOUT_MESSAGE, "$bossmob has escaped!"); - configuration.addDefault(SPIRIT_WALK_HIT_INTERVAL, 15); - configuration.addDefault(ZOMBIE_KING_FLAMETHROWER_INTERVAL, 20); - configuration.addDefault(ZOMBIE_KING_UNHOLY_SMITE_INTERVAL, 20); - configuration.addDefault(ZOMBIE_KING_SUMMON_MINIONS_INTERVAL, 20); - configuration.addDefault(TREASURE_GOBLIN_GOLD_SHOTGUN_INTERVAL, 20); - configuration.addDefault(TREASURE_GOBLIN_RADIAL_EXPLOSION, 20); - configuration.addDefault(KRAKEN_ENABLED, true); - configuration.addDefault(BALROG_ENABLED, true); - configuration.addDefault(KRAKEN_CHANCE_ON_FISH, 0.005); - configuration.addDefault(KRAKEN_NAME, "&1Kraken"); - configuration.addDefault(BALROG_CHANCE_ON_MINE, 0.005); - configuration.addDefault(BALROG_NAME, "&cBalrog"); - configuration.addDefault(BALROG_TRASH_MOB_NAME, "&cRaug"); - configuration.addDefault(FAE_ENABLED, true); - configuration.addDefault(FAE_NAME, "&aFae"); - configuration.addDefault(FAE_CHANCE_ON_CHOP, 0.001); - configuration.addDefault(ANNOUNCEMENT_BROADCAST_WORLD_ONLY, false); - configuration.addDefault(DEADMOON_ANNOUNCEMENT_MESSAGE, "A dead moon rises, and the undead with it..."); - configuration.addDefault(DEADMOON_END_MESSAGE, "Dawn rises, the Dead Moon wanes for those still alive..."); + public static void initializeConfig() { + File file = ConfigurationEngine.fileCreator("events.yml"); + FileConfiguration fileConfiguration = ConfigurationEngine.fileConfigurationCreator(file); - configuration.options().copyDefaults(true); - UnusedNodeHandler.clearNodes(configuration); - customConfigLoader.saveDefaultCustomConfig(CONFIG_NAME); - customConfigLoader.saveCustomConfig(CONFIG_NAME); + announcementBroadcastWorldOnly = ConfigurationEngine.setBoolean(fileConfiguration, "Only broadcast event message in event worlds", false); + actionEventMinimumCooldown = ConfigurationEngine.setInt(fileConfiguration, "actionEventMinimumCooldownMinutes", 60 * 4); + actionEventsEnabled = ConfigurationEngine.setBoolean(fileConfiguration, "actionEventsEnabled", true); + timedEventsEnabled = ConfigurationEngine.setBoolean(fileConfiguration, "timedEventsEnabled", true); + ConfigurationEngine.fileSaverOnlyDefaults(fileConfiguration, file); } } diff --git a/src/main/java/com/magmaguy/elitemobs/config/ItemSettingsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/ItemSettingsConfig.java new file mode 100644 index 000000000..491c0712f --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/ItemSettingsConfig.java @@ -0,0 +1,192 @@ +package com.magmaguy.elitemobs.config; + +import com.magmaguy.elitemobs.ChatColorConverter; +import lombok.Getter; +import org.bukkit.configuration.file.FileConfiguration; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +public class ItemSettingsConfig { + @Getter + private static String shopItemSource; + @Getter + private static boolean doEliteMobsLoot; + @Getter + private static boolean doMmorpgColors; + @Getter + private static boolean preventCustomItemPlacement; + @Getter + private static List loreStructure; + @Getter + private static String mobItemSource; + @Getter + private static String loreWorth; + @Getter + private static String loreResale; + @Getter + private static double flatDropRate; + @Getter + private static double regionalBossNonUniqueDropRate; + @Getter + private static boolean regionalBossesDropVanillaLoot; + @Getter + private static double tierIncreaseDropRate; + @Getter + private static double proceduralItemWeight; + @Getter + private static double weighedItemWeight; + @Getter + private static double fixedItemWeight; + @Getter + private static double limitedItemWeight; + @Getter + private static double scalableItemWeight; + @Getter + private static double defaultLootMultiplier; + @Getter + private static double defaultExperienceMultiplier; + @Getter + private static String potionEffectOnHitTargetLore; + @Getter + private static int maxLevelForDefaultLootMultiplier; + @Getter + private static int maximumLootTier; + @Getter + private static boolean useEliteEnchantments; + @Getter + private static String eliteEnchantLoreString; + @Getter + private static boolean useHoesAsWeapons; + @Getter + private static boolean enableRareItemParticleEffects; + @Getter + private static String potionEffectOnHitSelfLore; + @Getter + private static String potionEffectContinuousLore; + @Getter + private static String scrapSucceededMessage; + @Getter + private static String eliteEnchantmentColor; + @Getter + private static String vanillaEnchantmentColor; + @Getter + private static String customEnchantmentColor; + @Getter + private static String potionEffectColor; + @Getter + private static String noSoulbindLore; + @Getter + private static boolean preventEliteItemEnchantment; + @Getter + private static boolean preventEliteItemDiamondToNetheriteUpgrade; + @Getter + private static boolean eliteDurability; + @Getter + private static double eliteDurabilityMultiplier; + @Getter + private static String scrapFailedMessage; + @Getter + private static boolean putLootDirectlyIntoPlayerInventory; + @Getter + private static int lootLevelDifferenceLockout; + @Getter + private static boolean preventEliteItemsFromBreaking; + @Getter + private static String lowArmorDurabilityItemDropMessage; + @Getter + private static String lowWeaponDurabilityItemDropMessage; + @Getter + private static int minimumProcedurallyGeneratedDiamondLootLevelPlusSeven; + @Getter + private static String simlootMessageSuccess; + @Getter + private static String simlootMessageFailure; + @Getter + private static String directDropCustomLootMessage; + @Getter + private static String directDropMinecraftLootMessage; + @Getter + private static String directDropCoinMessage; + @Getter + private static String directDropSpecialMessage; + + private ItemSettingsConfig() { + } + + public static void initializeConfig() { + File file = ConfigurationEngine.fileCreator("ItemSettings.yml"); + FileConfiguration fileConfiguration = ConfigurationEngine.fileConfigurationCreator(file); + + doEliteMobsLoot = ConfigurationEngine.setBoolean(fileConfiguration, "doEliteMobsLoot", true); + doMmorpgColors = ConfigurationEngine.setBoolean(fileConfiguration, "doMMORPGColorsForItems", true); + preventCustomItemPlacement = ConfigurationEngine.setBoolean(fileConfiguration, "preventCustomItemPlacement", true); + loreStructure = ConfigurationEngine.setList(fileConfiguration, "itemLoreStructures", Arrays.asList( + ChatColorConverter.convert("&7&m&l---------&7<&lEquip Info&7>&m&l---------"), + ChatColorConverter.convert("&7Item level: &f$itemLevel &7Prestige &6$prestigeLevel"), + ChatColorConverter.convert("$soulbindInfo"), + ChatColorConverter.convert("$itemSource"), + ChatColorConverter.convert("$ifLore&7&m&l-----------&7< &f&lLore&7 >&m&l-----------"), + ChatColorConverter.convert("$customLore"), + ChatColorConverter.convert("$ifEnchantments&7&m&l--------&7<&9&lEnchantments&7>&m&l--------"), + ChatColorConverter.convert("$enchantments"), + ChatColorConverter.convert("$eliteEnchantments"), + ChatColorConverter.convert("$ifCustomEnchantments&7&m&l------&7< &3&lCustom Enchants&7 >&m&l------"), + ChatColorConverter.convert("$customEnchantments"), + ChatColorConverter.convert("$ifPotionEffects&7&m&l----------&7< &5&lEffects&7 >&m&l----------"), + ChatColorConverter.convert("$potionEffect"), + ChatColorConverter.convert("&7&l&m-----------------------------"), + ChatColorConverter.convert("$loreResaleValue") + )); + shopItemSource = ConfigurationEngine.setString(fileConfiguration, "shopSourceItemLores", "&7Purchased from a store"); + mobItemSource = ConfigurationEngine.setString(fileConfiguration, "mobSourceItemLores", "&7Looted from $mob"); + loreWorth = ConfigurationEngine.setString(fileConfiguration, "loreWorths", "&7Worth $worth $currencyName"); + loreResale = ConfigurationEngine.setString(fileConfiguration, "loreResaleValues", "&7Sells for $resale $currencyName"); + flatDropRate = ConfigurationEngine.setDouble(fileConfiguration, "flatDropRateV3", 0.20); + regionalBossNonUniqueDropRate = ConfigurationEngine.setDouble(fileConfiguration, "regionalBossNonUniqueDropRate", 0.05); + regionalBossesDropVanillaLoot = ConfigurationEngine.setBoolean(fileConfiguration, "regionalBossesDropVanillaLoot", false); + tierIncreaseDropRate = ConfigurationEngine.setDouble(fileConfiguration, "tierIncreaseDropRateV2", 0.00); + proceduralItemWeight = ConfigurationEngine.setDouble(fileConfiguration, "proceduralItemDropWeight", 90); + weighedItemWeight = ConfigurationEngine.setDouble(fileConfiguration, "weighedItemDropWeight", 1); + fixedItemWeight = ConfigurationEngine.setDouble(fileConfiguration, "fixedItemDropWeight", 10); + limitedItemWeight = ConfigurationEngine.setDouble(fileConfiguration, "limitedItemDropWeight", 3); + scalableItemWeight = ConfigurationEngine.setDouble(fileConfiguration, "scalableItemDropWeight", 6); + defaultLootMultiplier = ConfigurationEngine.setDouble(fileConfiguration, "defaultLootMultiplier", 0); + maxLevelForDefaultLootMultiplier = ConfigurationEngine.setInt(fileConfiguration, "levelCapForDefaultLootMultiplier", 200); + defaultExperienceMultiplier = ConfigurationEngine.setDouble(fileConfiguration, "defaultExperienceMultiplier", 1); + maximumLootTier = ConfigurationEngine.setInt(fileConfiguration, "maximumLootTiers", 200); + useEliteEnchantments = ConfigurationEngine.setBoolean(fileConfiguration, "useEliteEnchantments", true); + eliteEnchantLoreString = ChatColorConverter.convert(ConfigurationEngine.setString(fileConfiguration, "eliteEnchantmentLoreStrings", "Elite")); + useHoesAsWeapons = ConfigurationEngine.setBoolean(fileConfiguration, "useHoesAsWeapons", false); + enableRareItemParticleEffects = ConfigurationEngine.setBoolean(fileConfiguration, "enableRareItemParticleEffects", true); + potionEffectOnHitTargetLore = ConfigurationEngine.setString(fileConfiguration, "potionEffectOnHitTargetLore", "&4⚔☠"); + potionEffectOnHitSelfLore = ConfigurationEngine.setString(fileConfiguration, "potionEffectOnHitSelfLore", "&9⚔🛡"); + potionEffectContinuousLore = ConfigurationEngine.setString(fileConfiguration, "potionEffectContinuousLore", "&6⟲"); + eliteEnchantmentColor = ConfigurationEngine.setString(fileConfiguration, "eliteEnchantmentLoreColor", "&9◇"); + vanillaEnchantmentColor = ConfigurationEngine.setString(fileConfiguration, "vanillaEnchantmentLoreColor", "&7◇"); + customEnchantmentColor = ConfigurationEngine.setString(fileConfiguration, "customEnchantmentColor", "&3◇"); + potionEffectColor = ConfigurationEngine.setString(fileConfiguration, "potionEffectLoreColor", "&5◇"); + noSoulbindLore = ConfigurationEngine.setString(fileConfiguration, "noSoulbindLore", "&7Not Soulbound!"); + preventEliteItemEnchantment = ConfigurationEngine.setBoolean(fileConfiguration, "preventEliteItemEnchantment", true); + preventEliteItemDiamondToNetheriteUpgrade = ConfigurationEngine.setBoolean(fileConfiguration, "preventEliteItemDiamondToNetheriteUpgrade", true); + eliteDurability = ConfigurationEngine.setBoolean(fileConfiguration, "eliteItemsDurabilityLossOnlyOnDeath", true); + eliteDurabilityMultiplier = ConfigurationEngine.setDouble(fileConfiguration, "eliteItemsDurabilityLossMultiplier", 1d); + scrapSucceededMessage = ConfigurationEngine.setString(fileConfiguration, "scrapSucceededMessage", "&8[EliteMobs] &2Scrap succeeded!"); + scrapFailedMessage = ConfigurationEngine.setString(fileConfiguration, "scrapFailedMessage", "&8[EliteMobs] &cScrap failed!"); + putLootDirectlyIntoPlayerInventory = ConfigurationEngine.setBoolean(fileConfiguration, "putLootDirectlyIntoPlayerInventory", false); + lootLevelDifferenceLockout = ConfigurationEngine.setInt(fileConfiguration, "lootLevelDifferenceLockout", 10); + preventEliteItemsFromBreaking = ConfigurationEngine.setBoolean(fileConfiguration, "preventEliteItemsFromBreaking", true); + lowArmorDurabilityItemDropMessage = ConfigurationEngine.setString(fileConfiguration, "lowDurabilityItemDropMessage", "&8[EliteMobs] &cDropped armor due to low durability! &8Repair it at the NPC with scrap to use it!"); + lowWeaponDurabilityItemDropMessage = ConfigurationEngine.setString(fileConfiguration, "lowWeaponItemDropMessage", "&8[EliteMobs] &cDropped weapon due to low durability! &8Repair it at the NPC with scrap to use it!"); + minimumProcedurallyGeneratedDiamondLootLevelPlusSeven = ConfigurationEngine.setInt(fileConfiguration, "minimumProcedurallyGeneratedDiamondLootLevelPlusSeven", 10); + simlootMessageSuccess = ConfigurationEngine.setString(fileConfiguration, "simlootMessageSuccess", "&8[EliteMobs] &2Rolled for loot and got $itemName &2!"); + simlootMessageFailure = ConfigurationEngine.setString(fileConfiguration, "simlootMessageFailure", "&8[EliteMobs] &cRolled for loot and got nothing!"); + directDropCustomLootMessage = ConfigurationEngine.setString(fileConfiguration, "directDropCustomLootMessage", "&8[EliteMobs] &2Obtained $itemName &2!"); + directDropMinecraftLootMessage = ConfigurationEngine.setString(fileConfiguration, "directDropMinecraftLootMessage", "&8[EliteMobs] &aObtained $itemName &a!"); + directDropCoinMessage = ConfigurationEngine.setString(fileConfiguration, "directDropCoinMessage", "&8[EliteMobs] &aObtained &2$amount $currencyName &a!"); + directDropSpecialMessage = ConfigurationEngine.setString(fileConfiguration, "directDropSpecialMessage", "&8[EliteMobs] &aObtained &2$amount $name &a!"); + + ConfigurationEngine.fileSaverOnlyDefaults(fileConfiguration, file); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/ItemUpgradeSystemConfig.java b/src/main/java/com/magmaguy/elitemobs/config/ItemUpgradeSystemConfig.java new file mode 100644 index 000000000..67b899093 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/ItemUpgradeSystemConfig.java @@ -0,0 +1,40 @@ +package com.magmaguy.elitemobs.config; + +import lombok.Getter; +import org.bukkit.configuration.file.FileConfiguration; + +import java.io.File; +import java.util.Arrays; +import java.util.List; + +public class ItemUpgradeSystemConfig { + + @Getter + private static String scrapItemName; + @Getter + private static List scrapItemLore; + @Getter + private static String upgradeItemName; + @Getter + private static List upgradeItemLore; + private ItemUpgradeSystemConfig() { + } + + public static void initializeConfig() { + File file = ConfigurationEngine.fileCreator("ScrapItemSettings.yml"); + FileConfiguration fileConfiguration = ConfigurationEngine.fileConfigurationCreator(file); + scrapItemName = ConfigurationEngine.setString(fileConfiguration, "scrapItemName", "&2Level $level Scrap"); + scrapItemLore = ConfigurationEngine.setList(fileConfiguration, "scrapItemLore", Arrays.asList( + "&aGather 25 scrap of the same level in", + "&aorder to create an item upgrade orb!", + "&aYou can also use scrap to repair", + "&aitems and craft higher level scrap!", + "&2Do this at the Adventurer's Guild Hub!")); + upgradeItemName = ConfigurationEngine.setString(fileConfiguration, "upgradeItemName", "&2Level $level Upgrade Orb"); + upgradeItemLore = ConfigurationEngine.setList(fileConfiguration, "upgradeItemLore", Arrays.asList( + "&aUse at at the Enhancer NPC to upgrade", + "&aitems up to level $orbLevel!")); + ConfigurationEngine.fileSaverOnlyDefaults(fileConfiguration, file); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/ItemsCustomLootListConfig.java b/src/main/java/com/magmaguy/elitemobs/config/ItemsCustomLootListConfig.java deleted file mode 100644 index e88e15dad..000000000 --- a/src/main/java/com/magmaguy/elitemobs/config/ItemsCustomLootListConfig.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.config; - -import com.magmaguy.elitemobs.MetadataHandler; -import org.bukkit.Bukkit; - -import java.io.File; - -/** - * Created by MagmaGuy on 01/05/2017. - */ -public class ItemsCustomLootListConfig { - - public static final String CONFIG_NAME = "ItemsCustomLootList.yml"; - - public void intializeConfig() { - - Bukkit.getLogger().info(Bukkit.getPluginManager().getPlugin(MetadataHandler.ELITE_MOBS).getDataFolder().getAbsolutePath() + "/data/" + CONFIG_NAME); - - File file = new File(Bukkit.getPluginManager().getPlugin(MetadataHandler.ELITE_MOBS).getDataFolder().getAbsolutePath() + "/data/" + CONFIG_NAME); - - if (!file.exists()) { - - CustomConfigConstructor customConfigConstructor = new CustomConfigConstructor(CONFIG_NAME, CONFIG_NAME); - - } - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/config/ItemsCustomLootSettingsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/ItemsCustomLootSettingsConfig.java deleted file mode 100644 index 194a00bdb..000000000 --- a/src/main/java/com/magmaguy/elitemobs/config/ItemsCustomLootSettingsConfig.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.config; - -import com.magmaguy.elitemobs.ChatColorConverter; -import org.bukkit.configuration.Configuration; - -import java.util.Arrays; - -public class ItemsCustomLootSettingsConfig { - - public static final String CONFIG_NAME = "ItemsCustomLootSettings.yml"; - public static final String MMORPG_COLORS_FOR_CUSTOM_ITEMS = "Use MMORPG colors for custom items"; -// public static final String SHOW_POTION_EFFECTS = "Show potion effects on lore"; - public static final String SHOW_ITEM_VALUE = "Show item value on lore"; - public static final String SHOW_ITEM_TIER = "Show item tier on lore"; - public static final String LORE_STRUCTURE = "Lore Structure"; - public static final String PREVENT_CUSTOM_ITEM_PLACING = "Prevent players from placing pleaceable Elite custom items"; - public static final String DEFAULT_POTION_EFFECT_DURATION_NODE_PREFIX = "Default potion effect duration (seconds, on hit)."; - public static final String ABSORPTION = DEFAULT_POTION_EFFECT_DURATION_NODE_PREFIX + "ABSORPTION"; - public static final String BLINDNESS = DEFAULT_POTION_EFFECT_DURATION_NODE_PREFIX + "BLINDNESS"; - public static final String CONFUSION = DEFAULT_POTION_EFFECT_DURATION_NODE_PREFIX + "CONFUSION"; - public static final String DAMAGE_RESISTANCE = DEFAULT_POTION_EFFECT_DURATION_NODE_PREFIX + "DAMAGE_RESISTANCE"; - public static final String FAST_DIGGING = DEFAULT_POTION_EFFECT_DURATION_NODE_PREFIX + "FAST_DIGGING"; - public static final String FIRE_RESISTANCE = DEFAULT_POTION_EFFECT_DURATION_NODE_PREFIX + "FIRE_RESISTANCE"; - public static final String GLOWING = DEFAULT_POTION_EFFECT_DURATION_NODE_PREFIX + "GLOWING"; - public static final String HEALTH_BOOST = DEFAULT_POTION_EFFECT_DURATION_NODE_PREFIX + "HEALTH_BOOST"; - public static final String HUNGER = DEFAULT_POTION_EFFECT_DURATION_NODE_PREFIX + "HUNGER"; - public static final String INCREASE_DAMAGE = DEFAULT_POTION_EFFECT_DURATION_NODE_PREFIX + "INCREASE_DAMAGE"; - public static final String INVISIBILITY = DEFAULT_POTION_EFFECT_DURATION_NODE_PREFIX + "INVISIBILITY"; - public static final String JUMP = DEFAULT_POTION_EFFECT_DURATION_NODE_PREFIX + "LEVITATION"; - public static final String LUCK = DEFAULT_POTION_EFFECT_DURATION_NODE_PREFIX + "LUCK"; - public static final String NIGHT_VISION = DEFAULT_POTION_EFFECT_DURATION_NODE_PREFIX + "NIGHT_VISION"; - public static final String POISON = DEFAULT_POTION_EFFECT_DURATION_NODE_PREFIX + "POISON"; - public static final String REGENERATION = DEFAULT_POTION_EFFECT_DURATION_NODE_PREFIX + "REGENERATION"; - public static final String SLOW = DEFAULT_POTION_EFFECT_DURATION_NODE_PREFIX + "SLOW"; - public static final String SLOW_DIGGING = DEFAULT_POTION_EFFECT_DURATION_NODE_PREFIX + "SLOW_DIGGING"; - public static final String SPEED = DEFAULT_POTION_EFFECT_DURATION_NODE_PREFIX + "SPEED"; - public static final String UNLUCK = DEFAULT_POTION_EFFECT_DURATION_NODE_PREFIX + "UNLUCK"; - public static final String WATER_BREATHING = DEFAULT_POTION_EFFECT_DURATION_NODE_PREFIX + "WATER_BREATHING"; - public static final String WEAKNESS = DEFAULT_POTION_EFFECT_DURATION_NODE_PREFIX + "WEAKNESS"; - public static final String WITHER = DEFAULT_POTION_EFFECT_DURATION_NODE_PREFIX + "WITHER"; - CustomConfigLoader customConfigLoader = new CustomConfigLoader(); - private Configuration configuration = customConfigLoader.getCustomConfig(CONFIG_NAME); - - public void initializeConfig() { - - configuration.addDefault(MMORPG_COLORS_FOR_CUSTOM_ITEMS, true); -// configuration.addDefault(SHOW_POTION_EFFECTS, true); - configuration.addDefault(SHOW_ITEM_VALUE, true); - configuration.addDefault(SHOW_ITEM_TIER, true); - configuration.addDefault(PREVENT_CUSTOM_ITEM_PLACING, true); - configuration.addDefault(LORE_STRUCTURE, Arrays.asList( - ChatColorConverter.convert("$enchantments"), - ChatColorConverter.convert("$potionEffect"), - ChatColorConverter.convert("&m----------------------"), - ChatColorConverter.convert(" $customLore "), - ChatColorConverter.convert(" $itemValue "), - ChatColorConverter.convert("&m----------------------"), - ChatColorConverter.convert(" Tier $tier ") - )); - configuration.addDefault(ABSORPTION, 2); - configuration.addDefault(BLINDNESS, 5); - configuration.addDefault(CONFUSION, 10); - configuration.addDefault(DAMAGE_RESISTANCE, 30); - configuration.addDefault(FAST_DIGGING, 30); - configuration.addDefault(FIRE_RESISTANCE, 15); - configuration.addDefault(GLOWING, 60); - configuration.addDefault(HEALTH_BOOST, 90); - configuration.addDefault(HUNGER, 30); - configuration.addDefault(INCREASE_DAMAGE, 30); - configuration.addDefault(INVISIBILITY, 3); - configuration.addDefault(JUMP, 10); - configuration.addDefault(LUCK, 5); - configuration.addDefault(NIGHT_VISION, 30); - configuration.addDefault(POISON, 20); - configuration.addDefault(REGENERATION, 20); - configuration.addDefault(SLOW, 15); - configuration.addDefault(SLOW_DIGGING, 10); - configuration.addDefault(SPEED, 30); - configuration.addDefault(UNLUCK, 30); - configuration.addDefault(WATER_BREATHING, 30); - configuration.addDefault(WEAKNESS, 15); - configuration.addDefault(WITHER, 15); - - customConfigLoader.getCustomConfig(CONFIG_NAME).options().copyDefaults(true); - UnusedNodeHandler.clearNodes(configuration); - customConfigLoader.saveDefaultCustomConfig(CONFIG_NAME); - customConfigLoader.saveCustomConfig(CONFIG_NAME); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/config/ItemsDropSettingsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/ItemsDropSettingsConfig.java deleted file mode 100644 index 2c389bf5c..000000000 --- a/src/main/java/com/magmaguy/elitemobs/config/ItemsDropSettingsConfig.java +++ /dev/null @@ -1,211 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.config; - -import com.magmaguy.elitemobs.items.customenchantments.CustomEnchantmentCache; -import org.bukkit.configuration.Configuration; - -public class ItemsDropSettingsConfig { - - public static final String CONFIG_NAME = "ItemsDropSettings.yml"; - - public static final String ENABLE_PLUGIN_LOOT = "Enable plugin loot"; - public static final String DROP_CUSTOM_ITEMS = "Elite Mobs can drop custom loot"; - public static final String LORE_WORTH = "Item worth"; - public static final String LORE_RESALE_WORTH = "Item resale worth"; - public static final String ELITE_ITEM_FLAT_DROP_RATE = "EliteMob base percentual plugin item drop chance"; - public static final String ELITE_ITEM_TIER_DROP_RATE = "EliteMob plugin item percentual drop chance increase per tier"; - public static final String PROCEDURAL_ITEM_WEIGHT = "Procedurally generated item weight"; - public static final String CUSTOM_ITEM_WEIGHT = "Custom item weight"; - public static final String CUSTOM_DYNAMIC_ITEM_WEIGHT = "Custom dynamic item weight"; - public static final String CUSTOM_STATIC_ITEM_WEIGHT = "Custom static item weight"; - public static final String SPAWNER_DEFAULT_LOOT_MULTIPLIER = "Drop multiplied default loot from elite mobs spawned in spawners"; - public static final String DEFAULT_LOOT_MULTIPLIER = "EliteMob default loot multiplier"; - public static final String MAXIMUM_LEVEL_FOR_LOOT_MULTIPLIER = "Maximum level of the Elite Mob default multiplier"; - public static final String EXPERIENCE_LOOT_MULTIPLIER = "EliteMob xp multiplier"; - public static final String MAXIMUM_LOOT_TIER = "Maximum loot tier (REQUIRES INCREASING SHARPNESS AND PROTECTION ENCHANTMENTS TO WORK PROPERLY, READ GITHUB WIKI!)"; - public static final String ENABLE_CUSTOM_ENCHANTMENT_SYSTEM = "Enable custom echantment system (check the github wiki before changing)"; - public static final String ENCHANTMENT_NAME = "Enchantment name."; - public static final String ARROW_DAMAGE_NAME = ENCHANTMENT_NAME +"ARROW_DAMAGE"; - public static final String ARROW_FIRE_NAME = ENCHANTMENT_NAME + "ARROW_FIRE"; - public static final String ARROW_INFINITE_NAME = ENCHANTMENT_NAME + "ARROW_INFINITE"; - public static final String ARROW_KNOCKBACK_NAME = ENCHANTMENT_NAME + "ARROW_KNOCKBACK"; - public static final String BINDING_CURSE_NAME = ENCHANTMENT_NAME + "BINDING_CURSE"; - public static final String CHANNELING_NAME = ENCHANTMENT_NAME + "CHANNELING"; - public static final String DAMAGE_ALL_NAME = ENCHANTMENT_NAME + "DAMAGE_ALL"; - public static final String DAMAGE_ARTHROPODS_NAME = ENCHANTMENT_NAME + "DAMAGE_ARTHROPODS"; - public static final String DAMAGE_UNDEAD_NAME = ENCHANTMENT_NAME + "DAMAGE_UNDEAD"; - public static final String DEPTH_STRIDER_NAME = ENCHANTMENT_NAME + "DEPTH_STRIDER"; - public static final String DIG_SPEED_NAME = ENCHANTMENT_NAME + "DIG_SPEED"; - public static final String DURABILITY_NAME = ENCHANTMENT_NAME + "DURABILITY"; - public static final String FIRE_ASPECT_NAME = ENCHANTMENT_NAME + "FIRE_ASPECT"; - public static final String FROST_WALKER_NAME = ENCHANTMENT_NAME + "FROST_WALKER"; - public static final String IMPALING_NAME = ENCHANTMENT_NAME + "IMPALING"; - public static final String KNOCKBACK_NAME = ENCHANTMENT_NAME + "KNOCKBACK"; - public static final String LOOT_BONUS_BLOCKS_NAME = ENCHANTMENT_NAME + "LOOT_BONUS_BLOCKS"; - public static final String LOOT_BONUS_MOBS_NAME = ENCHANTMENT_NAME + "LOOT_BONUS_MOBS"; - public static final String LOYALTY_NAME = ENCHANTMENT_NAME + "LOYALTY"; - public static final String LUCK_ENCHANTMENT_NAME = ENCHANTMENT_NAME + "LUCK"; - public static final String LURE_NAME = ENCHANTMENT_NAME + "LURE"; - public static final String MENDING_NAME = ENCHANTMENT_NAME + "MENDING"; - public static final String OXYGEN_NAME = ENCHANTMENT_NAME + "OXYGEN"; - public static final String PROTECTION_ENVIRONMENTAL_NAME = ENCHANTMENT_NAME + "PROTECTION_ENVIRONMENTAL"; - public static final String PROTECTION_EXPLOSIONS_NAME = ENCHANTMENT_NAME + "PROTECTION_EXPLOSIONS"; - public static final String PROTECTION_FALL_NAME = ENCHANTMENT_NAME + "PROTECTION_FALL"; - public static final String PROTECTION_FIRE_NAME = ENCHANTMENT_NAME + "PROTECTION_FIRE"; - public static final String PROTECTION_PROJECTILE_NAME = ENCHANTMENT_NAME + "PROTECTION_PROJECTILE"; - public static final String RIPTIDE_NAME = ENCHANTMENT_NAME + "RIPTIDE"; - public static final String SILK_TOUCH_NAME = ENCHANTMENT_NAME + "SILK_TOUCH"; - public static final String SWEEPING_EDGE_NAME = ENCHANTMENT_NAME + "SWEEPING_EDGE"; - public static final String THORNS_NAME = ENCHANTMENT_NAME + "THORNS"; - public static final String VANISHING_CURSE_NAME = ENCHANTMENT_NAME + "VANISHING_CURSE"; - public static final String WATER_WORKER_NAME = ENCHANTMENT_NAME + "WATER_WORKER"; - public static final String POTION_EFFECT_NAME = "Potion effect name."; - public static final String ABSORPTION_NAME = POTION_EFFECT_NAME + "ABSORPTION"; - public static final String BLINDNESS_NAME = POTION_EFFECT_NAME + "BLINDNESS"; - public static final String CONDUIT_POWER_NAME = POTION_EFFECT_NAME + "CONDUIT_POWER"; - public static final String CONFUSION_NAME = POTION_EFFECT_NAME + "CONFUSION"; - public static final String DAMAGE_RESISTANCE_NAME = POTION_EFFECT_NAME + "DAMAGE_RESISTANCE"; - public static final String DOLPHINS_GRACE_NAME = POTION_EFFECT_NAME + "DOLPHINS_GRACE"; - public static final String FAST_DIGGING_NAME = POTION_EFFECT_NAME + "FAST_DIGGING"; - public static final String FIRE_RESISTANCE_NAME = POTION_EFFECT_NAME + "FIRE_RESISTANCE"; - public static final String GLOWING_NAME = POTION_EFFECT_NAME + "GLOWING"; - public static final String HARM_NAME = POTION_EFFECT_NAME + "HARM"; - public static final String HEAL_NAME = POTION_EFFECT_NAME + "HEAL"; - public static final String HEAL_BOOST_NAME = POTION_EFFECT_NAME + "HEAL_BOOST"; - public static final String HUNGER_NAME = POTION_EFFECT_NAME + "HUNGER"; - public static final String INCREASE_DAMAGE_NAME = POTION_EFFECT_NAME + "INCREASE_DAMAGE"; - public static final String INVISIBILITY_NAME = POTION_EFFECT_NAME + "INVISIBILITY"; - public static final String JUMP_NAME = POTION_EFFECT_NAME + "JUMP"; - public static final String LEVITATION_NAME = POTION_EFFECT_NAME + "LEVITATION"; - public static final String LUCK_POTION_NAME = POTION_EFFECT_NAME + "LUCK"; - public static final String NIGHT_VISION_NAME = POTION_EFFECT_NAME + "NIGHT_VISION"; - public static final String POISON_NAME = POTION_EFFECT_NAME + "POISON"; - public static final String REGENERATION_NAME = POTION_EFFECT_NAME + "REGENERATION"; - public static final String SATURATION_NAME = POTION_EFFECT_NAME + "SATURATION"; - public static final String SLOW_NAME = POTION_EFFECT_NAME + "SLOW"; - public static final String SLOW_DIGGING_NAME = POTION_EFFECT_NAME + "SLOW_DIGGING"; - public static final String SLOW_FALLING_NAME = POTION_EFFECT_NAME + "SLOW_FALLING"; - public static final String SPEED_NAME = POTION_EFFECT_NAME + "SPEED"; - public static final String UNLUCK_NAME = POTION_EFFECT_NAME + "UNLUCK"; - public static final String WATER_BREATHING_NAME = POTION_EFFECT_NAME + "WATER_BREATHING"; - public static final String WEAKNESS_NAME = POTION_EFFECT_NAME + "WEAKNESS"; - public static final String WITHER_NAME = POTION_EFFECT_NAME + "WITHER"; - public static final String ENABLE_RARE_DROP_EFFECT = "Enable rare drop visual effect"; - - /* - Custom enchantments - */ - public static final String FLAMETHROWER_NAME = ENCHANTMENT_NAME + CustomEnchantmentCache.flamethrowerEnchantment.getKey(); - public static final String HUNTER_NAME = ENCHANTMENT_NAME + CustomEnchantmentCache.hunterEnchantment.getKey(); - - CustomConfigLoader customConfigLoader = new CustomConfigLoader(); - Configuration configuration = customConfigLoader.getCustomConfig(CONFIG_NAME); - - public void initializeConfig() { - - configuration.addDefault(ENABLE_PLUGIN_LOOT, true); - configuration.addDefault(DROP_CUSTOM_ITEMS, true); - configuration.addDefault(LORE_WORTH, "Worth $worth $currencyName"); - configuration.addDefault(LORE_RESALE_WORTH, "$resale $currencyName resale value"); - configuration.addDefault(ELITE_ITEM_FLAT_DROP_RATE, 025.00); - configuration.addDefault(ELITE_ITEM_TIER_DROP_RATE, 005.00); - configuration.addDefault(PROCEDURAL_ITEM_WEIGHT, 90); - configuration.addDefault(CUSTOM_ITEM_WEIGHT, 10); - configuration.addDefault(CUSTOM_DYNAMIC_ITEM_WEIGHT, 9); - configuration.addDefault(CUSTOM_STATIC_ITEM_WEIGHT, 1); - configuration.addDefault(SPAWNER_DEFAULT_LOOT_MULTIPLIER, true); - configuration.addDefault(DEFAULT_LOOT_MULTIPLIER, 1.0); - configuration.addDefault(MAXIMUM_LEVEL_FOR_LOOT_MULTIPLIER, 200); - configuration.addDefault(EXPERIENCE_LOOT_MULTIPLIER, 1.0); - configuration.addDefault(MAXIMUM_LOOT_TIER, 5); - configuration.addDefault(ENABLE_CUSTOM_ENCHANTMENT_SYSTEM, true); - configuration.addDefault(ARROW_DAMAGE_NAME, "Power"); - configuration.addDefault(ARROW_FIRE_NAME, "Flame"); - configuration.addDefault(ARROW_INFINITE_NAME, "Infinity"); - configuration.addDefault(ARROW_KNOCKBACK_NAME, "Punch"); - configuration.addDefault(BINDING_CURSE_NAME, "Curse of Binding"); - configuration.addDefault(CHANNELING_NAME, "Channeling"); - configuration.addDefault(DAMAGE_ALL_NAME, "Sharpness"); - configuration.addDefault(DAMAGE_ARTHROPODS_NAME, "Bane of Arthropods"); - configuration.addDefault(DAMAGE_UNDEAD_NAME, "Smite"); - configuration.addDefault(DEPTH_STRIDER_NAME, "Depth Strider"); - configuration.addDefault(DIG_SPEED_NAME, "Efficiency"); - configuration.addDefault(DURABILITY_NAME, "Unbreaking"); - configuration.addDefault(FIRE_ASPECT_NAME, "Fire Aspect"); - configuration.addDefault(FROST_WALKER_NAME, "Frost Walker"); - configuration.addDefault(IMPALING_NAME, "Impaling"); - configuration.addDefault(KNOCKBACK_NAME, "Knockback"); - configuration.addDefault(LOOT_BONUS_BLOCKS_NAME, "Fortune"); - configuration.addDefault(LOOT_BONUS_MOBS_NAME, "Looting"); - configuration.addDefault(LOYALTY_NAME, "Loyalty"); - configuration.addDefault(LUCK_ENCHANTMENT_NAME, "Luck of the Sea"); - configuration.addDefault(LURE_NAME, "Lure"); - configuration.addDefault(MENDING_NAME, "Mending"); - configuration.addDefault(OXYGEN_NAME, "Respiration"); - configuration.addDefault(PROTECTION_ENVIRONMENTAL_NAME, "Protection"); - configuration.addDefault(PROTECTION_EXPLOSIONS_NAME, "Blast Protection"); - configuration.addDefault(PROTECTION_FALL_NAME, "Feather Falling"); - configuration.addDefault(PROTECTION_FIRE_NAME, "Fire Protection"); - configuration.addDefault(PROTECTION_PROJECTILE_NAME, "Projectile Protection"); - configuration.addDefault(RIPTIDE_NAME, "Riptide"); - configuration.addDefault(SILK_TOUCH_NAME, "Silk Touch"); - configuration.addDefault(SWEEPING_EDGE_NAME, "Sweeping Edge"); - configuration.addDefault(THORNS_NAME, "Thorns"); - configuration.addDefault(VANISHING_CURSE_NAME, "Curse of Vanishing"); - configuration.addDefault(WATER_WORKER_NAME, "Aqua Affinity"); - configuration.addDefault(ABSORPTION_NAME, "Absorption"); - configuration.addDefault(BLINDNESS_NAME, "Blindness"); - configuration.addDefault(CONDUIT_POWER_NAME, "Conduit Power"); - configuration.addDefault(CONFUSION_NAME, "Nausea"); - configuration.addDefault(DAMAGE_RESISTANCE_NAME, "Resistance"); - configuration.addDefault(DOLPHINS_GRACE_NAME, "Dolphin's grace"); - configuration.addDefault(FAST_DIGGING_NAME, "Haste"); - configuration.addDefault(FIRE_RESISTANCE_NAME, "Fire Resistance"); - configuration.addDefault(GLOWING_NAME, "Glowing"); - configuration.addDefault(HARM_NAME, "Instant Damage"); - configuration.addDefault(HEAL_NAME, "Instant Health"); - configuration.addDefault(HEAL_BOOST_NAME, "Health Boost"); - configuration.addDefault(HUNGER_NAME, "Hunger"); - configuration.addDefault(INCREASE_DAMAGE_NAME, "Strength"); - configuration.addDefault(INVISIBILITY_NAME, "Invisibility"); - configuration.addDefault(JUMP_NAME, "Jump Boost"); - configuration.addDefault(LEVITATION_NAME, "Levitation"); - configuration.addDefault(LUCK_POTION_NAME, "Luck"); - configuration.addDefault(NIGHT_VISION_NAME, "Night Vision"); - configuration.addDefault(POISON_NAME, "Poison"); - configuration.addDefault(REGENERATION_NAME, "Regeneration"); - configuration.addDefault(SATURATION_NAME, "Saturation"); - configuration.addDefault(SLOW_NAME, "Slowness"); - configuration.addDefault(SLOW_DIGGING_NAME, "Mining Fatigue"); - configuration.addDefault(SLOW_FALLING_NAME, "Slow Falling"); - configuration.addDefault(SPEED_NAME, "Speed"); - configuration.addDefault(UNLUCK_NAME, "Bad Luck"); - configuration.addDefault(WATER_BREATHING_NAME, "Water Breathing"); - configuration.addDefault(WEAKNESS_NAME, "Weakness"); - configuration.addDefault(WITHER_NAME, "Wither"); - configuration.addDefault(FLAMETHROWER_NAME, "Flamethrower"); - configuration.addDefault(HUNTER_NAME, "Hunter"); - configuration.addDefault(ENABLE_RARE_DROP_EFFECT, true); - - configuration.options().copyDefaults(true); - UnusedNodeHandler.clearNodes(configuration); - customConfigLoader.saveDefaultCustomConfig(CONFIG_NAME); - customConfigLoader.saveCustomConfig(CONFIG_NAME); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/config/ItemsUniqueConfig.java b/src/main/java/com/magmaguy/elitemobs/config/ItemsUniqueConfig.java deleted file mode 100644 index ae6af6a33..000000000 --- a/src/main/java/com/magmaguy/elitemobs/config/ItemsUniqueConfig.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.config; - -import com.magmaguy.elitemobs.items.uniqueitems.*; -import org.bukkit.configuration.Configuration; - -public class ItemsUniqueConfig{ - - public static final String CONFIG_NAME = "ItemsUnique.yml"; - private CustomConfigLoader customConfigLoader = new CustomConfigLoader(); - private Configuration configuration = customConfigLoader.getCustomConfig(CONFIG_NAME); - - public static final String ENABLE_UNIQUE_ITEMS = "Enable unique items"; - public static final String ENABLE_HUNTING_SET = "Enable Mob Hunting set"; - public static final String HUNTING_SET_CHANCE_INCREASER = "EliteMob percentual spawn chance increase per hunting set item"; - public static final String ENABLE_ZOMBIE_KING_AXE = "Enable Zombie King Axe"; - public static final String SHOW_ITEM_WORTH = "Show item worth"; - public static final String ENABLE_KRAKEN_FISHING_ROD = "Enable Depths Seeker Fishing Rod"; - public static final String ENABLE_GREED = "Enable Dwarven Greed pickaxe"; - public static final String ENABLE_THE_FELLER = "Enable The Feller"; - - public void initializeConfig() { - - configuration.addDefault(ENABLE_UNIQUE_ITEMS, true); - configuration.addDefault(SHOW_ITEM_WORTH, true); - configuration.addDefault(ENABLE_HUNTING_SET, true); - configuration.addDefault(HUNTING_SET_CHANCE_INCREASER, 10); - configuration.addDefault(ENABLE_ZOMBIE_KING_AXE, true); - configuration.addDefault(ENABLE_KRAKEN_FISHING_ROD, true); - configuration.addDefault(ENABLE_GREED, true); - configuration.addDefault(ENABLE_THE_FELLER, true); - - customConfigLoader.getCustomConfig(CONFIG_NAME).options().copyDefaults(true); - customConfigLoader.saveDefaultCustomConfig(CONFIG_NAME); - customConfigLoader.saveCustomConfig(CONFIG_NAME); - -// Non-static item assembly to avoid issues with making the configuration static (messes up reloads and changes) - HuntingHelmet huntingHelmet = new HuntingHelmet(); - huntingHelmet.assembleConfigItem(configuration); - - HuntingChestplate huntingChestplate = new HuntingChestplate(); - huntingChestplate.assembleConfigItem(configuration); - - HuntingLeggings huntingLeggings = new HuntingLeggings(); - huntingLeggings.assembleConfigItem(configuration); - - HuntingBoots huntingBoots = new HuntingBoots(); - huntingBoots.assembleConfigItem(configuration); - - HuntingBow huntingBow = new HuntingBow(); - huntingBow.assembleConfigItem(configuration); - - ZombieKingsAxe zombieKingsAxe = new ZombieKingsAxe(); - zombieKingsAxe.assembleConfigItem(configuration); - - DepthsSeeker depthsSeeker = new DepthsSeeker(); - depthsSeeker.assembleConfigItem(configuration); - - DwarvenGreed dwarvenGreed = new DwarvenGreed(); - dwarvenGreed.assembleConfigItem(configuration); - - TheFeller theFeller = new TheFeller(); - theFeller.assembleConfigItem(configuration); - - customConfigLoader.getCustomConfig(CONFIG_NAME).options().copyDefaults(true); - UnusedNodeHandler.clearNodes(configuration); - customConfigLoader.saveDefaultCustomConfig(CONFIG_NAME); - customConfigLoader.saveCustomConfig(CONFIG_NAME); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/config/MobCombatSettingsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/MobCombatSettingsConfig.java index d80be6013..125d12b38 100644 --- a/src/main/java/com/magmaguy/elitemobs/config/MobCombatSettingsConfig.java +++ b/src/main/java/com/magmaguy/elitemobs/config/MobCombatSettingsConfig.java @@ -1,129 +1,129 @@ -/* - * 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 . - */ - package com.magmaguy.elitemobs.config; -import org.bukkit.configuration.Configuration; - -public class MobCombatSettingsConfig { - - public static final String CONFIG_NAME = "MobCombatSettings.yml"; +import lombok.Getter; +import org.bukkit.configuration.file.FileConfiguration; - public static final String NATURAL_MOB_SPAWNING = "Natural EliteMob spawning"; - public static final String SPAWNERS_SPAWN_ELITE_MOBS = "Spawners can spawn Elite Mobs"; - public static final String AGGRESSIVE_MOB_CONVERSION_PERCENTAGE = "Percentage of aggressive mobs that get converted to EliteMobs when they spawn"; - public static final String AGGRESSIVE_MOB_STACKING = "Aggressive mob stacking"; - public static final String ELITEMOB_STACKING_CAP = "Elite mob stacking cap"; - public static final String PER_TIER_LEVEL_INCREASE = "Levels between elite mob tiers"; - public static final String STACK_AGGRESSIVE_SPAWNER_MOBS = "Stack aggressive spawner mobs"; - public static final String STACK_AGGRESSIVE_NATURAL_MOBS = "Stack aggressive natural mobs"; - public static final String AGGRESSIVE_STACK_RANGE = "Range to stack aggressive mobs"; - public static final String PASSIVE_STACK_RANGE = "Range to stack passive mobs"; - public static final String NATURAL_ELITEMOB_LEVEL_CAP = "Natural elite mob level cap"; - public final static String TARGET_HITS_TO_KILL = "Target hits to kill Elite Mob"; - public final static String BASE_DAMAGE_DEALT_TO_PLAYER = "Base damage dealt to players by Elite Mobs"; - public static final String ELITE_CREEPER_EXPLOSION_MULTIPLIER = "SuperCreeper explosion nerf multiplier"; - public static final String ELITE_ARMOR = "Elite Mobs wear armor"; - public static final String ELITE_HELMETS = "Elite Mobs wear helmets"; - public static final String ENABLE_VISUAL_EFFECTS_FOR_NATURAL_MOBS = "Turn on visual effects for natural or plugin-spawned EliteMobs"; - public static final String DISABLE_VISUAL_EFFECTS_FOR_SPAWNER_MOBS = "Dangerous! Turn off visual effects for non-natural or non-plugin-spawned EliteMobs"; - public static final String ENABLE_WARNING_VISUAL_EFFECTS = "Turn on visual effects that indicate an attack is about to happen"; - public static final String ENABLE_DEATH_MESSAGES = "Enable EliteMobs death messages"; - private static final String DEATH_MESSAGES = "Player death messages cause by."; - public static final String BLAZE_DEATH_MESSAGE = DEATH_MESSAGES + "blazes"; - public static final String CREEPER_DEATH_MESSAGE = DEATH_MESSAGES + "creeper"; - public static final String ENDERMAN_DEATH_MESSAGE = DEATH_MESSAGES + "enderman"; - public static final String ENDERMITE_DEATH_MESSAGE = DEATH_MESSAGES + "endermite"; - public static final String IRONGOLEM_DEATH_MESSAGE = DEATH_MESSAGES + "iron golem"; - public static final String POLARBEAR_DEATH_MESSAGE = DEATH_MESSAGES + "polar bear"; - public static final String SILVERFISH_DEATH_MESSAGE = DEATH_MESSAGES + "silverfish"; - public static final String SKELETON_DEATH_MESSAGE = DEATH_MESSAGES + "skeleton"; - public static final String SPIDER_DEATH_MESSAGE = DEATH_MESSAGES + "spider"; - public static final String WITCH_DEATH_MESSAGE = DEATH_MESSAGES + "witch"; - public static final String ZOMBIE_DEATH_MESSAGE = DEATH_MESSAGES + "zombie"; - public static final String HUSK_DEATH_MESSAGE = DEATH_MESSAGES + "husk"; - public static final String ZOMBIE_PIGMAN_DEATH_MESSAGE = DEATH_MESSAGES + "zombie pigman"; - public static final String STRAY_DEATH_MESSAGE = DEATH_MESSAGES + "stray"; - public static final String WITHER_SKELETON_DEATH_MESSAGE = DEATH_MESSAGES + "wither skeleton"; - public static final String DEFAULT_DEATH_MESSAGE = DEATH_MESSAGES + "default"; - public static final String DISPLAY_HEALTH_ON_HIT = "Display Elite Mob health on hit"; - public static final String DISPLAY_DAMAGE_ON_HIT = "Display damage dealt to Elite Mobs on hit"; - public static final String ONLY_SHOW_HEALTH_FOR_ELITE_MOBS = "Only display health indicator for Elite Mobs"; - public static final String ONLY_SHOW_DAMAGE_FOR_ELITE_MOBS = "Only display damage indicator for Elite Mobs"; - public static final String INCREASE_DIFFICULTY_WITH_SPAWN_DISTANCE = "Increase level of mobs spawned based on distance from world spawn"; - public static final String DISTANCE_TO_INCREMENT = "Distance between increments"; - public static final String LEVEL_TO_INCREMENT = "Amount of levels incremented per distance"; - public static final String ANTI_EXPLOIT_MESSAGE = "Anti exploit message"; - public static final String OBFUSCATE_MOB_POWERS = "Hide mob powers until they are engaged"; +import java.io.File; +import java.util.Collections; +import java.util.List; - CustomConfigLoader customConfigLoader = new CustomConfigLoader(); - public Configuration configuration = customConfigLoader.getCustomConfig(CONFIG_NAME); +public class MobCombatSettingsConfig { + @Getter + private static boolean doNaturalMobSpawning; + @Getter + private static boolean doSpawnersSpawnEliteMobs; + @Getter + private static double aggressiveMobConversionPercentage; + @Getter + private static int superMobsStackRange; + @Getter + private static int naturalEliteMobLevelCap; + @Getter + private static boolean doEliteArmor; + @Getter + private static boolean doEliteHelmets; + @Getter + private static boolean enableVisualEffectsForNaturalMobs; + @Getter + private static boolean disableVisualEffectsForSpawnerMobs; + @Getter + private static boolean enableWarningVisualEffects; + @Getter + private static boolean enableDeathMessages; + @Getter + private static boolean displayHealthOnHit; + @Getter + private static boolean displayDamageOnHit; + @Getter + private static boolean increaseDifficultyWithSpawnDistance; + @Getter + private static double distanceToIncrement; + @Getter + private static double levelToIncrement; + @Getter + private static boolean obfuscateMobPowers; + @Getter + private static double damageToEliteMultiplier; + @Getter + private static double damageToPlayerMultiplier; + @Getter + private static boolean showCustomBossLocation; + @Getter + private static String bossLocationMessage; + @Getter + private static List commandsOnDeath; + @Getter + private static String bossKillParticipationMessage; + @Getter + private static boolean regenerateCustomBossHealthOnCombatEnd; + @Getter + private static String defaultOtherWorldBossLocationMessage; + @Getter + private static String weakTextColor; + @Getter + private static String resistTextColor; + @Getter + private static String weakText; + @Getter + private static String resistText; + @Getter + private static boolean doWeakEffect; + @Getter + private static boolean doResistEffect; + @Getter + private static double normalizedBaselineDamage; + @Getter + private static double normalizedBaselineHealth; + @Getter + private static boolean normalizeRegionalBosses; + @Getter + private static String fullHealMessage; + private MobCombatSettingsConfig() { + } - public void initializeConfig() { + public static void initializeConfig() { - configuration.addDefault(NATURAL_MOB_SPAWNING, true); - configuration.addDefault(SPAWNERS_SPAWN_ELITE_MOBS, false); - configuration.addDefault(AGGRESSIVE_MOB_CONVERSION_PERCENTAGE, 020.00); - configuration.addDefault(AGGRESSIVE_MOB_STACKING, true); - configuration.addDefault(ELITEMOB_STACKING_CAP, 100); - configuration.addDefault(STACK_AGGRESSIVE_SPAWNER_MOBS, true); - configuration.addDefault(STACK_AGGRESSIVE_NATURAL_MOBS, false); - configuration.addDefault(AGGRESSIVE_STACK_RANGE, 1); - configuration.addDefault(PASSIVE_STACK_RANGE, 15); - configuration.addDefault(NATURAL_ELITEMOB_LEVEL_CAP, 2500); - configuration.addDefault(TARGET_HITS_TO_KILL, 10); - configuration.addDefault(BASE_DAMAGE_DEALT_TO_PLAYER, 5); - configuration.addDefault(ELITE_CREEPER_EXPLOSION_MULTIPLIER, 1.0); - configuration.addDefault(ELITE_ARMOR, true); - configuration.addDefault(ELITE_HELMETS, true); - configuration.addDefault(ENABLE_VISUAL_EFFECTS_FOR_NATURAL_MOBS, true); - configuration.addDefault(DISABLE_VISUAL_EFFECTS_FOR_SPAWNER_MOBS, true); - configuration.addDefault(ENABLE_WARNING_VISUAL_EFFECTS, true); - configuration.addDefault(PER_TIER_LEVEL_INCREASE, 10); - configuration.addDefault(ENABLE_DEATH_MESSAGES, true); - configuration.addDefault(BLAZE_DEATH_MESSAGE, "$player was lit ablaze by $entity!"); - configuration.addDefault(CREEPER_DEATH_MESSAGE, "$player was blasted away by $entity!"); - configuration.addDefault(ENDERMAN_DEATH_MESSAGE, "$entity sent $player into the void!"); - configuration.addDefault(ENDERMITE_DEATH_MESSAGE, "$player was glitched to death by $entity!"); - configuration.addDefault(IRONGOLEM_DEATH_MESSAGE, "$player messed with the wrong $entity!"); - configuration.addDefault(POLARBEAR_DEATH_MESSAGE, "$player was clawed to death by $entity!"); - configuration.addDefault(SILVERFISH_DEATH_MESSAGE, "$player mistook $entity for a stone block!"); - configuration.addDefault(SKELETON_DEATH_MESSAGE, "$player became $entity's pin cushion!"); - configuration.addDefault(SPIDER_DEATH_MESSAGE, "$player became entangled in $entity's web!"); - configuration.addDefault(WITCH_DEATH_MESSAGE, "$player became $entity's test subject!"); - configuration.addDefault(ZOMBIE_DEATH_MESSAGE, "$player was devoured by $entity!"); - configuration.addDefault(HUSK_DEATH_MESSAGE, "$player was hollowed out by $entity!"); - configuration.addDefault(ZOMBIE_PIGMAN_DEATH_MESSAGE, "$player was mobbed to death by $entity!"); - configuration.addDefault(STRAY_DEATH_MESSAGE, "$player was led astray by $entity!"); - configuration.addDefault(WITHER_SKELETON_DEATH_MESSAGE, "$entity's arrows withered away $player!"); - configuration.addDefault(DEFAULT_DEATH_MESSAGE, "$player has been slain by $entity"); - configuration.addDefault(DISPLAY_HEALTH_ON_HIT, true); - configuration.addDefault(DISPLAY_DAMAGE_ON_HIT, true); - configuration.addDefault(ONLY_SHOW_HEALTH_FOR_ELITE_MOBS, true); - configuration.addDefault(ONLY_SHOW_DAMAGE_FOR_ELITE_MOBS, true); - configuration.addDefault(INCREASE_DIFFICULTY_WITH_SPAWN_DISTANCE, false); - configuration.addDefault(DISTANCE_TO_INCREMENT, 100); - configuration.addDefault(LEVEL_TO_INCREMENT, 1); - configuration.addDefault(ANTI_EXPLOIT_MESSAGE, "&c[EM AntiExploit] &7Nearby elite won't drop special loot."); - configuration.addDefault(OBFUSCATE_MOB_POWERS, true); + File file = ConfigurationEngine.fileCreator("MobCombatSettings.yml"); + FileConfiguration fileConfiguration = ConfigurationEngine.fileConfigurationCreator(file); - configuration.options().copyDefaults(true); - UnusedNodeHandler.clearNodes(configuration); - customConfigLoader.saveDefaultCustomConfig(CONFIG_NAME); - customConfigLoader.saveCustomConfig(CONFIG_NAME); + doNaturalMobSpawning = ConfigurationEngine.setBoolean(fileConfiguration, "doNaturalEliteMobSpawning", true); + doSpawnersSpawnEliteMobs = ConfigurationEngine.setBoolean(fileConfiguration, "doSpawnersSpawnEliteMobs", false); + aggressiveMobConversionPercentage = ConfigurationEngine.setDouble(fileConfiguration, "eliteMobsSpawnPercentage", 0.05); + superMobsStackRange = Math.max(ConfigurationEngine.setInt(fileConfiguration, "superMobStackRange", 15), 2); + naturalEliteMobLevelCap = ConfigurationEngine.setInt(fileConfiguration, "naturalEliteMobsLevelCap", 250); + doEliteArmor = ConfigurationEngine.setBoolean(fileConfiguration, "doElitesWearArmor", true); + doEliteHelmets = ConfigurationEngine.setBoolean(fileConfiguration, "doElitesWearHelmets", true); + enableVisualEffectsForNaturalMobs = ConfigurationEngine.setBoolean(fileConfiguration, "doNaturalEliteMobVisualEffects", true); + disableVisualEffectsForSpawnerMobs = ConfigurationEngine.setBoolean(fileConfiguration, "doSpawnerEliteMobVisualEffects", false); + enableWarningVisualEffects = ConfigurationEngine.setBoolean(fileConfiguration, "doPowerBuildupVisualEffects", true); + enableDeathMessages = ConfigurationEngine.setBoolean(fileConfiguration, "doCustomEliteMobsDeathMessages", true); + displayHealthOnHit = ConfigurationEngine.setBoolean(fileConfiguration, "doDisplayMobHealthOnHit", true); + displayDamageOnHit = ConfigurationEngine.setBoolean(fileConfiguration, "doDisplayMobDamageOnHit", true); + increaseDifficultyWithSpawnDistance = ConfigurationEngine.setBoolean(fileConfiguration, "doIncreaseEliteMobLevelBasedOnSpawnDistance", false); + distanceToIncrement = ConfigurationEngine.setDouble(fileConfiguration, "distanceBetweenIncrements", 100); + levelToIncrement = ConfigurationEngine.setDouble(fileConfiguration, "levelIncreaseAtIncrements", 1); + obfuscateMobPowers = ConfigurationEngine.setBoolean(fileConfiguration, "hideEliteMobPowersUntilAggro", true); + damageToEliteMultiplier = ConfigurationEngine.setDouble(fileConfiguration, "damageToEliteMobMultiplier", 1); + damageToPlayerMultiplier = ConfigurationEngine.setDouble(fileConfiguration, "damageToPlayerMultiplier", 1); + showCustomBossLocation = ConfigurationEngine.setBoolean(fileConfiguration, "showCustomBossLocation", true); + bossLocationMessage = ConfigurationEngine.setString(fileConfiguration, "bossLocationMessage", "&7[EM] &2[Click to track!]"); + //Accepts placeholders $players, $level and $name + commandsOnDeath = ConfigurationEngine.setList(fileConfiguration, "commandsOnEliteMobDeath", Collections.emptyList()); + //Accepts placeholder $playerDamage + bossKillParticipationMessage = ConfigurationEngine.setString(fileConfiguration, "bossKillParticipationMessage", "&eYour damage: &2$playerDamage"); + regenerateCustomBossHealthOnCombatEnd = ConfigurationEngine.setBoolean(fileConfiguration, "regenerateCustomBossHealthOnCombatEnd", true); + defaultOtherWorldBossLocationMessage = ConfigurationEngine.setString(fileConfiguration, "defaultOtherWorldBossLocationMessage", "$name: In different world!"); + weakTextColor = ConfigurationEngine.setString(fileConfiguration, "weakTextColor", "&9"); + resistTextColor = ConfigurationEngine.setString(fileConfiguration, "resistTextColor", "&c"); + weakText = ConfigurationEngine.setString(fileConfiguration, "weakText", "&9&lWeak!"); + resistText = ConfigurationEngine.setString(fileConfiguration, "resistText", "&c&lResist!"); + doWeakEffect = ConfigurationEngine.setBoolean(fileConfiguration, "doWeakEffect", true); + doResistEffect = ConfigurationEngine.setBoolean(fileConfiguration, "doResistEffect", true); + normalizedBaselineDamage = ConfigurationEngine.setDouble(fileConfiguration, "normalizedRegionalBossBaselineDamage", 5); + normalizedBaselineHealth = ConfigurationEngine.setDouble(fileConfiguration, "normalizedRegionalBossBaselineHealthV2", 7); + normalizeRegionalBosses = ConfigurationEngine.setBoolean(fileConfiguration, "normalizeRegionalBosses", true); + fullHealMessage = ConfigurationEngine.setString(fileConfiguration, "fullHealMessage", "&2FULL HEAL!"); + ConfigurationEngine.fileSaverOnlyDefaults(fileConfiguration, file); } - } diff --git a/src/main/java/com/magmaguy/elitemobs/config/MobPowersConfig.java b/src/main/java/com/magmaguy/elitemobs/config/MobPowersConfig.java deleted file mode 100644 index 045da3623..000000000 --- a/src/main/java/com/magmaguy/elitemobs/config/MobPowersConfig.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.config; - -import org.bukkit.configuration.Configuration; - -/** - * Created by MagmaGuy on 01/05/2017. - */ -public class MobPowersConfig { - - public static final String CONFIG_NAME = "MobPowers.yml"; - CustomConfigLoader customConfigLoader = new CustomConfigLoader(); - private Configuration configuration = customConfigLoader.getCustomConfig(CONFIG_NAME); - - private static final String POWERS = "Powers."; - private static final String DEFENSIVE_POWERS = POWERS + "Defensive Powers."; - private static final String OFFENSIVE_POWERS = POWERS + "Offensive Powers."; - private static final String MISCELLANEOUS_POWERS = POWERS + "Miscellaneous Powers."; - private static final String MAJOR_POWERS = POWERS + "Major Powers."; - - public static final String ATTACK_ARROW = OFFENSIVE_POWERS + "AttackArrow"; - public static final String ATTACK_BLINDING = OFFENSIVE_POWERS + "AttackBlinding"; - public static final String ATTACK_CONFUSING = OFFENSIVE_POWERS + "AttackConfusing"; - public static final String ATTACK_FIRE = OFFENSIVE_POWERS + "AttackFire"; - public static final String ATTACK_FIREBALL = OFFENSIVE_POWERS + "AttackFireball"; - public static final String ATTACK_FREEZE = OFFENSIVE_POWERS + "AttackFreeze"; - public static final String ATTACK_GRAVITY = OFFENSIVE_POWERS + "AttackGravity"; - public static final String ATTACK_POISON = OFFENSIVE_POWERS + "AttackPoison"; - public static final String ATTACK_PUSH = OFFENSIVE_POWERS + "AttackPush"; - public static final String ATTACK_WEAKNESS = OFFENSIVE_POWERS + "AttackWeakness"; - public static final String ATTACK_WEB = OFFENSIVE_POWERS + "AttackWeb"; - public static final String ATTACK_WITHER = OFFENSIVE_POWERS + "AttackWither"; - - public static final String INVISIBILITY = DEFENSIVE_POWERS + "Invisibility"; - public static final String INVULNERABILITY_ARROW = DEFENSIVE_POWERS + "InvulnerabilityArrow"; - public static final String INVULNERABILITY_FALL_DAMAGE = DEFENSIVE_POWERS + "InvulnerabilityFallDamage"; - public static final String INVULNERABILITY_FIRE = DEFENSIVE_POWERS + "InvulnerabilityFire"; - public static final String INVULNERABILITY_KNOCKBACK = DEFENSIVE_POWERS + "InvulnerabilityKnockback"; - - public static final String BONUS_LOOT = MISCELLANEOUS_POWERS + "BonusLoot"; - public static final String MOVEMENT_SPEED = MISCELLANEOUS_POWERS + "MovementSpeed"; - public static final String TAUNT = MISCELLANEOUS_POWERS + "Taunt"; - - public static final String SKELETON_PILLAR = MAJOR_POWERS + "SkeletonPillar"; - public static final String SKELETON_TRACKING_ARROW = MAJOR_POWERS + "SkeletonTrackingArrow"; - public static final String ZOMBIE_BLOAT = MAJOR_POWERS + "ZombieBloat"; - public static final String ZOMBIE_FRIENDS = MAJOR_POWERS + "ZombieFriends"; - public static final String ZOMBIE_NECRONOMICON = MAJOR_POWERS + "ZombieNecronomicon"; - public static final String ZOMBIE_PARENTS = MAJOR_POWERS + "ZombieParents"; - public static final String ZOMBIE_TEAM_ROCKET = MAJOR_POWERS + "ZombieTeamRocket"; - - public static final String FROZEN_MESSAGE = "Freeze power message"; - - public void initializeConfig() { - - configuration.addDefault(ATTACK_ARROW, true); - configuration.addDefault(ATTACK_BLINDING, true); - configuration.addDefault(ATTACK_CONFUSING, true); - configuration.addDefault(ATTACK_FIRE, true); - configuration.addDefault(ATTACK_FIREBALL, true); - configuration.addDefault(ATTACK_FREEZE, true); - configuration.addDefault(ATTACK_GRAVITY, true); - configuration.addDefault(ATTACK_POISON, true); - configuration.addDefault(ATTACK_PUSH, true); - configuration.addDefault(ATTACK_WEAKNESS, true); - configuration.addDefault(ATTACK_WEB, true); - configuration.addDefault(ATTACK_WITHER, true); - - configuration.addDefault(INVISIBILITY, true); - configuration.addDefault(INVULNERABILITY_ARROW, true); - configuration.addDefault(INVULNERABILITY_FALL_DAMAGE, true); - configuration.addDefault(INVULNERABILITY_FIRE, true); - configuration.addDefault(INVULNERABILITY_KNOCKBACK, true); - - configuration.addDefault(BONUS_LOOT, true); - configuration.addDefault(MOVEMENT_SPEED, true); - configuration.addDefault(TAUNT, true); - configuration.addDefault(SKELETON_PILLAR, true); - configuration.addDefault(SKELETON_TRACKING_ARROW, true); - configuration.addDefault(ZOMBIE_BLOAT, true); - configuration.addDefault(ZOMBIE_FRIENDS, true); - configuration.addDefault(ZOMBIE_NECRONOMICON, true); - configuration.addDefault(ZOMBIE_PARENTS, true); - configuration.addDefault(ZOMBIE_TEAM_ROCKET, true); - - configuration.addDefault(FROZEN_MESSAGE, "&9You've been frozen!"); - - customConfigLoader.getCustomConfig(CONFIG_NAME).options().copyDefaults(true); - UnusedNodeHandler.clearNodes(configuration); - customConfigLoader.saveDefaultCustomConfig(CONFIG_NAME); - customConfigLoader.saveCustomConfig(CONFIG_NAME); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/config/PlayerCacheData.java b/src/main/java/com/magmaguy/elitemobs/config/PlayerCacheData.java deleted file mode 100644 index b2d107ad6..000000000 --- a/src/main/java/com/magmaguy/elitemobs/config/PlayerCacheData.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.config; - -import org.bukkit.configuration.Configuration; - -/** - * Created by MagmaGuy on 02/07/2017. - */ -public class PlayerCacheData { - - public static final String CONFIG_NAME = "playerCache.yml"; - public CustomConfigLoader customConfigLoader = new CustomConfigLoader(); - public Configuration configuration = customConfigLoader.getCustomConfig(CONFIG_NAME, true); - - public void initializeConfig() { - - //no real defaults, just a data file - customConfigLoader.getCustomConfig(CONFIG_NAME, true).options().copyDefaults(true); - customConfigLoader.saveDefaultCustomConfig(CONFIG_NAME, true); - customConfigLoader.saveCustomConfig(CONFIG_NAME, true); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/config/PlayerGuildRank.java b/src/main/java/com/magmaguy/elitemobs/config/PlayerGuildRank.java deleted file mode 100644 index e5c9ebe9c..000000000 --- a/src/main/java/com/magmaguy/elitemobs/config/PlayerGuildRank.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.magmaguy.elitemobs.config; - -import org.bukkit.configuration.Configuration; - -public class PlayerGuildRank { - - public static final String CONFIG_NAME = "playerGuildRank.yml"; - public CustomConfigLoader customConfigLoader = new CustomConfigLoader(); - public Configuration configuration = customConfigLoader.getCustomConfig(CONFIG_NAME, true); - - public void intializeConfig() { - - //no real defaults, just a data file - customConfigLoader.getCustomConfig(CONFIG_NAME, true).options().copyDefaults(true); - customConfigLoader.saveDefaultCustomConfig(CONFIG_NAME, true); - customConfigLoader.saveCustomConfig(CONFIG_NAME, true); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/config/PlayerMaxGuildRank.java b/src/main/java/com/magmaguy/elitemobs/config/PlayerMaxGuildRank.java deleted file mode 100644 index a8aa2cbfe..000000000 --- a/src/main/java/com/magmaguy/elitemobs/config/PlayerMaxGuildRank.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.magmaguy.elitemobs.config; - -import org.bukkit.configuration.Configuration; - -public class PlayerMaxGuildRank { - - public static final String CONFIG_NAME = "playerMaxGuildRank.yml"; - public CustomConfigLoader customConfigLoader = new CustomConfigLoader(); - public Configuration configuration = customConfigLoader.getCustomConfig(CONFIG_NAME, true); - - public void intializeConfig() { - - //no real defaults, just a data file - customConfigLoader.getCustomConfig(CONFIG_NAME, true).options().copyDefaults(true); - customConfigLoader.saveDefaultCustomConfig(CONFIG_NAME, true); - customConfigLoader.saveCustomConfig(CONFIG_NAME, true); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/config/PlayerMoneyData.java b/src/main/java/com/magmaguy/elitemobs/config/PlayerMoneyData.java deleted file mode 100644 index 3d29906d4..000000000 --- a/src/main/java/com/magmaguy/elitemobs/config/PlayerMoneyData.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.config; - -import org.bukkit.configuration.Configuration; - -/** - * Created by MagmaGuy on 17/06/2017. - */ -public class PlayerMoneyData { - - public static final String CONFIG_NAME = "playerMoneyData.yml"; - public CustomConfigLoader customConfigLoader = new CustomConfigLoader(); - public Configuration configuration = customConfigLoader.getCustomConfig(CONFIG_NAME, true); - - public void intializeConfig() { - - //no real defaults, just a data file - customConfigLoader.getCustomConfig(CONFIG_NAME, true).options().copyDefaults(true); - customConfigLoader.saveDefaultCustomConfig(CONFIG_NAME, true); - customConfigLoader.saveCustomConfig(CONFIG_NAME, true); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/config/ItemsProceduralSettingsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/ProceduralItemGenerationSettingsConfig.java similarity index 65% rename from src/main/java/com/magmaguy/elitemobs/config/ItemsProceduralSettingsConfig.java rename to src/main/java/com/magmaguy/elitemobs/config/ProceduralItemGenerationSettingsConfig.java index e255dda69..5088a3447 100644 --- a/src/main/java/com/magmaguy/elitemobs/config/ItemsProceduralSettingsConfig.java +++ b/src/main/java/com/magmaguy/elitemobs/config/ProceduralItemGenerationSettingsConfig.java @@ -1,352 +1,147 @@ -/* - * 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 . - */ - package com.magmaguy.elitemobs.config; -import com.magmaguy.elitemobs.ChatColorConverter; -import org.bukkit.configuration.Configuration; +import com.magmaguy.elitemobs.items.itemconstructor.MaterialGenerator; +import lombok.Getter; +import org.bukkit.Material; +import org.bukkit.configuration.file.FileConfiguration; +import java.io.File; +import java.util.ArrayList; import java.util.Arrays; +import java.util.List; + +public class ProceduralItemGenerationSettingsConfig { + @Getter + private static FileConfiguration fileConfiguration; + @Getter + private + static boolean doProceduralItemDrops; + @Getter + private static double customEnchantmentChance; + @Getter + private static List validMaterials = new ArrayList<>(); + @Getter + private static String swordName; + @Getter + private static String bowName; + @Getter + private static String pickaxeName; + @Getter + private static String spadeName; + @Getter + private static String hoeName; + @Getter + private static String axeName; + @Getter + private static String helmetName; + @Getter + private static String chestplateName; + @Getter + private static String leggingsName; + @Getter + private static String bootsName; + @Getter + private static String shearsName; + @Getter + private static String fishingRodName; + @Getter + private static String shieldName; + @Getter + private static String tridentName; + @Getter + private static String crossbowName; + @Getter + private static List nameFormat; + @Getter + private static List nouns; + @Getter + private static List adjectives; + @Getter + private static List verbs; + @Getter + private static List verbers; + private ProceduralItemGenerationSettingsConfig() { + } -/** - * Created by MagmaGuy on 04/06/2017. - */ -public class ItemsProceduralSettingsConfig { - - public static final String CONFIG_NAME = "ItemsProceduralSettings.yml"; - public static final String LORE_MOB_LEVEL_SOURCE = "Item source (mob)"; - public static final String LORE_SHOP_SOURCE = "Item source (shop)"; - public static final String LORE_STRUCTURE = "Lore structure"; - public static final String DROP_ITEMS_ON_DEATH = "Drop procedurally generated items on Elite Mob death"; - public static final String MONITOR_ITEMS_ON_CONSOLE = "Monitor procedurally generated items on console"; - public static final String PROCEDURAL_ITEM_VALID_MATERIALS = "Valid material list for random items"; - public static String ARROW_DAMAGE_BOOL, ARROW_DAMAGE_MAX_LEVEL, - ARROW_FIRE_BOOL, ARROW_FIRE_MAX_LEVEL, - ARROW_INFINITE_BOOL, - ARROW_KNOCKBACK_BOOL, ARROW_KNOCKBACK_MAX_LEVEL, - BINDING_CURSE_BOOL, - DAMAGE_ALL_BOOL, DAMAGE_ALL_MAX_LEVEL, - DAMAGE_ARTHROPODS_BOOL, DAMAGE_ARTHROPODS_MAX_LEVEL, - DAMAGE_UNDEAD_BOOL, DAMAGE_UNDEAD_MAX_LEVEL, - DEPTH_STRIDER_BOOL, DEPTH_STRIDER_MAX_LEVEL, - DIG_SPEED_BOOL, DIG_SPEED_MAX_LEVEL, - DURABILITY_BOOL, DURABILITY_MAX_LEVEL, - FIRE_ASPECT_BOOL, FIRE_ASPECT_MAX_LEVEL, - FROST_WALKER_BOOL, FROST_WALKER_MAX_LEVEL, - KNOCKBACK_BOOL, KNOCKBACK_MAX_LEVEL, - LOOT_BONUS_BLOCKS_BOOL, LOOT_BONUS_BLOCKS_MAX_LEVEL, - LOOT_BONUS_MOBS_BOOL, LOOT_BONUS_MOBS_MAX_LEVEL, - LUCK_BOOL, LUCK_MAX_LEVEL, - LURE_BOOL, LURE_MAX_LEVEL, - MENDING_BOOL, - OXYGEN_BOOL, OXYGEN_MAX_LEVEL, - PROTECTION_ENVIRONMENTAL_BOOL, PROTECTION_ENVIRONMENTAL_MAX_LEVEL, - PROTECTION_EXPLOSIONS_BOOL, PROTECTION_EXPLOSIONS_MAX_LEVEL, - PROTECTION_FALL_BOOL, PROTECTION_FALL_MAX_LEVEL, - PROTECTION_FIRE_BOOL, PROTECTION_FIRE_MAX_LEVEL, - PROTECTION_PROJECTILE_BOOL, PROTECTION_PROJECTILE_MAX_LEVEL, - SILK_TOUCH_BOOL, - SWEEPING_EDGE_BOOL, SWEEPING_EDGE_MAX_LEVEL, - THORNS_BOOL, THORNS_MAX_LEVEL, - VANISHING_CURSE_BOOL, - WATER_WORKER_BOOL, WATER_WORKER_MAX_LEVEL; - public static String HUNTER_BOOL, HUNTER_MAX_LEVEL; - public static final String ITEM_NAME_FORMAT = "Procedurally generated item name format"; - private static final String MATERIAL_NAME = "Material name."; - public static final String SWORD_MATERIAL_NAME = MATERIAL_NAME + "Sword"; - public static final String BOW_MATERIAL_NAME = MATERIAL_NAME + "Bow"; - public static final String PICKAXE_MATERIAL_NAME = MATERIAL_NAME + "Pickaxe"; - public static final String SPADE_MATERIAL_NAME = MATERIAL_NAME + "Spade"; - public static final String HOE_MATERIAL_NAME = MATERIAL_NAME + "Hoe"; - public static final String AXE_MATERIAL_NAME = MATERIAL_NAME + "Axe"; - public static final String HELMET_MATERIAL_NAME = MATERIAL_NAME + "Helmet"; - public static final String CHESTPLATE_MATERIAL_NAME = MATERIAL_NAME + "Chestplate"; - public static final String LEGGINGS_MATERIAL_NAME = MATERIAL_NAME + "Leggings"; - public static final String BOOTS_MATERIAL_NAME = MATERIAL_NAME + "Boots"; - public static final String SHEARS_MATERIAL_NAME = MATERIAL_NAME + "Shears"; - public static final String FISHING_ROD_MATERIAL_NAME = MATERIAL_NAME + "Fishing Rod"; - public static final String SHIELD_MATERIAL_NAME = MATERIAL_NAME + "Shield"; - public static final String CUSTOM_ENCHANTMENT_CHANCE = "Chance of getting a custom enchantment"; - - CustomConfigLoader customConfigLoader = new CustomConfigLoader(); - public Configuration configuration = customConfigLoader.getCustomConfig(CONFIG_NAME); - - public void intializeConfig() { - - configuration.addDefault(DROP_ITEMS_ON_DEATH, true); - configuration.addDefault(MONITOR_ITEMS_ON_CONSOLE, false); - configuration.addDefault(LORE_MOB_LEVEL_SOURCE, "Looted from a level $level Elite $mob"); - configuration.addDefault(LORE_SHOP_SOURCE, "Purchased from a store"); - configuration.addDefault(LORE_STRUCTURE, Arrays.asList( - ChatColorConverter.convert("$enchantments"), - ChatColorConverter.convert("$potionEffects"), - ChatColorConverter.convert("&m----------------------"), - ChatColorConverter.convert("$itemSource"), - ChatColorConverter.convert( "$itemValue"), - ChatColorConverter.convert("Elite Mobs drop"), - ChatColorConverter.convert("&m----------------------"), - ChatColorConverter.convert("Tier $tier") - )); - configuration.addDefault(PROCEDURAL_ITEM_VALID_MATERIALS, Arrays.asList( - "DIAMOND_SWORD", - "GOLD_SWORD", - "IRON_SWORD", - "STONE_SWORD", - "WOOD_SWORD", - "BOW", - "DIAMOND_PICKAXE", - "GOLD_PICKAXE", - "IRON_PICKAXE", - "STONE_PICKAXE", - "WOOD_PICKAXE", - "DIAMOND_SPADE", - "GOLD_SPADE", - "IRON_SPADE", - "STONE_SPADE", - "WOOD_SPADE", - "DIAMOND_HOE", - "GOLD_HOE", - "IRON_HOE", - "STONE_HOE", - "WOOD_HOE", - "DIAMOND_AXE", - "GOLD_AXE", - "IRON_AXE", - "STONE_AXE", - "WOOD_AXE", - "SHEARS", - "SHIELD", - "FISHING_ROD", - "CHAINMAIL_HELMET", - "DIAMOND_HELMET", - "GOLD_HELMET", - "IRON_HELMET", - "LEATHER_HELMET", - "CHAINMAIL_CHESTPLATE", - "DIAMOND_CHESTPLATE", - "GOLD_CHESTPLATE", - "IRON_CHESTPLATE", - "LEATHER_CHESTPLATE", - "CHAINMAIL_LEGGINGS", - "DIAMOND_LEGGINGS", - "GOLD_LEGGINGS", - "IRON_LEGGINGS", - "LEATHER_LEGGINGS", - "CHAINMAIL_BOOTS", - "DIAMOND_BOOTS", - "GOLD_BOOTS", - "IRON_BOOTS", - "LEATHER_BOOTS" - )); - - ARROW_DAMAGE_BOOL = boolValidEnchantmentConstructor("ARROW_DAMAGE"); - ARROW_DAMAGE_MAX_LEVEL = maxLevelValidEnchantmentConstructor("ARROW_DAMAGE"); - - ARROW_FIRE_BOOL = boolValidEnchantmentConstructor("ARROW_FIRE"); - ARROW_FIRE_MAX_LEVEL = maxLevelValidEnchantmentConstructor("ARROW_FIRE"); - - ARROW_INFINITE_BOOL = boolValidEnchantmentConstructor("ARROW_INFINITE"); - - ARROW_KNOCKBACK_BOOL = boolValidEnchantmentConstructor("ARROW_KNOCKBACK"); - ARROW_KNOCKBACK_MAX_LEVEL = maxLevelValidEnchantmentConstructor("ARROW_KNOCKBACK"); - - BINDING_CURSE_BOOL = boolValidEnchantmentConstructor("BINDING_CURSE"); - - DAMAGE_ALL_BOOL = boolValidEnchantmentConstructor("DAMAGE_ALL"); - DAMAGE_ALL_MAX_LEVEL = maxLevelValidEnchantmentConstructor("DAMAGE_ALL"); - - DAMAGE_ARTHROPODS_BOOL = boolValidEnchantmentConstructor("DAMAGE_ARTHROPODS"); - DAMAGE_ARTHROPODS_MAX_LEVEL = maxLevelValidEnchantmentConstructor("DAMAGE_ARTHROPODS"); - - DAMAGE_UNDEAD_BOOL = boolValidEnchantmentConstructor("DAMAGE_UNDEAD"); - DAMAGE_UNDEAD_MAX_LEVEL = maxLevelValidEnchantmentConstructor("DAMAGE_UNDEAD"); - - DEPTH_STRIDER_BOOL = boolValidEnchantmentConstructor("DEPTH_STRIDER"); - DEPTH_STRIDER_MAX_LEVEL = maxLevelValidEnchantmentConstructor("DEPTH_STRIDER"); - - DIG_SPEED_BOOL = boolValidEnchantmentConstructor("DIG_SPEED"); - DIG_SPEED_MAX_LEVEL = maxLevelValidEnchantmentConstructor("DIG_SPEED"); - - DURABILITY_BOOL = boolValidEnchantmentConstructor("DURABILITY"); - DURABILITY_MAX_LEVEL = maxLevelValidEnchantmentConstructor("DURABILITY"); - - FIRE_ASPECT_BOOL = boolValidEnchantmentConstructor("FIRE_ASPECT"); - FIRE_ASPECT_MAX_LEVEL = maxLevelValidEnchantmentConstructor("FIRE_ASPECT"); - - FROST_WALKER_BOOL = boolValidEnchantmentConstructor("FROST_WALKER"); - FROST_WALKER_MAX_LEVEL = maxLevelValidEnchantmentConstructor("FROST_WALKER"); - - KNOCKBACK_BOOL = boolValidEnchantmentConstructor("KNOCKBACK"); - KNOCKBACK_MAX_LEVEL = maxLevelValidEnchantmentConstructor("KNOCKBACK"); - - LOOT_BONUS_BLOCKS_BOOL = boolValidEnchantmentConstructor("LOOT_BONUS_BLOCKS"); - LOOT_BONUS_BLOCKS_MAX_LEVEL = maxLevelValidEnchantmentConstructor("LOOT_BONUS_BLOCKS"); - - LOOT_BONUS_MOBS_BOOL = boolValidEnchantmentConstructor("LOOT_BONUS_MOBS"); - LOOT_BONUS_MOBS_MAX_LEVEL = maxLevelValidEnchantmentConstructor("LOOT_BONUS_MOBS"); - - LUCK_BOOL = boolValidEnchantmentConstructor("LUCK"); - LUCK_MAX_LEVEL = maxLevelValidEnchantmentConstructor("LUCK"); - - LURE_BOOL = boolValidEnchantmentConstructor("LURE"); - LURE_MAX_LEVEL = maxLevelValidEnchantmentConstructor("LURE"); - - MENDING_BOOL = boolValidEnchantmentConstructor("MENDING"); - - OXYGEN_BOOL = boolValidEnchantmentConstructor("OXYGEN"); - OXYGEN_MAX_LEVEL = maxLevelValidEnchantmentConstructor("OXYGEN"); - - PROTECTION_ENVIRONMENTAL_BOOL = boolValidEnchantmentConstructor("PROTECTION_ENVIRONMENTAL"); - PROTECTION_ENVIRONMENTAL_MAX_LEVEL = maxLevelValidEnchantmentConstructor("PROTECTION_ENVIRONMENTAL"); - - PROTECTION_EXPLOSIONS_BOOL = boolValidEnchantmentConstructor("PROTECTION_EXPLOSIONS"); - PROTECTION_EXPLOSIONS_MAX_LEVEL = maxLevelValidEnchantmentConstructor("PROTECTION_EXPLOSIONS"); - - PROTECTION_FALL_BOOL = boolValidEnchantmentConstructor("PROTECTION_FALL"); - PROTECTION_FALL_MAX_LEVEL = maxLevelValidEnchantmentConstructor("PROTECTION_FALL"); - - PROTECTION_FIRE_BOOL = boolValidEnchantmentConstructor("PROTECTION_FIRE"); - PROTECTION_FIRE_MAX_LEVEL = maxLevelValidEnchantmentConstructor("PROTECTION_FIRE"); - - PROTECTION_PROJECTILE_BOOL = boolValidEnchantmentConstructor("PROTECTION_PROJECTILE"); - PROTECTION_PROJECTILE_MAX_LEVEL = maxLevelValidEnchantmentConstructor("PROTECTION_PROJECTILE"); - - SILK_TOUCH_BOOL = boolValidEnchantmentConstructor("SILK_TOUCH"); - - SWEEPING_EDGE_BOOL = boolValidEnchantmentConstructor("SWEEPING_EDGE"); - SWEEPING_EDGE_MAX_LEVEL = maxLevelValidEnchantmentConstructor("SWEEPING_EDGE"); - - THORNS_BOOL = boolValidEnchantmentConstructor("THORNS"); - THORNS_MAX_LEVEL = maxLevelValidEnchantmentConstructor("THORNS"); - - VANISHING_CURSE_BOOL = boolValidEnchantmentConstructor("VANISHING"); - - WATER_WORKER_BOOL = boolValidEnchantmentConstructor("WATER_WORKER"); - WATER_WORKER_MAX_LEVEL = maxLevelValidEnchantmentConstructor("WATER_WORKER"); - - /* - Custom enchantments - */ - HUNTER_BOOL = boolValidEnchantmentConstructor("HUNTER"); - HUNTER_MAX_LEVEL = maxLevelValidEnchantmentConstructor("HUNTER"); - - - configuration.addDefault(ARROW_DAMAGE_BOOL, true); - configuration.addDefault(ARROW_DAMAGE_MAX_LEVEL, 5); - - configuration.addDefault(ARROW_FIRE_BOOL, true); - configuration.addDefault(ARROW_FIRE_MAX_LEVEL, 1); - - configuration.addDefault(ARROW_INFINITE_BOOL, true); - - configuration.addDefault(ARROW_KNOCKBACK_BOOL, true); - configuration.addDefault(ARROW_KNOCKBACK_MAX_LEVEL, 2); - - configuration.addDefault(BINDING_CURSE_BOOL, true); - - configuration.addDefault(DAMAGE_ALL_BOOL, true); - configuration.addDefault(DAMAGE_ALL_MAX_LEVEL, 5); - - configuration.addDefault(DAMAGE_ARTHROPODS_BOOL, true); - configuration.addDefault(DAMAGE_ARTHROPODS_MAX_LEVEL, 5); - - configuration.addDefault(DAMAGE_UNDEAD_BOOL, true); - configuration.addDefault(DAMAGE_UNDEAD_MAX_LEVEL, 5); - - configuration.addDefault(DEPTH_STRIDER_BOOL, true); - configuration.addDefault(DEPTH_STRIDER_MAX_LEVEL, 3); - - configuration.addDefault(DIG_SPEED_BOOL, true); - configuration.addDefault(DIG_SPEED_MAX_LEVEL, 5); - - configuration.addDefault(DURABILITY_BOOL, true); - configuration.addDefault(DURABILITY_MAX_LEVEL, 3); + public static void initializeConfig() { + File file = ConfigurationEngine.fileCreator("ProceduralItemGenerationSettings.yml"); + fileConfiguration = ConfigurationEngine.fileConfigurationCreator(file); - configuration.addDefault(FIRE_ASPECT_BOOL, true); - configuration.addDefault(FIRE_ASPECT_MAX_LEVEL, 2); + doProceduralItemDrops = ConfigurationEngine.setBoolean(fileConfiguration, "dropProcedurallyGeneratedItems", true); + customEnchantmentChance = ConfigurationEngine.setDouble(fileConfiguration, "customEnchantmentsChance", 0.5); - configuration.addDefault(FROST_WALKER_BOOL, true); - configuration.addDefault(FROST_WALKER_MAX_LEVEL, 2); + addMaterial(Material.DIAMOND_HELMET); + addMaterial(Material.DIAMOND_CHESTPLATE); + addMaterial(Material.DIAMOND_LEGGINGS); + addMaterial(Material.DIAMOND_BOOTS); - configuration.addDefault(KNOCKBACK_BOOL, true); - configuration.addDefault(KNOCKBACK_MAX_LEVEL, 2); + addMaterial(Material.DIAMOND_SWORD); + addMaterial(Material.DIAMOND_AXE); - configuration.addDefault(LOOT_BONUS_BLOCKS_BOOL, true); - configuration.addDefault(LOOT_BONUS_BLOCKS_MAX_LEVEL, 3); - configuration.addDefault(LOOT_BONUS_MOBS_BOOL, true); - configuration.addDefault(LOOT_BONUS_MOBS_MAX_LEVEL, 3); + addMaterial(Material.IRON_HELMET); + addMaterial(Material.IRON_CHESTPLATE); + addMaterial(Material.IRON_LEGGINGS); + addMaterial(Material.IRON_BOOTS); - configuration.addDefault(LUCK_BOOL, true); - configuration.addDefault(LUCK_MAX_LEVEL, 3); + addMaterial(Material.IRON_SWORD); + addMaterial(Material.IRON_AXE); - configuration.addDefault(LURE_BOOL, true); - configuration.addDefault(LURE_MAX_LEVEL, 3); - configuration.addDefault(MENDING_BOOL, false); + addMaterial(Material.GOLDEN_HELMET); + addMaterial(Material.GOLDEN_CHESTPLATE); + addMaterial(Material.GOLDEN_LEGGINGS); + addMaterial(Material.GOLDEN_BOOTS); - configuration.addDefault(OXYGEN_BOOL, true); - configuration.addDefault(OXYGEN_MAX_LEVEL, 3); + addMaterial(Material.GOLDEN_SWORD); + addMaterial(Material.GOLDEN_AXE); - configuration.addDefault(PROTECTION_ENVIRONMENTAL_BOOL, true); - configuration.addDefault(PROTECTION_ENVIRONMENTAL_MAX_LEVEL, 4); - configuration.addDefault(PROTECTION_EXPLOSIONS_BOOL, true); - configuration.addDefault(PROTECTION_EXPLOSIONS_MAX_LEVEL, 4); + addMaterial(Material.CHAINMAIL_HELMET); + addMaterial(Material.CHAINMAIL_CHESTPLATE); + addMaterial(Material.CHAINMAIL_LEGGINGS); + addMaterial(Material.CHAINMAIL_BOOTS); - configuration.addDefault(PROTECTION_FALL_BOOL, true); - configuration.addDefault(PROTECTION_FALL_MAX_LEVEL, 4); - configuration.addDefault(PROTECTION_FIRE_BOOL, true); - configuration.addDefault(PROTECTION_FIRE_MAX_LEVEL, 4); + addMaterial(Material.LEATHER_HELMET); + addMaterial(Material.LEATHER_CHESTPLATE); + addMaterial(Material.LEATHER_LEGGINGS); + addMaterial(Material.LEATHER_BOOTS); - configuration.addDefault(PROTECTION_PROJECTILE_BOOL, true); - configuration.addDefault(PROTECTION_PROJECTILE_MAX_LEVEL, 4); - configuration.addDefault(SILK_TOUCH_BOOL, true); + addMaterial(Material.STONE_SWORD); + addMaterial(Material.STONE_AXE); - configuration.addDefault(SWEEPING_EDGE_BOOL, true); - configuration.addDefault(SWEEPING_EDGE_MAX_LEVEL, 3); - configuration.addDefault(THORNS_BOOL, true); - configuration.addDefault(THORNS_MAX_LEVEL, 3); + addMaterial(Material.WOODEN_SWORD); + addMaterial(Material.WOODEN_AXE); - configuration.addDefault(VANISHING_CURSE_BOOL, true); - configuration.addDefault(WATER_WORKER_BOOL, true); - configuration.addDefault(WATER_WORKER_MAX_LEVEL, 1); + addMaterial(Material.SHIELD); + addMaterial(Material.TURTLE_HELMET); + addMaterial(Material.TRIDENT); + addMaterial(Material.BOW); + addMaterial(Material.CROSSBOW); - configuration.addDefault(HUNTER_BOOL, true); - configuration.addDefault(HUNTER_MAX_LEVEL, 3); + cacheMaterials(); - configuration.addDefault(SWORD_MATERIAL_NAME, "Sword"); - configuration.addDefault(BOW_MATERIAL_NAME, "Bow"); - configuration.addDefault(PICKAXE_MATERIAL_NAME, "Pickaxe"); - configuration.addDefault(SPADE_MATERIAL_NAME, "Spade"); - configuration.addDefault(HOE_MATERIAL_NAME, "Hoe"); - configuration.addDefault(AXE_MATERIAL_NAME, "Axe"); - configuration.addDefault(FISHING_ROD_MATERIAL_NAME, "Fishing Rod"); - configuration.addDefault(SHIELD_MATERIAL_NAME, "Shield"); - configuration.addDefault(SHEARS_MATERIAL_NAME, "Shears"); - configuration.addDefault(HELMET_MATERIAL_NAME, "Helmet"); - configuration.addDefault(CHESTPLATE_MATERIAL_NAME, "Chestplate"); - configuration.addDefault(LEGGINGS_MATERIAL_NAME, "Leggings"); - configuration.addDefault(BOOTS_MATERIAL_NAME, "Boots"); - configuration.addDefault(CUSTOM_ENCHANTMENT_CHANCE, 0.1); + swordName = ConfigurationEngine.setString(fileConfiguration, "materialNames.swordName", "Sword"); + bowName = ConfigurationEngine.setString(fileConfiguration, "materialNames.bowName", "Bow"); + pickaxeName = ConfigurationEngine.setString(fileConfiguration, "materialNames.pickaxe", "Pickaxe"); + spadeName = ConfigurationEngine.setString(fileConfiguration, "materialNames.spade", "Spade"); + hoeName = ConfigurationEngine.setString(fileConfiguration, "materialNames.hoe", "Hoe"); + axeName = ConfigurationEngine.setString(fileConfiguration, "materialNames.axe", "Axe"); + helmetName = ConfigurationEngine.setString(fileConfiguration, "materialNames.helmet", "Helmet"); + chestplateName = ConfigurationEngine.setString(fileConfiguration, "materialNames.chestplate", "Chestplate"); + leggingsName = ConfigurationEngine.setString(fileConfiguration, "materialNames.leggings", "Leggings"); + bootsName = ConfigurationEngine.setString(fileConfiguration, "materialNames.boots", "Boots"); + shearsName = ConfigurationEngine.setString(fileConfiguration, "materialNames.shears", "Shears"); + fishingRodName = ConfigurationEngine.setString(fileConfiguration, "materialNames.fishingRod", "Fishing Rod"); + shieldName = ConfigurationEngine.setString(fileConfiguration, "materialNames.shield", "Shield"); + tridentName = ConfigurationEngine.setString(fileConfiguration, "materialNames.trident", "Trident"); + crossbowName = ConfigurationEngine.setString(fileConfiguration, "materialNames.crossbow", "Crossbow"); - configuration.addDefault(ITEM_NAME_FORMAT, Arrays.asList( + nameFormat = ConfigurationEngine.setList(fileConfiguration, "nameFormats", Arrays.asList( "$verb $itemType of the $adjective $noun", "$itemType of the $adjective $noun", "$noun's $adjective $verb $itemType", @@ -356,7 +151,7 @@ public void intializeConfig() { "The $adjective $verb-er" )); - configuration.addDefault("Valid nouns", Arrays.asList( + nouns = ConfigurationEngine.setList(fileConfiguration, "nouns", Arrays.asList( "MagmaGuy", "Dawn", "Sunset", @@ -488,7 +283,7 @@ public void intializeConfig() { "Monk", "Sorcerer", "Warlock", - "Demon HunterEnchantment", + "Demon Hunter", "Death Knight", "Priest", "Shaman", @@ -558,219 +353,98 @@ public void intializeConfig() { "Pirate", "Vanguard", "Voidblade", - "Whisp", + "Wisp", "Peasant", "Footman", "Swordsman", "Thrall", "Felhound", "Huntress", - "HunterEnchantment" + "Hunter", + "Aarakorcra", + "Aboleth", + "Deva", + "Planetar", + "Solar", + "Ankheg", + "Azer", + "Behir", + "Death Tyrant", + "Blight", + "Bugbear", + "Hugbear", + "Bullywug", + "Cambion", + "Chuul", + "Lich King", + "Cockatrice", + "Couatl", + "Cyclops", + "Titan", + "Darkmantle", + "Ancient One", + "Demilich", + "Balor", + "Barlgura", + "Chasme", + "Dretch", + "Glabrezu", + "Goristro", + "Hezrou", + "Manes", + "Marilith", + "Nalfeshnee", + "Quasit", + "Vrock", + "Yochlol", + "Pit Fiend", + "Lemure", + "Dracolich", + "Doppleganger", + "Chromatic Dragon", + "Drider", + "Air Elemental", + "Earth Elemental", + "Fire Elemental", + "Water Elemental", + "Rohirrim", + "Gondorian", + "Empyrean", + "Faerie Dragon", + "Ettin", + "Flumph", + "Fomorian", + "Dao", + "Gnoll", + "Parshendi", + "Listener", + "Spren", + "Stormfather", + "Rosharian", + "Brightlord", + "Highprince", + "King", + "Emperor", + "Shardbearer", + "Surgebinder", + "Bondsmith", + "Golem", + "Gorgon", + "Hag", + "Harpy", + "Hippogriff", + "Homunculus", + "State Alchemist", + "Undying Soldier", + "Jackalwere", + "Nothic", + "Oni", + "Rakshasa", + "Revenant", + "Cultist" )); - configuration.addDefault("Valid verb-er (noun)", Arrays.asList( - "World Breaker", - "World Shatterer", - "Avenger", - "Ashbringer", - "Windseeker", - "Defiler", - "Thunderfury", - "Slicer", - "Slasher", - "Cutter", - "Stabber", - "Scratcher", - "Killer", - "Slayer", - "Destroyer", - "Hugger", - "Murderer", - "Slapper", - "Traveller", - "Teleporter", - "Blinker", - "Wrecker", - "Materializer", - "Spawner", - "Demander", - "Assaulter", - "Striker", - "Ambusher", - "Rusher", - "Stormer", - "Bombarder", - "Barrager", - "Smiter", - "Charger", - "Battler", - "Hammerer", - "Beater", - "Combater", - "Overwhelmer", - "Raider", - "Tackler", - "Shooter", - "Venturer", - "Cracker", - "Smasher", - "Shatterer", - "Fracturer", - "Splinterer", - "Pulverizer", - "Tearer", - "Renderer", - "Snapper", - "Burster", - "Exploder", - "Damager", - "Fragmenter", - "Splitter", - "Fortifier", - "Nudger", - "Tapper", - "Thumper", - "Butter", - "Clatterer", - "Striker", - "Whacker", - "Slammer", - "Summoner", - "Screamer", - "Shifter", - "Transformer", - "Modifyer", - "Twister", - "Blurrer", - "Warper", - "Alterer", - "Adapter", - "Evolver", - "HunterEnchantment", - "Trailer", - "Follower", - "Stalker", - "Shadower", - "Hounder", - "Caser", - "Mounter", - "Ascender", - "Riser", - "Springer", - "Hoarder", - "Reaper", - "Harvester", - "Saver", - "Shelterer", - "Cloaker", - "Shrouder", - "Encloser", - "Hider", - "Masker", - "Buryer", - "Clouder", - "Shader", - "Sealer", - "Enveloper", - "Veiler", - "Traverser", - "Forder", - "Glider", - "Howler", - "Whimperer", - "Screamer", - "Squealer", - "Bawler", - "Screecher", - "Chopper", - "Chipper", - "Snipper", - "Splitter", - "Axer", - "Slasher", - "Renderer", - "Tearer", - "Thinner", - "Cropper", - "Carver", - "Hacker", - "Piercer", - "Sawer", - "Shaver", - "Shearer", - "Miner", - "Excavater", - "Burrower", - "Driller", - "Tunneler", - "Invader", - "Boarder", - "Wanderer", - "Intruder", - "Evader", - "Runner", - "Dodger", - "Crasher", - "Battler", - "Wrestler", - "Scuffler", - "Dueler", - "Brawler", - "Clasher", - "Grappler", - "Scrapper", - "Attacker", - "Feuder", - "Catcher", - "Solver", - "Revealer", - "Leaper", - "Bouncer", - "Vaulter", - "Hopper", - "Surger", - "Punter", - "Dropkicker", - "Perceiver", - "Fader", - "Bleeder", - "Weakener", - "Forger", - "Releaser", - "Gatherer", - "Crusher", - "Propeller", - "Jogger", - "Sprinter", - "Scouter", - "Explorer", - "Digger", - "Trembler", - "Parter", - "Hacker", - "Carver", - "Divider", - "Halver", - "Breaker", - "Renderer", - "Ripper", - "Grazer", - "Imprisoner", - "Cornerer", - "Pinner", - "Catcher", - "Restrainer", - "Binder", - "Snagger", - "Snatcher", - "Cager", - "Capturer", - "Haunter", - "Creeper", - "Sneaker" - )); - - configuration.addDefault("Valid adjectives", Arrays.asList( + adjectives = ConfigurationEngine.setList(fileConfiguration, "adjectives", Arrays.asList( "Adorable", "Beautiful", "Clean", @@ -1293,10 +967,13 @@ public void intializeConfig() { "Worried", "Worthless", "Wrong", - "Menacing" + "Menacing", + "Trusting", + "Unassuming", + "Threatening" )); - configuration.addDefault("Valid verbs", Arrays.asList( + verbs = ConfigurationEngine.setList(fileConfiguration, "verbs", Arrays.asList( "Slashing", "Cutting", "Stabbing", @@ -1556,36 +1233,236 @@ public void intializeConfig() { "Creeping", "Sneaking", "Spying", - "Avenging" + "Avenging", + "Storming" + )); + verbers = ConfigurationEngine.setList(fileConfiguration, "verb-ers (noun)", Arrays.asList( + "World Breaker", + "World Shatterer", + "Avenger", + "Ashbringer", + "Windseeker", + "Defiler", + "Thunderfury", + "Slicer", + "Slasher", + "Cutter", + "Stabber", + "Scratcher", + "Killer", + "Slayer", + "Destroyer", + "Hugger", + "Murderer", + "Slapper", + "Traveller", + "Teleporter", + "Blinker", + "Wrecker", + "Materializer", + "Spawner", + "Demander", + "Assaulter", + "Striker", + "Ambusher", + "Rusher", + "Stormer", + "Bombarder", + "Barrager", + "Smiter", + "Charger", + "Battler", + "Hammerer", + "Beater", + "Combater", + "Overwhelmer", + "Raider", + "Tackler", + "Shooter", + "Venturer", + "Cracker", + "Smasher", + "Shatterer", + "Fracturer", + "Splinterer", + "Pulverizer", + "Tearer", + "Renderer", + "Snapper", + "Burster", + "Exploder", + "Damager", + "Fragmenter", + "Splitter", + "Fortifier", + "Nudger", + "Tapper", + "Thumper", + "Butter", + "Clatterer", + "Striker", + "Whacker", + "Slammer", + "Summoner", + "Screamer", + "Shifter", + "Transformer", + "Modifyer", + "Twister", + "Blurrer", + "Warper", + "Alterer", + "Adapter", + "Evolver", + "HunterEnchantment", + "Trailer", + "Follower", + "Stalker", + "Shadower", + "Hounder", + "Caser", + "Mounter", + "Ascender", + "Riser", + "Springer", + "Hoarder", + "Reaper", + "Harvester", + "Saver", + "Shelterer", + "Cloaker", + "Shrouder", + "Encloser", + "Hider", + "Masker", + "Buryer", + "Clouder", + "Shader", + "Sealer", + "Enveloper", + "Veiler", + "Traverser", + "Forder", + "Glider", + "Howler", + "Whimperer", + "Screamer", + "Squealer", + "Bawler", + "Screecher", + "Chopper", + "Chipper", + "Snipper", + "Splitter", + "Axer", + "Slasher", + "Renderer", + "Tearer", + "Thinner", + "Cropper", + "Carver", + "Hacker", + "Piercer", + "Sawer", + "Shaver", + "Shearer", + "Miner", + "Excavater", + "Burrower", + "Driller", + "Tunneler", + "Invader", + "Boarder", + "Wanderer", + "Intruder", + "Evader", + "Runner", + "Dodger", + "Crasher", + "Battler", + "Wrestler", + "Scuffler", + "Dueler", + "Brawler", + "Clasher", + "Grappler", + "Scrapper", + "Attacker", + "Feuder", + "Catcher", + "Solver", + "Revealer", + "Leaper", + "Bouncer", + "Vaulter", + "Hopper", + "Surger", + "Punter", + "Dropkicker", + "Perceiver", + "Fader", + "Bleeder", + "Weakener", + "Forger", + "Releaser", + "Gatherer", + "Crusher", + "Propeller", + "Jogger", + "Sprinter", + "Scouter", + "Explorer", + "Digger", + "Trembler", + "Parter", + "Hacker", + "Carver", + "Divider", + "Halver", + "Breaker", + "Renderer", + "Ripper", + "Grazer", + "Imprisoner", + "Cornerer", + "Pinner", + "Catcher", + "Restrainer", + "Binder", + "Snagger", + "Snatcher", + "Cager", + "Capturer", + "Haunter", + "Creeper", + "Sneaker", + "Binder", + "Jailer", + "Seducer", + "Dancer", + "Blasphemer", + "Eater", + "Snorer", + "Thruster", + "Slapper" )); - configuration.options().copyDefaults(true); - UnusedNodeHandler.clearNodes(configuration); - customConfigLoader.saveDefaultCustomConfig(CONFIG_NAME); - customConfigLoader.saveCustomConfig(CONFIG_NAME); + ConfigurationEngine.fileSaverCustomValues(fileConfiguration, file); + MaterialGenerator.initializeValidProceduralMaterials(); } - private String boolValidEnchantmentConstructor(String string) { - - String validEnchantmentsprefix = "Valid Enchantments."; - String allowSuffix = ".Allow"; - - String finalString = validEnchantmentsprefix + string + allowSuffix; - - return finalString; - + private static void addMaterial(Material material) { + ConfigurationEngine.setBoolean(fileConfiguration, "validMaterials." + material.name(), true); } - private String maxLevelValidEnchantmentConstructor(String string) { - - String validEnchantmentsprefix = "Valid Enchantments."; - String maxLevelSuffix = ".Max Level"; - - String finalString = validEnchantmentsprefix + string + maxLevelSuffix; - - return finalString; + public static void cacheMaterials() { + validMaterials.clear(); + for (String material : fileConfiguration.getConfigurationSection("validMaterials").getKeys(false)) + if (fileConfiguration.getConfigurationSection("validMaterials").getBoolean(material)) + validMaterials.add(material); } + } diff --git a/src/main/java/com/magmaguy/elitemobs/config/QuestsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/QuestsConfig.java new file mode 100644 index 000000000..dd07a16f4 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/QuestsConfig.java @@ -0,0 +1,240 @@ +package com.magmaguy.elitemobs.config; + +import com.magmaguy.elitemobs.quests.objectives.CustomFetchObjective; +import com.magmaguy.elitemobs.quests.objectives.DialogObjective; +import com.magmaguy.elitemobs.quests.objectives.KillObjective; +import com.magmaguy.elitemobs.quests.objectives.Objective; +import com.magmaguy.elitemobs.utils.VersionChecker; +import com.magmaguy.elitemobs.utils.WarningMessage; +import lombok.Getter; +import org.bukkit.ChatColor; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.EntityType; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public class QuestsConfig { + + @Getter + private static boolean requireQuestTurnIn; + @Getter + private static String questJoinMessage; + @Getter + private static String questLeaveMessage; + @Getter + private static String questCompleteMessage; + @Getter + private static String leaveWhenNoActiveQuestsExist; + @Getter + private static String questLeaveConfirmationMessage; + @Getter + private static boolean useQuestAcceptTitles; + @Getter + private static String questStartTitle; + @Getter + private static String questStartSubtitle; + @Getter + private static boolean useQuestCompleteTitles; + @Getter + private static String questCompleteTitle; + @Getter + private static String questCompleteSubtitle; + @Getter + private static boolean useQuestLeaveTitles; + @Getter + private static String questLeaveTitle; + @Getter + private static String questLeaveSubtitle; + @Getter + private static boolean doQuestChatProgression; + @Getter + private static String ongoingColorCode; + @Getter + private static String completedColorCode; + @Getter + private static String killQuestChatProgressionMessage; + @Getter + private static String fetchQuestChatProgressionMessage; + @Getter + private static String dialogQuestChatProgressionMessage; + @Getter + private static boolean useQuestScoreboards; + @Getter + private static String killQuestScoreboardProgressionLine; + @Getter + private static String fetchQuestScoreboardProgressionLine; + @Getter + private static String dialogQuestScoreboardProgressionLine; + @Getter + private static int maximumActiveQuests; + @Getter + private static String questCapMessage; + @Getter + private static List questEntityTypes = new ArrayList<>(); + @Getter + private static String chatTrackMessage; + @Getter + private static String chatTrackHover; + @Getter + private static String chatTrackCommand; + @Getter + private static String chatTrackingMessage; + @Getter + private static String chatTrackingHover; + @Getter + private static String chatTrackingCommand; + @Getter + private static boolean autoTrackQuestsOnAccept; + @Getter + private static String noQuestDestinationFound; + @Getter + private static String questDestinationInOtherWorld; + @Getter + private static String questAlreadyCompletedMessage; + @Getter + private static String questPrerequisitesMissingMessage; + private QuestsConfig() { + } + + public static void initializeConfig() { + File file = ConfigurationEngine.fileCreator("Quests.yml"); + FileConfiguration fileConfiguration = ConfigurationEngine.fileConfigurationCreator(file); + + requireQuestTurnIn = ConfigurationEngine.setBoolean(fileConfiguration, "requireQuestTurnIn", true); + questJoinMessage = ConfigurationEngine.setString(fileConfiguration, "questJoinMessage", "&aYou have accepted the quest $questName &a!"); + questLeaveMessage = ConfigurationEngine.setString(fileConfiguration, "questLeaveMessage", "&cYou have abandoned the quest $questName &c!"); + questCompleteMessage = ConfigurationEngine.setString(fileConfiguration, "questCompleteMessage", "&2You completed the quest $questName &2!"); + leaveWhenNoActiveQuestsExist = ConfigurationEngine.setString(fileConfiguration, "leaveWhenNoActiveQuestsExist", "&cYou don't currently have an active quest!"); + questLeaveConfirmationMessage = ConfigurationEngine.setString(fileConfiguration, "questLeaveConfirmationMessage", "&cAre you sure you want to abandon your current quest? Do &a/em confirm &c to confirm your choice!"); + useQuestAcceptTitles = ConfigurationEngine.setBoolean(fileConfiguration, "useQuestAcceptTitles", true); + questStartTitle = ConfigurationEngine.setString(fileConfiguration, "questStartTitle", "&aQuest Accepted!"); + questStartSubtitle = ConfigurationEngine.setString(fileConfiguration, "questStartSubtitle", "$questName"); + useQuestCompleteTitles = ConfigurationEngine.setBoolean(fileConfiguration, "useQuestCompleteTitles", true); + questCompleteTitle = ConfigurationEngine.setString(fileConfiguration, "questCompleteTitle", "&2Quest Completed!"); + questCompleteSubtitle = ConfigurationEngine.setString(fileConfiguration, "questCompleteSubtitle", "$questName"); + useQuestLeaveTitles = ConfigurationEngine.setBoolean(fileConfiguration, "useQuestLeaveTitles", true); + questLeaveTitle = ConfigurationEngine.setString(fileConfiguration, "questLeaveTitle", "&cQuest Abandoned!"); + questLeaveSubtitle = ConfigurationEngine.setString(fileConfiguration, "questLeaveSubtitle", "$questName"); + doQuestChatProgression = ConfigurationEngine.setBoolean(fileConfiguration, "doQuestChatProgression", true); + ongoingColorCode = ConfigurationEngine.setString(fileConfiguration, "ongoingQuestColorCode", "&c"); + completedColorCode = ConfigurationEngine.setString(fileConfiguration, "ongoingQuestColorCode", "&2"); + killQuestChatProgressionMessage = ConfigurationEngine.setString(fileConfiguration, "killQuestChatProgressionMessage", "&8[EliteMobs]&c➤Kill $name:$color$current&0/$color$target"); + fetchQuestChatProgressionMessage = ConfigurationEngine.setString(fileConfiguration, "fetchQuestChatProgressionMessage", "&8[EliteMobs]&c➤Get $name:$color$current&0/$color$target"); + dialogQuestChatProgressionMessage = ConfigurationEngine.setString(fileConfiguration, "dialogQuestChatProgressionMessage", "&8[EliteMobs]&c➤Talk to $name:$color$current&0/$color$target"); + maximumActiveQuests = ConfigurationEngine.setInt(fileConfiguration, "maximumActiveQuests", 10); + questCapMessage = ConfigurationEngine.setString(fileConfiguration, "questCapMessage", "&8[EliteMobs] &cYou have reached the maximum amount of active quests (10)! " + + "&4Abandon or complete at least one active quest if you want to get more quests!"); + + useQuestScoreboards = ConfigurationEngine.setBoolean(fileConfiguration, "useQuestScoreboards", true); + + killQuestScoreboardProgressionLine = ConfigurationEngine.setString(fileConfiguration, "killQuestScoreboardProgressionMessage", "&c➤Kill $name:$color$current&0/$color$target"); + fetchQuestScoreboardProgressionLine = ConfigurationEngine.setString(fileConfiguration, "fetchQuestScoreboardProgressionMessage", "&c➤Get $name:$color$current&0/$color$target"); + dialogQuestScoreboardProgressionLine = ConfigurationEngine.setString(fileConfiguration, "dialogQuestScoreboardProgressionMessage", "&c➤Talk to $name:$color$current&0/$color$target"); + + questEntityTypes = setEntityTypes(fileConfiguration); + + chatTrackMessage = ConfigurationEngine.setString(fileConfiguration, "chatTrackMessage", "&8[EliteMobs]&2 Click here to track your quest!"); + chatTrackHover = ConfigurationEngine.setString(fileConfiguration, "chatTrackHover", "&2Click to track!"); + chatTrackCommand = ConfigurationEngine.setString(fileConfiguration, "chatTrackCommand", "/elitemobs quest track $questID"); + + chatTrackingMessage = ConfigurationEngine.setString(fileConfiguration, "chatTrackingMessage", "&8[EliteMobs]&9 You are now tracking a quest!"); + chatTrackingHover = ConfigurationEngine.setString(fileConfiguration, "chatTrackingHover", "&2Click to untrack/track! /em -> Quests to track a different quest!"); + chatTrackingCommand = ConfigurationEngine.setString(fileConfiguration, "chatTrackingCommand", "/elitemobs quest track $questID"); + + autoTrackQuestsOnAccept = ConfigurationEngine.setBoolean(fileConfiguration, "autoTrackQuestsOnAccept", true); + + noQuestDestinationFound = ConfigurationEngine.setString(fileConfiguration, "noQuestDestinationFound", "[EM] No quest destination found!"); + questDestinationInOtherWorld = ConfigurationEngine.setString(fileConfiguration, "questDestinationInOtherWorld", "[EM] Go to world $world!"); + + questAlreadyCompletedMessage = ConfigurationEngine.setString(fileConfiguration, "questAlreadyCompletedMessage", "&8[EliteMobs] &cYou already completed this quest!"); + questPrerequisitesMissingMessage = ConfigurationEngine.setString(fileConfiguration, "questPrerequisitesMissingMessage", "&8[EliteMobs] &cCan't accept this quest yet!"); + + ConfigurationEngine.fileSaverOnlyDefaults(fileConfiguration, file); + } + + private static List setEntityTypes(FileConfiguration fileConfiguration) { + List entityTypes = new ArrayList<>(Arrays.asList( + EntityType.BLAZE.toString(), + EntityType.CAVE_SPIDER.toString(), + EntityType.DROWNED.toString(), + EntityType.ELDER_GUARDIAN.toString(), + EntityType.ENDERMAN.toString(), + EntityType.ENDERMITE.toString(), + EntityType.EVOKER.toString(), + EntityType.GHAST.toString(), + EntityType.GUARDIAN.toString(), + EntityType.HUSK.toString(), + EntityType.ILLUSIONER.toString(), + EntityType.IRON_GOLEM.toString(), + EntityType.PILLAGER.toString(), + EntityType.RAVAGER.toString(), + EntityType.SILVERFISH.toString(), + EntityType.SKELETON.toString(), + EntityType.SPIDER.toString(), + EntityType.STRAY.toString(), + EntityType.VINDICATOR.toString(), + EntityType.WITCH.toString(), + EntityType.WITHER_SKELETON.toString(), + EntityType.WOLF.toString(), + EntityType.ZOMBIE.toString() + )); + + if (!VersionChecker.serverVersionOlderThan(16, 0)) { + List laterEntities = Arrays.asList( + EntityType.HOGLIN.toString(), + EntityType.ZOGLIN.toString(), + EntityType.PIGLIN_BRUTE.toString(), + EntityType.PIGLIN.toString(), + EntityType.ZOMBIFIED_PIGLIN.toString()); + entityTypes.addAll(laterEntities); + } + + ConfigurationEngine.setList(fileConfiguration, "questEntityTypes", entityTypes); + + List parsedTypes = new ArrayList<>(); + for (String string : entityTypes) + try { + parsedTypes.add(EntityType.valueOf(string)); + } catch (Exception ex) { + new WarningMessage("Entity type " + string + " is not a valid entity type from the Spigot API!"); + } + return parsedTypes; + } + + public static String getQuestChatProgressionMessage(Objective objective) { + String newString = ""; + if (objective instanceof KillObjective) + newString = killQuestChatProgressionMessage; + else if (objective instanceof CustomFetchObjective) + newString = fetchQuestChatProgressionMessage; + else if (objective instanceof DialogObjective) + newString = dialogQuestChatProgressionMessage; + newString = newString.replace("$name", ChatColor.WHITE + ChatColor.stripColor(objective.getObjectiveName())); + newString = newString.replace("$current", objective.getCurrentAmount() + ""); + newString = newString.replace("$target", objective.getTargetAmount() + ""); + if (!objective.isObjectiveCompleted()) + return newString.replace("$color", ongoingColorCode); + else + return newString.replace("$color", completedColorCode); + } + + public static String getQuestScoreboardProgressionLine(Objective objective) { + String newString = ""; + if (objective instanceof KillObjective) + newString = killQuestScoreboardProgressionLine; + else if (objective instanceof CustomFetchObjective) + newString = fetchQuestScoreboardProgressionLine; + else if (objective instanceof DialogObjective) + newString = dialogQuestScoreboardProgressionLine; + newString = newString.replace("$name", ChatColor.WHITE + ChatColor.stripColor(objective.getObjectiveName())); + newString = newString.replace("$current", objective.getCurrentAmount() + ""); + newString = newString.replace("$target", objective.getTargetAmount() + ""); + if (!objective.isObjectiveCompleted()) + return newString.replace("$color", ongoingColorCode); + else + return newString.replace("$color", completedColorCode); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/ReadMeForTranslationsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/ReadMeForTranslationsConfig.java new file mode 100644 index 000000000..8d1f91b35 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/ReadMeForTranslationsConfig.java @@ -0,0 +1,26 @@ +package com.magmaguy.elitemobs.config; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.utils.WarningMessage; +import org.apache.commons.io.FileUtils; + +import java.io.File; +import java.io.InputStream; +import java.nio.file.Paths; + +public class ReadMeForTranslationsConfig { + private ReadMeForTranslationsConfig() { + } + + public static void initialize() { + InputStream inputStream = MetadataHandler.PLUGIN.getResource("READ_ME_FOR_TRANSLATIONS.yml"); + try { + FileUtils.copyInputStreamToFile(inputStream, new File(Paths.get(MetadataHandler.PLUGIN.getDataFolder() + + "/READ_ME_FOR_TRANSLATIONS.yml").normalize().toString())); + } catch (Exception ex) { + new WarningMessage("Failed to write read me for translations file!"); + ex.printStackTrace(); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/TranslationConfig.java b/src/main/java/com/magmaguy/elitemobs/config/TranslationConfig.java index b42e74aaa..510853339 100644 --- a/src/main/java/com/magmaguy/elitemobs/config/TranslationConfig.java +++ b/src/main/java/com/magmaguy/elitemobs/config/TranslationConfig.java @@ -1,530 +1,102 @@ -/* - * 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 . - */ - package com.magmaguy.elitemobs.config; -import org.bukkit.configuration.Configuration; +import lombok.Getter; +import org.bukkit.configuration.file.FileConfiguration; -import java.util.Arrays; +import java.io.File; /** * Created by MagmaGuy on 12/05/2017. */ public class TranslationConfig { + /* + Translation for the economy messages + */ + @Getter + private static String economyPayMessage; + @Getter + private static String economyCurrencyLeftMessage; + @Getter + private static String economyPaymentReceivedMessage; + @Getter + private static String economyPaymentInsufficientCurrency; + @Getter + private static String economyWalletCommand; + @Getter + private static String economyTaxMessage; + /* + Translation for the shop messages + */ + @Getter + private static String shopBuyMessage; + @Getter + private static String shopSellMessage; + @Getter + private static String shopInsufficientFundsMessage; + @Getter + private static String shopSaleInstructions; + @Getter + private static String shopSaleOthersItems; + @Getter + private static String shopCurrentBalance; + @Getter + private static String shopItemPrice; + /* + Translation for the teleport messages + */ + @Getter + private static String teleportTimeLeft; + @Getter + private static String teleportCancelled; + @Getter + private static String noPendingCommands; + @Getter + private static String shopBatchSellMessage; + @Getter + private static String trackMessage; + @Getter + private static String chestLowRankMessage; + @Getter + private static String chestCooldownMessage; + @Getter + private static String insufficientCurrencyForWormholeMessage; + @Getter + private static String dismissEMMessage; + @Getter + private static String switchEMStyleMessage; + + private TranslationConfig() { + } - private static final String ELITE_MOB_NAME = "Elite mob names."; - public static final String NAME_BLAZE = ELITE_MOB_NAME + "Blaze"; - public static final String NAME_CAVE_SPIDER = ELITE_MOB_NAME + "CaveSpider"; - public static final String NAME_CREEPER = ELITE_MOB_NAME + "Creeper"; - public static final String NAME_ENDERMAN = ELITE_MOB_NAME + "Enderman"; - public static final String NAME_ENDERMITE = ELITE_MOB_NAME + "Endermite"; - public static final String NAME_HUSK = ELITE_MOB_NAME + "Husk"; - public static final String NAME_IRON_GOLEM = ELITE_MOB_NAME + "IronGolem"; - public static final String NAME_PIG_ZOMBIE = ELITE_MOB_NAME + "PigZombie"; - public static final String NAME_POLAR_BEAR = ELITE_MOB_NAME + "PolarBear"; - public static final String NAME_SILVERFISH = ELITE_MOB_NAME + "Silverfish"; - public static final String NAME_SKELETON = ELITE_MOB_NAME + "Skeleton"; - public static final String NAME_SPIDER = ELITE_MOB_NAME + "Spider"; - public static final String NAME_STRAY = ELITE_MOB_NAME + "Stray"; - public static final String NAME_WITCH = ELITE_MOB_NAME + "Witch"; - public static final String NAME_WITHER_SKELETON = ELITE_MOB_NAME + "WitherSkeleton"; - public static final String NAME_ZOMBIE = ELITE_MOB_NAME + "Zombie"; - public static final String NAME_VEX = ELITE_MOB_NAME + "Vex"; - public static final String NAME_VINDICATOR = ELITE_MOB_NAME + "Vindicator"; - public static final String NAME_DROWNED = ELITE_MOB_NAME + "Drowned"; - - public static final String NAME_CHICKEN = ELITE_MOB_NAME + "Chicken"; - public static final String NAME_COW = ELITE_MOB_NAME + "Cow"; - public static final String NAME_MUSHROOM_COW = ELITE_MOB_NAME + "MushroomCow"; - public static final String NAME_PIG = ELITE_MOB_NAME + "Pig"; - public static final String NAME_SHEEP = ELITE_MOB_NAME + "Sheep"; - - public static final String CONFIG_NAME = "translation.yml"; - CustomConfigLoader customConfigLoader = new CustomConfigLoader(); - Configuration configuration = customConfigLoader.getCustomConfig(CONFIG_NAME); - - public void initializeConfig() { - - configuration.addDefault(NAME_BLAZE, "Level $level Elite Blaze"); - configuration.addDefault(NAME_CAVE_SPIDER, "Level $level Elite Cave Spider"); - configuration.addDefault(NAME_CREEPER, "Level $level Elite Creeper"); - configuration.addDefault(NAME_ENDERMAN, "Level $level Elite Enderman"); - configuration.addDefault(NAME_ENDERMITE, "Level $level Elite Endermite"); - configuration.addDefault(NAME_HUSK, "Level $level Elite Husk"); - configuration.addDefault(NAME_IRON_GOLEM, "Level $level Elite Iron Golem"); - configuration.addDefault(NAME_PIG_ZOMBIE, "Level $level Elite Zombie Pigman"); - configuration.addDefault(NAME_POLAR_BEAR, "Level $level Elite Polar Bear"); - configuration.addDefault(NAME_SILVERFISH, "Level $level Elite Silverfish"); - configuration.addDefault(NAME_SKELETON, "Level $level Elite Skeleton"); - configuration.addDefault(NAME_SPIDER, "Level $level Elite Spider"); - configuration.addDefault(NAME_STRAY, "Level $level Elite Stray"); - configuration.addDefault(NAME_WITCH, "Level $level Elite Witch"); - configuration.addDefault(NAME_WITHER_SKELETON, "Level $level Elite Wither Skeleton"); - configuration.addDefault(NAME_ZOMBIE, "Level $level Elite Zombie"); - configuration.addDefault(NAME_VEX, "Level $level Elite Vex"); - configuration.addDefault(NAME_VINDICATOR, "Level $level Elite Vindicator"); - configuration.addDefault(NAME_DROWNED, "Level $level Elite Drowned"); - - configuration.addDefault(NAME_CHICKEN, "Super Chicken"); - configuration.addDefault(NAME_COW, "Super Cow"); - configuration.addDefault(NAME_MUSHROOM_COW, "Super Mooshroom"); - configuration.addDefault(NAME_PIG, "Super Pig"); - configuration.addDefault(NAME_SHEEP, "Super Sheep"); - - configuration.addDefault("ScoreBoard.Health", "Health: "); - - configuration.addDefault("Taunts.Target", Arrays.asList( - "OI! Get over here!", - "What's that I see? A coward?", - "Sir, prepare your fisticuffs!", - "Let's settle this like cavemen!", - "En garde!", - "Look out! A creeper, behind you!", - "Aren't you a right ugly mug!", - "You look delicious.", - "Prepare for trouble!", - "Let the best click spammer win!", - "SPARTAAAAAA", - "I am actually level 9001", - "Not an Elite Mob", - "Poorly disguised Elite Mob", - "Ah, fresh prey!", - "The hunter becomes the hunted!", - "Killing me crashes the server", - "I'm actually a disguised player!", - "I'm not going to drop any loot!", - "Why can't we be friends?", - "Sssssss", - "This is my last day on the job!", - "Stop right there criminal scum!", - "Prepare to die!", - "Praise the Sun!", - "Git gud", - "Alea jacta est!", - "Facta, non verba!", - "Skulls for the skull throne!", - "Blood for the blood throne!", - "A sacrifice for Herobrine!", - "I shall pierce the heavens!", - "Just who do you think I am!?", - "A weakling! He's mine.", - "Dibs on the weakling!", - "Accio player!", - "A duel to the death!", - "I challenge you to a duel!", - "Pika pika!", - "Did you just call me an infernal", - "What did you just call me?", - "I know what you did you monster!", - "This is how your story ends!", - "Prepare for trouble!", - "I've been preparing for this!", - "I am prepared. Are you?", - "A worthy foe!", - "A worthy opponent!", - "A newbie! It's my lucky day!", - "Your stuff or your life!", - "This is a robbery!", - "It's you! You monster!", - "So hungry, give me your flesh!", - "There he is!", - "Must've been my imagination", - "Hi I'm Mr Meeseeks!", - "I'm Mr Meeseeks, look at me!", - "Your diamonds or your life!", - "For king and country!", - "Hit me with your best shot!", - "Witness me!", - "Witness me blood bag!", - "I go all shiny and chrome!")); - - configuration.addDefault("Taunts.Damaged", Arrays.asList( - "Ow!", - "Oi!", - "Stop that!", - "Why?!", - "You fight like a Dairy Farmer!", - "You are a pain in the backside!", - "En garde! Touche!", - "Hacks!", - "My health is bugged, unkillable!", - "Your hits only make me stronger!", - "Sticks and stones...", - "'tis but a flesh wound!", - "Emperor protects!", - "Herobrine, aid me!", - "Behind you! A creeper!", - "I have made a terrible mistake.", - "What doesn't kill me...", - "Zombies dig scars", - "I shall show you my true power!", - "Prepare for my ultimate attack!", - "My reinforcements are arriving!", - "You're going to pay for that!", - "That's going to leave a mark!", - "An eye for an eye!", - "Health insurance will cover that", - "I felt that one in my bones", - "'tis but a scratch", - "What was that? A soft breeze?", - "You'll never defeat me like that", - "Pathetic.", - "Weak.", - "That didn't even dent my armor!", - "This is going to be an easy one", - "My grandchildren will feel that", - "Are you even trying?", - "An admin just fully healed me", - "Haxxor!", - "Me? Damaged? Hacks!", - "I can't be defeated!", - "Good thing I'm using hacks!", - "Watch out! Herobrine behind you!", - "My life for Aiur!", - "Your home is getting griefed!", - "Why can't we be friends?", - "Valhalla!", - "Notch save me!", - "No retreat!", - "Hit me with your best shot!" - )); - - configuration.addDefault("Taunts.BowDamaged", Arrays.asList( - "Fight me like a Player!", - "Afraid to come up-close?", - "I can smell your fear from here!", - "Did you forget your sword?", - "Coward! Bow are no fair!", - "Bows? That's so 2011...", - "Bows are for the weak of mind!", - "Bows are for the weak of spirit!", - "Bows are for the weak of heart!", - "I thought we agreed no bows!", - "Bows? You'll regret that", - - //regular hits - "Ow!", - "Oi!", - "Stop that!", - "Why?!", - "You fight like a Dairy Farmer!", - "You are a pain in the backside!", - "En garde! Touche!", - "Hacks!", - "My health is bugged, unkillable!", - "Your hits only make me stronger!", - "Sticks and stones...", - "'tis but a flesh wound!", - "Emperor protects!", - "Herobrine, aid me!", - "Behind you! A creeper!", - "I have made a terrible mistake.", - "What doesn't kill me...", - "Zombies dig scars", - "I shall show you my true power!", - "Prepare for my ultimate attack!", - "My reinforcements are arriving!", - "You're going to pay for that!", - "That's going to leave a mark!", - "An eye for an eye!", - "Health insurance will cover that", - "I felt that one in my bones", - "'tis but a scratch", - "What was that? A soft breeze?", - "You'll never defeat me like that", - "Pathetic.", - "Weak.", - "That didn't even dent my armor!", - "This is going to be an easy one", - "My grandchildren will feel that", - "Are you even trying?", - "An admin just fully healed me", - "Haxxor!", - "Me? Damaged? Hacks!", - "I can't be defeated!", - "Good thing I'm using hacks!", - "Watch out! Herobrine behind you!", - "My life for Aiur!", - "Your home is getting griefed!", - "Why can't we be friends?", - "Valhalla!", - "Notch save me!", - "No retreat!", - "Hit me with your best shot!" - )); - - configuration.addDefault("Taunts.Hit", Arrays.asList( - "A solid hit!", - "He shoots, and he scores!", - "You'll feel that in the morning!", - "Victory approaches!", - "Victory shall be mine!", - "That was only half of my power!", - "You came to the wrong hood!", - "You messed with the wrong mob!", - "Get ready to get mobbed on!", - "This was your last mistake!", - "Feel the burn!", - "John Cena", - "How are you still standing?", - "Just give up already!", - "Give up!", - "I have the high ground!", - "I will end you!", - "Hope you came prepared for pain!", - "The hunter becomes the hunted!", - "Blood for the blood throne!", - "Skulls for the skull throne!", - "A good player is a dead player!", - "Git gud!", - "Praise the Sun!", - "The end draws near!", - "You are not prepared.", - "Zug zug!", - "Hardly worth my time!", - "I thought this was a challenge?", - "Pro tip: don't get hit", - "Ima firin mah lazer bwooooooooo", - "For the Emperor!", - "Herobrine shall be pleased!", - "This is the end for you!", - "Are you even trying?", - "Weakling!", - "Pathetic.", - "Maybe this will wake you up.", - "This is just the beggining!", - "We're just getting started!", - "That was just a warm-up!", - "You are no match for me!", - "RKO out of nowhere!", - "I can do this all night long!", - "A fine punching bag!", - "I am the night!", - "I wonder what will break first", - "Revenge for Steve! You monster!", - "Join the mob side!", - "Too easy, too easy!", - "Too easy!", - "You can't defeat me!", - "Pikachuuuuuu", - "Avada kedavra!", - "Crucio!", - "Jierda!", - "A critical hit!", - "This is what skills looks like!", - "9001 damage!", - "Still standing?", - "Face your defeat!", - "A taste of pain to come!", - "I'll make you endangered!" - )); - - configuration.addDefault("Taunts.Death", Arrays.asList( - "Alas, poor Yorick!", - "The rest is silence", - "I shall return", - "Unforgivable", - "I live, I die, I live again!", - "WITNESS ME", - "I ride to valhalla!", - "VALHALLA!", - "VALHALLA! DELIVERANCE", - "You win, this time", - "A blight upon your land!", - "A pox upon thee!", - "You'll join me soon enough!", - "This is not over", - "Death is but a setback", - "Not like this...", - "I just wanted to go into space", - "We could've been friends", - "Your sins crawling on your back", - "See you in a bit", - "See you later", - "I'll be waiting for you", - "I will be avenged!", - "I won't go gently into the night", - "Should've gotten life insurance", - "It was my last day on the job", - "It was my last day here", - "Et tu, Brute?", - "RIP", - "x.x", - "(x.x)", - "xox", - "Fainted", - "GG, WP", - "GG", - "WP", - "GG no RE", - "HAX", - "Hacker", - "Not fair I was lagging", - "You win, this time", - "You monster...", - "Mediocre..." - )); - - configuration.addDefault("ZombieFriends.Friend 1", "BFF #1"); - configuration.addDefault("ZombieFriends.Friend 2", "BFF #2"); - - configuration.addDefault("ZombieFriends.DeathMessage", Arrays.asList( - "Noooo!", - "Mediocre!", - "Zacharias!", - "He's deader than before!" - )); - - configuration.addDefault("ZombieFriends.ZombieDialog", Arrays.asList( - "Let's play ZombieCraft later!", - "Feel the power of friendship!", - "El pueblo, unido!", - "I called my friends over!", - "BFF power!", - "One for all!", - "Get him!", - "Screw you guys, I'm going home!" - )); - - configuration.addDefault("ZombieFriends.FriendDialog", Arrays.asList( - "Don't mess with our friends!", - "We got your back Zach!", - "Backup has arrived!", - "One for all, one for all!", - "This is going to be easy!", - "Give up we have the high ground!", - "You wanna go bruv?", - "Worldstaaaaaaaaar!", - "What are you doing to our friend", - "Feel the power of friendship!", - "Friendship power at 100%!", - "Zombies, assemble!", - "We got your back mate!", - "Together we are better!", - "The more the merrier!", - "I got you fam!", - "All for one!" - )); - - configuration.addDefault("ZombieNecronomicon.Summoned zombie", "Summoned Zombie"); - configuration.addDefault("ZombieNecronomicon.Summoned skeleton", "Summoned Skeleton"); - configuration.addDefault("ZombieNecronomicon.Summoning chant", "Nor is it to be thought..." + - "that man is either the oldest " + - "or the last of earth's masters, or that the common bulk of life and substance walks alone. The Old Ones" + - " were, the Old Ones are, and the Old Ones shall be. Not in the spaces we know, but between them, they " + - "walk serene and primal, undimensioned and to us unseen. Yog-Sothoth knows the gate. Yog-Sothoth is the " + - "gate. Yog-Sothoth is the key and guardian of the gate. Past, present, future, all are one in Yog-Sothoth. " + - "He knows where the Old Ones broke through of old, and where They shall break through again. He knows " + - "where They had trod earth's fields, and where They still tread them, and why no one can behold Them as " + - "They tread. By Their smell can men sometimes know Them near, but of Their semblance can no man know, " + - "saving only in the features of those They have begotten on mankind; and of those are there many sorts, " + - "differing in likeness from man's truest eidolon to that shape without sight or substance which is Them. " + - "They walk unseen and foul in lonely places where the Words have been spoken and the Rites howled through " + - "at their Seasons. The wind gibbers with Their voices, and the earth mutters with Their consciousness. " + - "They bend the forest and crush the city, yet may not forest or city behold the hand that smites. Kadath " + - "in the cold waste hath known Them, and what man knows Kadath? The ice desert of the South and the sunken " + - "isles of Ocean hold stones whereon Their seal is engraver, but who hath seen the deep frozen city or the " + - "sealed tower long garlanded with seaweed and barnacles? Great Cthulhu is Their cousin, yet can he spy " + - "Them only dimly. Iä! Shub-Niggurath! As a foulness shall ye know Them. Their hand is at your throats, " + - "yet ye see Them not; and Their habitation is even one with your guarded threshold. Yog-Sothoth is the " + - "key to the gate, whereby the spheres meet. Man rules now where They ruled once; They shall soon rule " + - "where man rules now. After summer is winter, after winter summer. They wait patient and potent, for " + - "here shall They reign again."); - - configuration.addDefault("ZombieTeamRocket.Intro", Arrays.asList( - "Prepare for trouble!", - "Make it double!", - "To protect the world", - "from devastation!", - "To unite all people", - "within our nation!", - "To denounce the evils", - "of truth and love!", - "To extend our reach", - "to the stars above!", - "Jesse!", - "James!", - "Team Rocket blasts off", - "at the speed of light!", - "Surrender now", - "or prepare to fight!", - "Meowth! That's right!" - )); - - configuration.addDefault("ZombieTeamRocket.Jesse name", "Jesse"); - configuration.addDefault("ZombieTeamRocket.James name", "James"); - configuration.addDefault("ZombieTeamRocket.Meowth name", "Meowth"); - configuration.addDefault("ZombieTeamRocket.DeathMessage", "Team rocket blasts off again!"); - - configuration.addDefault("ZombieParents.Dad Name", "Zombie's Dad"); - configuration.addDefault("ZombieParents.Mom Name", "Zombie's Mom"); - - configuration.addDefault("ZombieParents.DeathMessage", Arrays.asList( - "You monster!", - "My baby!", - "What have you done!?", - "Revenge!", - "Nooooo!", - "You will pay for that!", - "Eh, he was adopted", - "He's dead! Again!", - "He's deader than before!", - "You broke him!" - )); - - configuration.addDefault("ZombieParents.ZombieDialog", Arrays.asList( - "You're embarrassing me!", - "He's bullying me!", - "He's the one picking on me!", - "I can deal with this alone!", - "Leave me alone, I got this!", - "Stop following me around!", - "God this is so embarassing!", - "He took my lunch money!", - "He's bullying me!" - )); - - configuration.addDefault("ZombieParents.ZombieDadDialog", Arrays.asList( - "Get away from my son!", - "Stand up for yourself son!", - "I'll deal with him!", - "Stop picking on my son!", - "Why are you doing this?", - "I'll talk to your parents!", - "You go kiddo!", - "Show him who's boss kiddo!", - "Nice punch kiddo!" - )); - - configuration.addDefault("ZombieParents.ZombieMomDialog", Arrays.asList( - "Hands off my child!", - "Are you hurt sweety?", - "Did he hurt you sweety?", - "Let me see that booboo sweety", - "I'll talk to his parents!", - "You forgot your jacket sweety!", - "Posture, sweetheart", - "Break it up!", - "Stop this!", - "Did you take out the garbage?" - )); - - configuration.options().copyDefaults(true); - UnusedNodeHandler.clearNodes(configuration); - customConfigLoader.saveDefaultCustomConfig(CONFIG_NAME); - customConfigLoader.saveCustomConfig(CONFIG_NAME); + public static void initializeConfig() { + + File file = ConfigurationEngine.fileCreator("translation.yml"); + FileConfiguration fileConfiguration = ConfigurationEngine.fileConfigurationCreator(file); + + economyPayMessage = ConfigurationEngine.setString(fileConfiguration, "Economy pay message v2", "&2You have paid &2$amount_sent $currency_name &2to $receiver&2, who got $amount_received after taxes!"); + economyCurrencyLeftMessage = ConfigurationEngine.setString(fileConfiguration, "Economy currency left message", "You now have &2$amount_left $currency_name"); + economyPaymentReceivedMessage = ConfigurationEngine.setString(fileConfiguration, "Economy money from payment message", "You have received &2$amount_received $currency_name &ffrom $sender"); + economyPaymentInsufficientCurrency = ConfigurationEngine.setString(fileConfiguration, "Economy payment insuficient currency", "&cYou don't have enough $currency_name to do that!"); + economyWalletCommand = ConfigurationEngine.setString(fileConfiguration, "Wallet command message", "You have &2$balance $currency_name"); + economyTaxMessage = ConfigurationEngine.setString(fileConfiguration, "Tax confirmation message", "&cSending a payment will cost $percentage% in taxes. &aDo &9$command &ato proceed!"); + shopBatchSellMessage = ConfigurationEngine.setString(fileConfiguration, "shopBatchSellItem", "&aYou have sold your items &afor $currency_amount $currency_name!"); + shopBuyMessage = ConfigurationEngine.setString(fileConfiguration, "Shop buy message", "&aYou have bought $item_name &afor $item_value $currency_name!"); + shopCurrentBalance = ConfigurationEngine.setString(fileConfiguration, "Shop current balance message", "&aYou have $currency_amount $currency_name."); + shopInsufficientFundsMessage = ConfigurationEngine.setString(fileConfiguration, "Shop insufficient funds message", "&cYou don't have enough $currency_name!"); + shopItemPrice = ConfigurationEngine.setString(fileConfiguration, "Shop item cost message", "That item costs &c$item_value $currency_name."); + shopSellMessage = ConfigurationEngine.setString(fileConfiguration, "Shop sell message", "&aYou have sold $item_name &afor $currency_amount $currency_name!"); + shopSaleOthersItems = ConfigurationEngine.setString(fileConfiguration, "Shop sale player items warning", "&cYou can't sell items that are not currently soulbound to you! This includes items from other prestige tiers!"); + shopSaleInstructions = ConfigurationEngine.setString(fileConfiguration, "Shop sale instructions", "&cYou can only sell EliteMobs loot here! (Armor / weapons dropped from elites showing a value on their lore)"); + teleportTimeLeft = ConfigurationEngine.setString(fileConfiguration, "Teleport time left", "&7[EM] Teleporting in &a$time &7seconds..."); + teleportCancelled = ConfigurationEngine.setString(fileConfiguration, "Teleport cancelled", "&7[EM] &cTeleport interrupted!"); + noPendingCommands = ConfigurationEngine.setString(fileConfiguration, "noPendingCommands", "&cYou don't currently have any pending commands!"); + trackMessage = ConfigurationEngine.setString(fileConfiguration, "trackMessage", "Track the $name"); + chestLowRankMessage = ConfigurationEngine.setString(fileConfiguration, "chestLowRankMessage", "&7[EM] &cYour guild rank needs to be at least $rank &cin order to open this chest!"); + chestCooldownMessage = ConfigurationEngine.setString(fileConfiguration, "chestCooldownMessage", "&7[EM] &cYou've already opened this chest recently! Wait $time!"); + insufficientCurrencyForWormholeMessage = ConfigurationEngine.setString(fileConfiguration, "insufficientCurrencyForWormholeMessage", "&8[EliteMobs] &cInsufficient currency! You need $amount to use this com.magmaguy.elitemobs.wormhole!"); + dismissEMMessage = ConfigurationEngine.setString(fileConfiguration, "dismissEMMessage", "&8[EliteMobs] &2/elitemobs &fmenu not working for you? Try &2/elitemobs alt &fto see an alternative version of the menu! &cDon't want to see this message again? &4/em dismiss"); + switchEMStyleMessage = ConfigurationEngine.setString(fileConfiguration, "switchEMStyleMessage", "&8[EliteMobs] &2/elitemobs &fmenu style changed! Check it out!"); + ConfigurationEngine.fileSaverOnlyDefaults(fileConfiguration, file); } diff --git a/src/main/java/com/magmaguy/elitemobs/config/UnusedNodeHandler.java b/src/main/java/com/magmaguy/elitemobs/config/UnusedNodeHandler.java index d239f2545..f08f8338a 100644 --- a/src/main/java/com/magmaguy/elitemobs/config/UnusedNodeHandler.java +++ b/src/main/java/com/magmaguy/elitemobs/config/UnusedNodeHandler.java @@ -2,37 +2,28 @@ import org.bukkit.Bukkit; import org.bukkit.configuration.Configuration; +import org.bukkit.configuration.file.FileConfiguration; public class UnusedNodeHandler { - public static Configuration clearNodes(Configuration configuration) { + private UnusedNodeHandler() { + } - for (String actual : configuration.getKeys(false)) { + public static Configuration clearNodes(FileConfiguration configuration) { + for (String actual : configuration.getKeys(false)) { boolean keyExists = false; - - for (String defaults : configuration.getDefaults().getKeys(true)) { - - if (actual.equals(defaults)) { - + for (String defaults : configuration.getDefaults().getKeys(true)) + if (actual.equals(defaults)) keyExists = true; - } - - } - if (!keyExists) { - configuration.set(actual, null); Bukkit.getLogger().warning(actual); Bukkit.getLogger().info("[EliteMobs] Deleting unused config values."); - } - } - return configuration; - } } diff --git a/src/main/java/com/magmaguy/elitemobs/config/ValidMobsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/ValidMobsConfig.java deleted file mode 100644 index 1bbef23a4..000000000 --- a/src/main/java/com/magmaguy/elitemobs/config/ValidMobsConfig.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.config; - -import org.bukkit.configuration.Configuration; - -public class ValidMobsConfig { - - public static final String CONFIG_NAME = "ValidMobs.yml"; - public static final String ALLOW_AGGRESSIVE_ELITEMOBS = "Allow aggressive EliteMobs"; - public static final String ALLOW_PASSIVE_SUPERMOBS = "Allow Passive SuperMobs"; - public static final String VALID_SUPERMOBS = "Valid Super Mobs."; - public static final String CHICKEN = VALID_SUPERMOBS + "CHICKEN"; - public static final String COW = VALID_SUPERMOBS + "COW"; - public static final String MUSHROOM_COW = VALID_SUPERMOBS + "MUSHROOM_COW"; - public static final String PIG = VALID_SUPERMOBS + "PIG"; - public static final String SHEEP = VALID_SUPERMOBS + "SHEEP"; - public static final String VALID_AGGRESSIVE_ELITEMOBS = "Valid aggressive EliteMobs."; - public static final String BLAZE = VALID_AGGRESSIVE_ELITEMOBS + "BLAZE"; - public static final String CAVE_SPIDER = VALID_AGGRESSIVE_ELITEMOBS + "CAVE_SPIDER"; - public static final String CREEPER = VALID_AGGRESSIVE_ELITEMOBS + "CREEPER"; - public static final String ENDERMAN = VALID_AGGRESSIVE_ELITEMOBS + "ENDERMAN"; - public static final String ENDERMITE = VALID_AGGRESSIVE_ELITEMOBS + "ENDERMITE"; - public static final String HUSK = VALID_AGGRESSIVE_ELITEMOBS + "HUSK"; - public static final String IRON_GOLEM = VALID_AGGRESSIVE_ELITEMOBS + "IRON_GOLEM"; - public static final String PIG_ZOMBIE = VALID_AGGRESSIVE_ELITEMOBS + "PIG_ZOMBIE"; - public static final String POLAR_BEAR = VALID_AGGRESSIVE_ELITEMOBS + "POLAR_BEAR"; - public static final String SILVERFISH = VALID_AGGRESSIVE_ELITEMOBS + "SILVERFISH"; - public static final String STRAY = VALID_AGGRESSIVE_ELITEMOBS + "STRAY"; - public static final String SKELETON = VALID_AGGRESSIVE_ELITEMOBS + "SKELETON"; - public static final String WITHER_SKELETON = VALID_AGGRESSIVE_ELITEMOBS + "WITHER_SKELETON"; - public static final String SPIDER = VALID_AGGRESSIVE_ELITEMOBS + "SPIDER"; - public static final String VEX = VALID_AGGRESSIVE_ELITEMOBS + "VEX"; - public static final String VINDICATOR = VALID_AGGRESSIVE_ELITEMOBS + "VINDICATOR"; - public static final String WITCH = VALID_AGGRESSIVE_ELITEMOBS + "WITCH"; - public static final String ZOMBIE = VALID_AGGRESSIVE_ELITEMOBS + "ZOMBIE"; - CustomConfigLoader customConfigLoader = new CustomConfigLoader(); - private Configuration configuration = customConfigLoader.getCustomConfig(CONFIG_NAME); - - public void initializeConfig() { - - configuration.addDefault(ALLOW_AGGRESSIVE_ELITEMOBS, true); - configuration.addDefault(BLAZE, true); - configuration.addDefault(CAVE_SPIDER, true); - configuration.addDefault(CREEPER, true); - configuration.addDefault(ENDERMAN, true); - configuration.addDefault(ENDERMITE, true); - configuration.addDefault(HUSK, true); - configuration.addDefault(IRON_GOLEM, true); - configuration.addDefault(PIG_ZOMBIE, true); - configuration.addDefault(POLAR_BEAR, true); - configuration.addDefault(SILVERFISH, true); - configuration.addDefault(SKELETON, true); - configuration.addDefault(WITHER_SKELETON, true); - configuration.addDefault(SPIDER, true); - configuration.addDefault(STRAY, true); - configuration.addDefault(VEX, true); - configuration.addDefault(VINDICATOR, true); - configuration.addDefault(WITCH, true); - configuration.addDefault(ZOMBIE, true); - configuration.addDefault(ALLOW_PASSIVE_SUPERMOBS, true); - configuration.addDefault(CHICKEN, true); - configuration.addDefault(COW, true); - configuration.addDefault(MUSHROOM_COW, true); - configuration.addDefault(PIG, true); - configuration.addDefault(SHEEP, true); - - - customConfigLoader.getCustomConfig(CONFIG_NAME).options().copyDefaults(true); - UnusedNodeHandler.clearNodes(configuration); - customConfigLoader.saveDefaultCustomConfig(CONFIG_NAME); - customConfigLoader.saveCustomConfig(CONFIG_NAME); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/config/ValidWorldsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/ValidWorldsConfig.java index b9918237d..04865e4a5 100644 --- a/src/main/java/com/magmaguy/elitemobs/config/ValidWorldsConfig.java +++ b/src/main/java/com/magmaguy/elitemobs/config/ValidWorldsConfig.java @@ -1,43 +1,55 @@ -/* - * 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 . - */ - package com.magmaguy.elitemobs.config; +import lombok.Getter; import org.bukkit.Bukkit; import org.bukkit.World; -import org.bukkit.configuration.Configuration; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.configuration.file.FileConfiguration; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; public class ValidWorldsConfig { + @Getter + private static List validWorlds = new ArrayList<>(); + @Getter + private static List zoneBasedWorlds = new ArrayList<>(); + @Getter + private static List nightmareWorlds = new ArrayList<>(); + @Getter + private static FileConfiguration fileConfiguration; + private static File file; + + private ValidWorldsConfig() { + } - public static final String CONFIG_NAME = "ValidWorlds.yml"; - CustomConfigLoader customConfigLoader = new CustomConfigLoader(); - private Configuration configuration = customConfigLoader.getCustomConfig(CONFIG_NAME); + public static void initializeConfig() { + file = ConfigurationEngine.fileCreator("ValidWorlds.yml"); + fileConfiguration = ConfigurationEngine.fileConfigurationCreator(file); - public void initializeConfig() { + for (World world : Bukkit.getWorlds()) + ConfigurationEngine.setBoolean(fileConfiguration, "Valid worlds." + world.getName(), true); - for (World world : Bukkit.getWorlds()) { + ConfigurationSection validWorldsSection = fileConfiguration.getConfigurationSection("Valid worlds"); - configuration.addDefault("Valid worlds." + world.getName(), true); + for (String key : validWorldsSection.getKeys(false)) + if (validWorldsSection.getBoolean(key)) + validWorlds.add(key); - } + zoneBasedWorlds = ConfigurationEngine.setList(fileConfiguration, "zoneBasedWorlds", new ArrayList()); + nightmareWorlds = ConfigurationEngine.setList(fileConfiguration, "nightmareWorlds", new ArrayList()); + + ConfigurationEngine.fileSaverOnlyDefaults(fileConfiguration, file); + + } - customConfigLoader.getCustomConfig(CONFIG_NAME).options().copyDefaults(true); - UnusedNodeHandler.clearNodes(configuration); - customConfigLoader.saveDefaultCustomConfig(CONFIG_NAME); - customConfigLoader.saveCustomConfig(CONFIG_NAME); + public static void addWorld(String worldName) { + if (fileConfiguration.getKeys(true).contains("Valid worlds." + worldName)) return; + ConfigurationEngine.setBoolean(fileConfiguration, "Valid worlds." + worldName, true); + ConfigurationEngine.fileSaverOnlyDefaults(fileConfiguration, file); + validWorlds.add(worldName); } } diff --git a/src/main/java/com/magmaguy/elitemobs/config/VanillaItemDrop.java b/src/main/java/com/magmaguy/elitemobs/config/VanillaItemDrop.java new file mode 100644 index 000000000..543e0012f --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/VanillaItemDrop.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config; + +import lombok.Getter; +import lombok.Setter; +import org.bukkit.inventory.ItemStack; + +public class VanillaItemDrop { + @Getter + @Setter + private ItemStack itemStack; + @Getter + @Setter + private double chance; + + public VanillaItemDrop(ItemStack itemStack, double chance) { + this.itemStack = itemStack; + this.chance = chance; + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/WormholesConfig.java b/src/main/java/com/magmaguy/elitemobs/config/WormholesConfig.java new file mode 100644 index 000000000..a5d854a6c --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/WormholesConfig.java @@ -0,0 +1,32 @@ +package com.magmaguy.elitemobs.config; + +import lombok.Getter; +import org.bukkit.configuration.file.FileConfiguration; + +import java.io.File; + +public class WormholesConfig { + @Getter + private static String dungeonNotInstalledMessage; + @Getter + private static String defaultPortalMissingMessage; + @Getter + private static boolean reducedParticlesMode; + @Getter + private static boolean noParticlesMode; + + private WormholesConfig() { + } + + public static void initializeConfig() { + File file = ConfigurationEngine.fileCreator("Wormholes.yml"); + FileConfiguration fileConfiguration = ConfigurationEngine.fileConfigurationCreator(file); + + dungeonNotInstalledMessage = ConfigurationEngine.setString(fileConfiguration, "dungeonNotInstalledMessage", "&8[EliteMobs] &cDungeon $dungeonID &cis not installed! This teleport will not work."); + defaultPortalMissingMessage = ConfigurationEngine.setString(fileConfiguration, "defaultPortalMissingMessage", "&8[EliteMobs] &cThis portal doesn't seem to lead anywhere!"); + reducedParticlesMode = ConfigurationEngine.setBoolean(fileConfiguration, "reducedParticlesMode", false); + noParticlesMode = ConfigurationEngine.setBoolean(fileConfiguration, "noParticlesMode", false); + + ConfigurationEngine.fileSaverOnlyDefaults(fileConfiguration, file); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/commands/CommandsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/commands/CommandsConfig.java new file mode 100644 index 000000000..84556f0d9 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/commands/CommandsConfig.java @@ -0,0 +1,46 @@ +package com.magmaguy.elitemobs.config.commands; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.commands.premade.CheckTierConfig; +import com.magmaguy.elitemobs.config.commands.premade.CheckTierOthersConfig; +import org.bukkit.configuration.file.FileConfiguration; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; + +public class CommandsConfig { + + private static final ArrayList commandsConfigFields = new ArrayList<>(Arrays.asList( + new CheckTierConfig(), + new CheckTierOthersConfig() + )); + + private CommandsConfig() { + + } + + public static void initializeConfigs() { + //Checks if the directory doesn't exist + for (CommandsConfigFields commandsConfigFields : commandsConfigFields) + initializeConfiguration(commandsConfigFields); + } + + /** + * Initializes a single instance of a premade configuration using the default values. + * + * @param commandsConfigFields + * @return + */ + private static FileConfiguration initializeConfiguration(CommandsConfigFields commandsConfigFields) { + + File file = ConfigurationEngine.fileCreator("commands", commandsConfigFields.getFileName()); + FileConfiguration fileConfiguration = ConfigurationEngine.fileConfigurationCreator(file); + commandsConfigFields.generateConfigDefaults(fileConfiguration); + ConfigurationEngine.fileSaverOnlyDefaults(fileConfiguration, file); + + return fileConfiguration; + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/commands/CommandsConfigFields.java b/src/main/java/com/magmaguy/elitemobs/config/commands/CommandsConfigFields.java new file mode 100644 index 000000000..246cf12eb --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/commands/CommandsConfigFields.java @@ -0,0 +1,24 @@ +package com.magmaguy.elitemobs.config.commands; + +import org.bukkit.configuration.file.FileConfiguration; + +public class CommandsConfigFields { + + private String fileName; + + public CommandsConfigFields(String fileName) { + this.fileName = fileName + ".yml"; + } + + public CommandsConfigFields(FileConfiguration configuration) { + + } + + public void generateConfigDefaults(FileConfiguration fileConfiguration) { + } + + public String getFileName() { + return fileName; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/commands/premade/CheckTierConfig.java b/src/main/java/com/magmaguy/elitemobs/config/commands/premade/CheckTierConfig.java new file mode 100644 index 000000000..da05674fa --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/commands/premade/CheckTierConfig.java @@ -0,0 +1,21 @@ +package com.magmaguy.elitemobs.config.commands.premade; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.commands.CommandsConfigFields; +import org.bukkit.configuration.file.FileConfiguration; + +public class CheckTierConfig extends CommandsConfigFields { + public static String message1, message2, message3, noPermMessage; + + public CheckTierConfig() { + super("check_tier"); + } + + @Override + public void generateConfigDefaults(FileConfiguration fileConfiguration) { + message1 = ConfigurationEngine.setString(fileConfiguration, "message1", "&7[EM] Your combat tier is $tier"); + message2 = ConfigurationEngine.setString(fileConfiguration, "message2", "&7[EM] Your guild tier bonus is $tier"); + message3 = ConfigurationEngine.setString(fileConfiguration, "message3", "&7[EM] &aYour total threat tier is $tier"); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/commands/premade/CheckTierOthersConfig.java b/src/main/java/com/magmaguy/elitemobs/config/commands/premade/CheckTierOthersConfig.java new file mode 100644 index 000000000..5c4e5c778 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/commands/premade/CheckTierOthersConfig.java @@ -0,0 +1,21 @@ +package com.magmaguy.elitemobs.config.commands.premade; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.commands.CommandsConfigFields; +import org.bukkit.configuration.file.FileConfiguration; + +public class CheckTierOthersConfig extends CommandsConfigFields { + public static String message1, message2, message3, noPermMessage; + + public CheckTierOthersConfig() { + super("check_tier_others"); + } + + @Override + public void generateConfigDefaults(FileConfiguration fileConfiguration) { + message1 = ConfigurationEngine.setString(fileConfiguration, "message1", "&7[EM] $player's combat tier is $tier"); + message2 = ConfigurationEngine.setString(fileConfiguration, "message2", "&7[EM] $player's guild tier bonus is $tier"); + message3 = ConfigurationEngine.setString(fileConfiguration, "message3", "&7[EM] &a$player's total threat tier is $tier"); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customarenas/CustomArenasConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customarenas/CustomArenasConfig.java new file mode 100644 index 000000000..c14a1b966 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customarenas/CustomArenasConfig.java @@ -0,0 +1,30 @@ +package com.magmaguy.elitemobs.config.customarenas; + +import com.magmaguy.elitemobs.config.CustomConfig; +import com.magmaguy.elitemobs.instanced.ArenaInstance; + +import java.util.HashMap; + +public class CustomArenasConfig extends CustomConfig { + + private static HashMap customArenas; + + public CustomArenasConfig() { + super("customarenas", "com.magmaguy.elitemobs.config.customarenas.premade", CustomArenasConfigFields.class); + customArenas = new HashMap<>(); + for (String key : super.getCustomConfigFieldsHashMap().keySet()) + if (super.getCustomConfigFieldsHashMap().get(key).isEnabled()) { + customArenas.put(key, (CustomArenasConfigFields) super.getCustomConfigFieldsHashMap().get(key)); + ArenaInstance.initializeArena((CustomArenasConfigFields) super.getCustomConfigFieldsHashMap().get(key)); + } + } + + public static HashMap getCustomArenas() { + return customArenas; + } + + public static CustomArenasConfigFields getCustomArena(String string) { + return customArenas.get(string); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customarenas/CustomArenasConfigFields.java b/src/main/java/com/magmaguy/elitemobs/config/customarenas/CustomArenasConfigFields.java new file mode 100644 index 000000000..3a22f3f0b --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customarenas/CustomArenasConfigFields.java @@ -0,0 +1,80 @@ +package com.magmaguy.elitemobs.config.customarenas; + +import com.magmaguy.elitemobs.config.CustomConfigFields; +import com.magmaguy.elitemobs.config.CustomConfigFieldsInterface; +import com.magmaguy.elitemobs.items.customloottable.CustomLootTable; +import lombok.Getter; +import lombok.Setter; + +import java.util.ArrayList; +import java.util.List; + +public class CustomArenasConfigFields extends CustomConfigFields implements CustomConfigFieldsInterface { + + @Getter + @Setter + private String arenaName; + @Getter + @Setter + private String corner1; + @Getter + @Setter + private String corner2; + @Getter + @Setter + private String startLocation; + @Getter + @Setter + private String exitLocation; + @Getter + @Setter + private int waveCount; + @Getter + @Setter + private int delayBetweenWaves; + @Getter + @Setter + private List spawnPoints = new ArrayList<>(); + @Getter + @Setter + private List bossList = new ArrayList<>(); + @Getter + @Setter + private List rawArenaRewards = new ArrayList<>(); + @Getter + @Setter + private CustomLootTable arenaRewards; + @Getter + @Setter + private int minimumPlayerCount = 1; + @Getter + @Setter + private int maximumPlayerCount; + @Getter + @Setter + private List arenaMessages = new ArrayList<>(); + + public CustomArenasConfigFields(String filename, boolean isEnabled) { + super(filename, isEnabled); + } + + @Override + public void processConfigFields() { + this.isEnabled = processBoolean("isEnabled", isEnabled, true, true); + this.arenaName = processString("arenaName", arenaName, "Default name", false); + this.corner1 = processString("corner1", corner1, null, false); + this.corner2 = processString("corner2", corner2, null, false); + this.startLocation = processString("startLocation", startLocation, null, false); + this.exitLocation = processString("exitLocation", exitLocation, null, false); + this.waveCount = processInt("waveCount", waveCount, 0, false); + this.delayBetweenWaves = processInt("delayBetweenWaves", delayBetweenWaves, 0, false); + this.spawnPoints = processStringList("spawnPoints", spawnPoints, new ArrayList<>(), false); + this.bossList = processStringList("bossList", bossList, new ArrayList<>(), false); + this.rawArenaRewards = processStringList("rawArenaReward", rawArenaRewards, new ArrayList<>(), false); + arenaRewards = new CustomLootTable(this); + this.minimumPlayerCount = processInt("minimumPlayerCount", minimumPlayerCount, 1, false); + this.maximumPlayerCount = processInt("maximumPlayerCount", maximumPlayerCount, 100, false); + this.arenaMessages = processStringList("arenaMessages", arenaMessages, new ArrayList<>(), false); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customarenas/premade/WoodLeagueArena.java b/src/main/java/com/magmaguy/elitemobs/config/customarenas/premade/WoodLeagueArena.java new file mode 100644 index 000000000..d59d14f51 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customarenas/premade/WoodLeagueArena.java @@ -0,0 +1,793 @@ +package com.magmaguy.elitemobs.config.customarenas.premade; + +import com.magmaguy.elitemobs.config.customarenas.CustomArenasConfigFields; + +import java.util.ArrayList; +import java.util.Arrays; + +public class WoodLeagueArena extends CustomArenasConfigFields { + public WoodLeagueArena() { + super("wood_league", true); + super.setArenaName("Wood League"); + super.setCorner1("em_adventurers_guild,257,69,333,0,0"); + super.setCorner2("em_adventurers_guild,181,91,257,0,0"); + super.setStartLocation("em_adventurers_guild,219.5,70,295.5,0,0"); + super.setExitLocation("em_adventurers_guild,245.5,92,274.5,0,0"); + super.setWaveCount(50); + super.setBossList(Arrays.asList( + "wave=1:spawnPoint=north:boss=wood_league_wave_1_melee.yml", + "wave=1:spawnPoint=north:boss=wood_league_wave_1_melee.yml", + "wave=1:spawnPoint=north:boss=wood_league_wave_1_ranged.yml", + + "wave=2:spawnPoint=north:boss=wood_league_wave_2_melee.yml", + "wave=2:spawnPoint=north:boss=wood_league_wave_2_melee.yml", + "wave=2:spawnPoint=north:boss=wood_league_wave_2_ranged.yml", + "wave=2:spawnPoint=south:boss=wood_league_wave_2_melee.yml", + "wave=2:spawnPoint=south:boss=wood_league_wave_2_melee.yml", + "wave=2:spawnPoint=south:boss=wood_league_wave_2_ranged.yml", + + "wave=3:spawnPoint=north:boss=wood_league_wave_3_melee.yml", + "wave=3:spawnPoint=north:boss=wood_league_wave_3_melee.yml", + "wave=3:spawnPoint=north:boss=wood_league_wave_3_ranged.yml", + "wave=3:spawnPoint=south:boss=wood_league_wave_3_melee.yml", + "wave=3:spawnPoint=south:boss=wood_league_wave_3_melee.yml", + "wave=3:spawnPoint=south:boss=wood_league_wave_3_ranged.yml", + + "wave=4:spawnPoint=north:boss=wood_league_wave_4_melee.yml", + "wave=4:spawnPoint=north:boss=wood_league_wave_4_melee.yml", + "wave=4:spawnPoint=north:boss=wood_league_wave_4_ranged.yml", + "wave=4:spawnPoint=south:boss=wood_league_wave_4_melee.yml", + "wave=4:spawnPoint=south:boss=wood_league_wave_4_melee.yml", + "wave=4:spawnPoint=south:boss=wood_league_wave_4_ranged.yml", + + "wave=5:spawnPoint=center:boss=wood_league_wave_5_miniboss.yml", + + "wave=6:spawnPoint=north:boss=wood_league_wave_6_melee.yml", + "wave=6:spawnPoint=north:boss=wood_league_wave_6_melee.yml", + "wave=6:spawnPoint=north:boss=wood_league_wave_6_ranged.yml", + "wave=6:spawnPoint=south:boss=wood_league_wave_6_melee.yml", + "wave=6:spawnPoint=south:boss=wood_league_wave_6_melee.yml", + "wave=6:spawnPoint=south:boss=wood_league_wave_6_ranged.yml", + "wave=6:spawnPoint=east:boss=wood_league_wave_6_melee.yml", + "wave=6:spawnPoint=east:boss=wood_league_wave_6_melee.yml", + "wave=6:spawnPoint=east:boss=wood_league_wave_6_ranged.yml", + "wave=6:spawnPoint=west:boss=wood_league_wave_6_melee.yml", + "wave=6:spawnPoint=west:boss=wood_league_wave_6_melee.yml", + "wave=6:spawnPoint=west:boss=wood_league_wave_6_ranged.yml", + + "wave=7:spawnPoint=north:boss=wood_league_wave_7_melee.yml", + "wave=7:spawnPoint=north:boss=wood_league_wave_7_melee.yml", + "wave=7:spawnPoint=north:boss=wood_league_wave_7_ranged.yml", + "wave=7:spawnPoint=south:boss=wood_league_wave_7_melee.yml", + "wave=7:spawnPoint=south:boss=wood_league_wave_7_melee.yml", + "wave=7:spawnPoint=south:boss=wood_league_wave_7_ranged.yml", + + "wave=8:spawnPoint=north:boss=wood_league_wave_8_melee.yml", + "wave=8:spawnPoint=north:boss=wood_league_wave_8_melee.yml", + "wave=8:spawnPoint=north:boss=wood_league_wave_8_melee.yml", + "wave=8:spawnPoint=south:boss=wood_league_wave_8_melee.yml", + "wave=8:spawnPoint=south:boss=wood_league_wave_8_melee.yml", + "wave=8:spawnPoint=south:boss=wood_league_wave_8_melee.yml", + + "wave=9:spawnPoint=north:boss=wood_league_wave_9_ranged.yml", + "wave=9:spawnPoint=north:boss=wood_league_wave_9_ranged.yml", + "wave=9:spawnPoint=north:boss=wood_league_wave_9_ranged.yml", + "wave=9:spawnPoint=south:boss=wood_league_wave_9_ranged.yml", + "wave=9:spawnPoint=south:boss=wood_league_wave_9_ranged.yml", + "wave=9:spawnPoint=south:boss=wood_league_wave_9_ranged.yml", + + "wave=10:spawnPoint=center:boss=wood_league_wave_10_boss.yml", + + "wave=11:spawnPoint=north:boss=wood_league_wave_11_melee.yml", + "wave=11:spawnPoint=north:boss=wood_league_wave_11_melee.yml", + "wave=11:spawnPoint=north:boss=wood_league_wave_11_ranged.yml", + "wave=11:spawnPoint=south:boss=wood_league_wave_11_melee.yml", + "wave=11:spawnPoint=south:boss=wood_league_wave_11_melee.yml", + "wave=11:spawnPoint=south:boss=wood_league_wave_11_ranged.yml", + + "wave=12:spawnPoint=north:boss=wood_league_wave_12_melee.yml", + "wave=12:spawnPoint=north:boss=wood_league_wave_12_melee.yml", + "wave=12:spawnPoint=north:boss=wood_league_wave_12_ranged.yml", + "wave=12:spawnPoint=south:boss=wood_league_wave_12_melee.yml", + "wave=12:spawnPoint=south:boss=wood_league_wave_12_melee.yml", + "wave=12:spawnPoint=south:boss=wood_league_wave_12_ranged.yml", + "wave=12:spawnPoint=east:boss=wood_league_wave_12_melee.yml", + "wave=12:spawnPoint=east:boss=wood_league_wave_12_melee.yml", + "wave=12:spawnPoint=east:boss=wood_league_wave_12_ranged.yml", + + "wave=13:spawnPoint=north:boss=wood_league_wave_13_melee.yml", + "wave=13:spawnPoint=north:boss=wood_league_wave_13_melee.yml", + "wave=13:spawnPoint=north:boss=wood_league_wave_13_ranged.yml", + "wave=13:spawnPoint=south:boss=wood_league_wave_13_melee.yml", + "wave=13:spawnPoint=south:boss=wood_league_wave_13_melee.yml", + "wave=13:spawnPoint=south:boss=wood_league_wave_13_ranged.yml", + "wave=13:spawnPoint=east:boss=wood_league_wave_13_melee.yml", + "wave=13:spawnPoint=east:boss=wood_league_wave_13_melee.yml", + "wave=13:spawnPoint=east:boss=wood_league_wave_13_ranged.yml", + + "wave=14:spawnPoint=north:boss=wood_league_wave_14_melee.yml", + "wave=14:spawnPoint=north:boss=wood_league_wave_14_melee.yml", + "wave=14:spawnPoint=north:boss=wood_league_wave_14_ranged.yml", + "wave=14:spawnPoint=south:boss=wood_league_wave_14_melee.yml", + "wave=14:spawnPoint=south:boss=wood_league_wave_14_melee.yml", + "wave=14:spawnPoint=south:boss=wood_league_wave_14_ranged.yml", + "wave=14:spawnPoint=east:boss=wood_league_wave_14_melee.yml", + "wave=14:spawnPoint=east:boss=wood_league_wave_14_melee.yml", + "wave=14:spawnPoint=east:boss=wood_league_wave_14_ranged.yml", + + "wave=15:spawnPoint=center:boss=wood_league_wave_15_miniboss.yml", + + "wave=16:spawnPoint=north:boss=wood_league_wave_16_melee.yml", + "wave=16:spawnPoint=north:boss=wood_league_wave_16_melee.yml", + "wave=16:spawnPoint=north:boss=wood_league_wave_16_ranged.yml", + "wave=16:spawnPoint=south:boss=wood_league_wave_16_melee.yml", + "wave=16:spawnPoint=south:boss=wood_league_wave_16_melee.yml", + "wave=16:spawnPoint=south:boss=wood_league_wave_16_ranged.yml", + "wave=16:spawnPoint=east:boss=wood_league_wave_16_melee.yml", + "wave=16:spawnPoint=east:boss=wood_league_wave_16_melee.yml", + "wave=16:spawnPoint=east:boss=wood_league_wave_16_ranged.yml", + "wave=16:spawnPoint=west:boss=wood_league_wave_16_melee.yml", + "wave=16:spawnPoint=west:boss=wood_league_wave_16_melee.yml", + "wave=16:spawnPoint=west:boss=wood_league_wave_16_ranged.yml", + "wave=16:spawnPoint=northeast:boss=wood_league_wave_16_melee.yml", + "wave=16:spawnPoint=northeast:boss=wood_league_wave_16_melee.yml", + "wave=16:spawnPoint=northeast:boss=wood_league_wave_16_ranged.yml", + + "wave=17:spawnPoint=north:boss=wood_league_wave_17_melee.yml", + "wave=17:spawnPoint=north:boss=wood_league_wave_17_melee.yml", + "wave=17:spawnPoint=north:boss=wood_league_wave_17_ranged.yml", + "wave=17:spawnPoint=south:boss=wood_league_wave_17_melee.yml", + "wave=17:spawnPoint=south:boss=wood_league_wave_17_melee.yml", + "wave=17:spawnPoint=south:boss=wood_league_wave_17_ranged.yml", + "wave=17:spawnPoint=east:boss=wood_league_wave_17_melee.yml", + "wave=17:spawnPoint=east:boss=wood_league_wave_17_melee.yml", + "wave=17:spawnPoint=east:boss=wood_league_wave_17_ranged.yml", + + "wave=18:spawnPoint=north:boss=wood_league_wave_18_melee.yml", + "wave=18:spawnPoint=north:boss=wood_league_wave_18_melee.yml", + "wave=18:spawnPoint=north:boss=wood_league_wave_18_melee.yml", + "wave=18:spawnPoint=south:boss=wood_league_wave_18_melee.yml", + "wave=18:spawnPoint=south:boss=wood_league_wave_18_melee.yml", + "wave=18:spawnPoint=south:boss=wood_league_wave_18_melee.yml", + "wave=18:spawnPoint=east:boss=wood_league_wave_18_melee.yml", + "wave=18:spawnPoint=east:boss=wood_league_wave_18_melee.yml", + "wave=18:spawnPoint=east:boss=wood_league_wave_18_melee.yml", + + "wave=19:spawnPoint=north:boss=wood_league_wave_19_ranged.yml", + "wave=19:spawnPoint=north:boss=wood_league_wave_19_ranged.yml", + "wave=19:spawnPoint=north:boss=wood_league_wave_19_ranged.yml", + "wave=19:spawnPoint=south:boss=wood_league_wave_19_ranged.yml", + "wave=19:spawnPoint=south:boss=wood_league_wave_19_ranged.yml", + "wave=19:spawnPoint=south:boss=wood_league_wave_19_ranged.yml", + "wave=19:spawnPoint=east:boss=wood_league_wave_19_ranged.yml", + "wave=19:spawnPoint=east:boss=wood_league_wave_19_ranged.yml", + "wave=19:spawnPoint=east:boss=wood_league_wave_19_ranged.yml", + + "wave=20:spawnPoint=center:boss=wood_league_wave_20_boss.yml", + + "wave=21:spawnPoint=north:boss=wood_league_wave_21_melee.yml", + "wave=21:spawnPoint=north:boss=wood_league_wave_21_melee.yml", + "wave=21:spawnPoint=north:boss=wood_league_wave_21_ranged.yml", + "wave=21:spawnPoint=south:boss=wood_league_wave_21_melee.yml", + "wave=21:spawnPoint=south:boss=wood_league_wave_21_melee.yml", + "wave=21:spawnPoint=south:boss=wood_league_wave_21_ranged.yml", + "wave=21:spawnPoint=east:boss=wood_league_wave_21_melee.yml", + "wave=21:spawnPoint=east:boss=wood_league_wave_21_melee.yml", + "wave=21:spawnPoint=east:boss=wood_league_wave_21_ranged.yml", + + "wave=22:spawnPoint=north:boss=wood_league_wave_22_melee.yml", + "wave=22:spawnPoint=north:boss=wood_league_wave_22_melee.yml", + "wave=22:spawnPoint=north:boss=wood_league_wave_22_ranged.yml", + "wave=22:spawnPoint=south:boss=wood_league_wave_22_melee.yml", + "wave=22:spawnPoint=south:boss=wood_league_wave_22_melee.yml", + "wave=22:spawnPoint=south:boss=wood_league_wave_22_ranged.yml", + "wave=22:spawnPoint=east:boss=wood_league_wave_22_melee.yml", + "wave=22:spawnPoint=east:boss=wood_league_wave_22_melee.yml", + "wave=22:spawnPoint=east:boss=wood_league_wave_22_ranged.yml", + "wave=22:spawnPoint=west:boss=wood_league_wave_22_melee.yml", + "wave=22:spawnPoint=west:boss=wood_league_wave_22_melee.yml", + "wave=22:spawnPoint=west:boss=wood_league_wave_22_ranged.yml", + + "wave=23:spawnPoint=north:boss=wood_league_wave_23_melee.yml", + "wave=23:spawnPoint=north:boss=wood_league_wave_23_melee.yml", + "wave=23:spawnPoint=north:boss=wood_league_wave_23_ranged.yml", + "wave=23:spawnPoint=south:boss=wood_league_wave_23_melee.yml", + "wave=23:spawnPoint=south:boss=wood_league_wave_23_melee.yml", + "wave=23:spawnPoint=south:boss=wood_league_wave_23_ranged.yml", + "wave=23:spawnPoint=east:boss=wood_league_wave_23_melee.yml", + "wave=23:spawnPoint=east:boss=wood_league_wave_23_melee.yml", + "wave=23:spawnPoint=east:boss=wood_league_wave_23_ranged.yml", + "wave=23:spawnPoint=west:boss=wood_league_wave_23_melee.yml", + "wave=23:spawnPoint=west:boss=wood_league_wave_23_melee.yml", + "wave=23:spawnPoint=west:boss=wood_league_wave_23_ranged.yml", + + "wave=24:spawnPoint=north:boss=wood_league_wave_24_melee.yml", + "wave=24:spawnPoint=north:boss=wood_league_wave_24_melee.yml", + "wave=24:spawnPoint=north:boss=wood_league_wave_24_ranged.yml", + "wave=24:spawnPoint=south:boss=wood_league_wave_24_melee.yml", + "wave=24:spawnPoint=south:boss=wood_league_wave_24_melee.yml", + "wave=24:spawnPoint=south:boss=wood_league_wave_24_ranged.yml", + "wave=24:spawnPoint=east:boss=wood_league_wave_24_melee.yml", + "wave=24:spawnPoint=east:boss=wood_league_wave_24_melee.yml", + "wave=24:spawnPoint=east:boss=wood_league_wave_24_ranged.yml", + "wave=24:spawnPoint=west:boss=wood_league_wave_24_melee.yml", + "wave=24:spawnPoint=west:boss=wood_league_wave_24_melee.yml", + "wave=24:spawnPoint=west:boss=wood_league_wave_24_ranged.yml", + + "wave=25:spawnPoint=center:boss=wood_league_wave_25_miniboss.yml", + + "wave=26:spawnPoint=north:boss=wood_league_wave_26_melee.yml", + "wave=26:spawnPoint=north:boss=wood_league_wave_26_melee.yml", + "wave=26:spawnPoint=north:boss=wood_league_wave_26_ranged.yml", + "wave=26:spawnPoint=south:boss=wood_league_wave_26_melee.yml", + "wave=26:spawnPoint=south:boss=wood_league_wave_26_melee.yml", + "wave=26:spawnPoint=south:boss=wood_league_wave_26_ranged.yml", + "wave=26:spawnPoint=east:boss=wood_league_wave_26_melee.yml", + "wave=26:spawnPoint=east:boss=wood_league_wave_26_melee.yml", + "wave=26:spawnPoint=east:boss=wood_league_wave_26_ranged.yml", + "wave=26:spawnPoint=west:boss=wood_league_wave_26_melee.yml", + "wave=26:spawnPoint=west:boss=wood_league_wave_26_melee.yml", + "wave=26:spawnPoint=west:boss=wood_league_wave_26_ranged.yml", + "wave=26:spawnPoint=northeast:boss=wood_league_wave_26_melee.yml", + "wave=26:spawnPoint=northeast:boss=wood_league_wave_26_melee.yml", + "wave=26:spawnPoint=northeast:boss=wood_league_wave_26_ranged.yml", + "wave=26:spawnPoint=southwest:boss=wood_league_wave_26_melee.yml", + "wave=26:spawnPoint=southwest:boss=wood_league_wave_26_melee.yml", + "wave=26:spawnPoint=southwest:boss=wood_league_wave_26_ranged.yml", + + "wave=27:spawnPoint=north:boss=wood_league_wave_27_melee.yml", + "wave=27:spawnPoint=north:boss=wood_league_wave_27_melee.yml", + "wave=27:spawnPoint=north:boss=wood_league_wave_27_ranged.yml", + "wave=27:spawnPoint=south:boss=wood_league_wave_27_melee.yml", + "wave=27:spawnPoint=south:boss=wood_league_wave_27_melee.yml", + "wave=27:spawnPoint=south:boss=wood_league_wave_27_ranged.yml", + "wave=27:spawnPoint=east:boss=wood_league_wave_27_melee.yml", + "wave=27:spawnPoint=east:boss=wood_league_wave_27_melee.yml", + "wave=27:spawnPoint=east:boss=wood_league_wave_27_ranged.yml", + "wave=27:spawnPoint=west:boss=wood_league_wave_27_melee.yml", + "wave=27:spawnPoint=west:boss=wood_league_wave_27_melee.yml", + "wave=27:spawnPoint=west:boss=wood_league_wave_27_ranged.yml", + + "wave=28:spawnPoint=north:boss=wood_league_wave_28_melee.yml", + "wave=28:spawnPoint=north:boss=wood_league_wave_28_melee.yml", + "wave=28:spawnPoint=north:boss=wood_league_wave_28_melee.yml", + "wave=28:spawnPoint=south:boss=wood_league_wave_28_melee.yml", + "wave=28:spawnPoint=south:boss=wood_league_wave_28_melee.yml", + "wave=28:spawnPoint=south:boss=wood_league_wave_28_melee.yml", + "wave=28:spawnPoint=east:boss=wood_league_wave_28_melee.yml", + "wave=28:spawnPoint=east:boss=wood_league_wave_28_melee.yml", + "wave=28:spawnPoint=east:boss=wood_league_wave_28_melee.yml", + "wave=28:spawnPoint=west:boss=wood_league_wave_28_melee.yml", + "wave=28:spawnPoint=west:boss=wood_league_wave_28_melee.yml", + "wave=28:spawnPoint=west:boss=wood_league_wave_28_melee.yml", + + "wave=29:spawnPoint=north:boss=wood_league_wave_29_ranged.yml", + "wave=29:spawnPoint=north:boss=wood_league_wave_29_ranged.yml", + "wave=29:spawnPoint=north:boss=wood_league_wave_29_ranged.yml", + "wave=29:spawnPoint=south:boss=wood_league_wave_29_ranged.yml", + "wave=29:spawnPoint=south:boss=wood_league_wave_29_ranged.yml", + "wave=29:spawnPoint=south:boss=wood_league_wave_29_ranged.yml", + "wave=29:spawnPoint=east:boss=wood_league_wave_29_ranged.yml", + "wave=29:spawnPoint=east:boss=wood_league_wave_29_ranged.yml", + "wave=29:spawnPoint=east:boss=wood_league_wave_29_ranged.yml", + "wave=29:spawnPoint=west:boss=wood_league_wave_29_ranged.yml", + "wave=29:spawnPoint=west:boss=wood_league_wave_29_ranged.yml", + "wave=29:spawnPoint=west:boss=wood_league_wave_29_ranged.yml", + + "wave=30:spawnPoint=center:boss=wood_league_wave_30_boss.yml", + + "wave=31:spawnPoint=north:boss=wood_league_wave_31_ranged.yml", + "wave=31:spawnPoint=north:boss=wood_league_wave_31_melee.yml", + "wave=31:spawnPoint=north:boss=wood_league_wave_31_melee.yml", + "wave=31:spawnPoint=south:boss=wood_league_wave_31_ranged.yml", + "wave=31:spawnPoint=south:boss=wood_league_wave_31_melee.yml", + "wave=31:spawnPoint=south:boss=wood_league_wave_31_melee.yml", + "wave=31:spawnPoint=east:boss=wood_league_wave_31_ranged.yml", + "wave=31:spawnPoint=east:boss=wood_league_wave_31_melee.yml", + "wave=31:spawnPoint=east:boss=wood_league_wave_31_melee.yml", + "wave=31:spawnPoint=west:boss=wood_league_wave_31_ranged.yml", + "wave=31:spawnPoint=west:boss=wood_league_wave_31_melee.yml", + "wave=31:spawnPoint=west:boss=wood_league_wave_31_melee.yml", + + "wave=32:spawnPoint=north:boss=wood_league_wave_32_ranged.yml", + "wave=32:spawnPoint=north:boss=wood_league_wave_32_melee.yml", + "wave=32:spawnPoint=north:boss=wood_league_wave_32_melee.yml", + "wave=32:spawnPoint=south:boss=wood_league_wave_32_ranged.yml", + "wave=32:spawnPoint=south:boss=wood_league_wave_32_melee.yml", + "wave=32:spawnPoint=south:boss=wood_league_wave_32_melee.yml", + "wave=32:spawnPoint=east:boss=wood_league_wave_32_ranged.yml", + "wave=32:spawnPoint=east:boss=wood_league_wave_32_melee.yml", + "wave=32:spawnPoint=east:boss=wood_league_wave_32_melee.yml", + "wave=32:spawnPoint=west:boss=wood_league_wave_32_ranged.yml", + "wave=32:spawnPoint=west:boss=wood_league_wave_32_melee.yml", + "wave=32:spawnPoint=west:boss=wood_league_wave_32_melee.yml", + "wave=32:spawnPoint=northeast:boss=wood_league_wave_32_ranged.yml", + "wave=32:spawnPoint=northeast:boss=wood_league_wave_32_melee.yml", + "wave=32:spawnPoint=northeast:boss=wood_league_wave_32_melee.yml", + + "wave=33:spawnPoint=north:boss=wood_league_wave_33_ranged.yml", + "wave=33:spawnPoint=north:boss=wood_league_wave_33_melee.yml", + "wave=33:spawnPoint=north:boss=wood_league_wave_33_melee.yml", + "wave=33:spawnPoint=south:boss=wood_league_wave_33_ranged.yml", + "wave=33:spawnPoint=south:boss=wood_league_wave_33_melee.yml", + "wave=33:spawnPoint=south:boss=wood_league_wave_33_melee.yml", + "wave=33:spawnPoint=east:boss=wood_league_wave_33_ranged.yml", + "wave=33:spawnPoint=east:boss=wood_league_wave_33_melee.yml", + "wave=33:spawnPoint=east:boss=wood_league_wave_33_melee.yml", + "wave=33:spawnPoint=west:boss=wood_league_wave_33_ranged.yml", + "wave=33:spawnPoint=west:boss=wood_league_wave_33_melee.yml", + "wave=33:spawnPoint=west:boss=wood_league_wave_33_melee.yml", + "wave=33:spawnPoint=northeast:boss=wood_league_wave_33_ranged.yml", + "wave=33:spawnPoint=northeast:boss=wood_league_wave_33_melee.yml", + "wave=33:spawnPoint=northeast:boss=wood_league_wave_33_melee.yml", + + "wave=34:spawnPoint=north:boss=wood_league_wave_34_ranged.yml", + "wave=34:spawnPoint=north:boss=wood_league_wave_34_melee.yml", + "wave=34:spawnPoint=north:boss=wood_league_wave_34_melee.yml", + "wave=34:spawnPoint=south:boss=wood_league_wave_34_ranged.yml", + "wave=34:spawnPoint=south:boss=wood_league_wave_34_melee.yml", + "wave=34:spawnPoint=south:boss=wood_league_wave_34_melee.yml", + "wave=34:spawnPoint=east:boss=wood_league_wave_34_ranged.yml", + "wave=34:spawnPoint=east:boss=wood_league_wave_34_melee.yml", + "wave=34:spawnPoint=east:boss=wood_league_wave_34_melee.yml", + "wave=34:spawnPoint=west:boss=wood_league_wave_34_ranged.yml", + "wave=34:spawnPoint=west:boss=wood_league_wave_34_melee.yml", + "wave=34:spawnPoint=west:boss=wood_league_wave_34_melee.yml", + "wave=34:spawnPoint=northeast:boss=wood_league_wave_34_ranged.yml", + "wave=34:spawnPoint=northeast:boss=wood_league_wave_34_melee.yml", + "wave=34:spawnPoint=northeast:boss=wood_league_wave_34_melee.yml", + + "wave=35:spawnPoint=center:boss=wood_league_wave_35_miniboss.yml", + + "wave=36:spawnPoint=north:boss=wood_league_wave_36_ranged.yml", + "wave=36:spawnPoint=north:boss=wood_league_wave_36_melee.yml", + "wave=36:spawnPoint=north:boss=wood_league_wave_36_melee.yml", + "wave=36:spawnPoint=south:boss=wood_league_wave_36_ranged.yml", + "wave=36:spawnPoint=south:boss=wood_league_wave_36_melee.yml", + "wave=36:spawnPoint=south:boss=wood_league_wave_36_melee.yml", + "wave=36:spawnPoint=east:boss=wood_league_wave_36_ranged.yml", + "wave=36:spawnPoint=east:boss=wood_league_wave_36_melee.yml", + "wave=36:spawnPoint=east:boss=wood_league_wave_36_melee.yml", + "wave=36:spawnPoint=west:boss=wood_league_wave_36_ranged.yml", + "wave=36:spawnPoint=west:boss=wood_league_wave_36_melee.yml", + "wave=36:spawnPoint=west:boss=wood_league_wave_36_melee.yml", + "wave=36:spawnPoint=northeast:boss=wood_league_wave_36_ranged.yml", + "wave=36:spawnPoint=northeast:boss=wood_league_wave_36_melee.yml", + "wave=36:spawnPoint=northeast:boss=wood_league_wave_36_melee.yml", + "wave=36:spawnPoint=southwest:boss=wood_league_wave_36_ranged.yml", + "wave=36:spawnPoint=southwest:boss=wood_league_wave_36_melee.yml", + "wave=36:spawnPoint=southwest:boss=wood_league_wave_36_melee.yml", + "wave=36:spawnPoint=southeast:boss=wood_league_wave_36_ranged.yml", + "wave=36:spawnPoint=southeast:boss=wood_league_wave_36_melee.yml", + "wave=36:spawnPoint=southeast:boss=wood_league_wave_36_melee.yml", + + "wave=37:spawnPoint=north:boss=wood_league_wave_37_ranged.yml", + "wave=37:spawnPoint=north:boss=wood_league_wave_37_melee.yml", + "wave=37:spawnPoint=north:boss=wood_league_wave_37_melee.yml", + "wave=37:spawnPoint=south:boss=wood_league_wave_37_ranged.yml", + "wave=37:spawnPoint=south:boss=wood_league_wave_37_melee.yml", + "wave=37:spawnPoint=south:boss=wood_league_wave_37_melee.yml", + "wave=37:spawnPoint=east:boss=wood_league_wave_37_ranged.yml", + "wave=37:spawnPoint=east:boss=wood_league_wave_37_melee.yml", + "wave=37:spawnPoint=east:boss=wood_league_wave_37_melee.yml", + "wave=37:spawnPoint=west:boss=wood_league_wave_37_ranged.yml", + "wave=37:spawnPoint=west:boss=wood_league_wave_37_melee.yml", + "wave=37:spawnPoint=west:boss=wood_league_wave_37_melee.yml", + "wave=37:spawnPoint=northeast:boss=wood_league_wave_37_ranged.yml", + "wave=37:spawnPoint=northeast:boss=wood_league_wave_37_melee.yml", + "wave=37:spawnPoint=northeast:boss=wood_league_wave_37_melee.yml", + + "wave=38:spawnPoint=north:boss=wood_league_wave_38_melee.yml", + "wave=38:spawnPoint=north:boss=wood_league_wave_38_melee.yml", + "wave=38:spawnPoint=north:boss=wood_league_wave_38_melee.yml", + "wave=38:spawnPoint=south:boss=wood_league_wave_38_melee.yml", + "wave=38:spawnPoint=south:boss=wood_league_wave_38_melee.yml", + "wave=38:spawnPoint=south:boss=wood_league_wave_38_melee.yml", + "wave=38:spawnPoint=east:boss=wood_league_wave_38_melee.yml", + "wave=38:spawnPoint=east:boss=wood_league_wave_38_melee.yml", + "wave=38:spawnPoint=east:boss=wood_league_wave_38_melee.yml", + "wave=38:spawnPoint=west:boss=wood_league_wave_38_melee.yml", + "wave=38:spawnPoint=west:boss=wood_league_wave_38_melee.yml", + "wave=38:spawnPoint=west:boss=wood_league_wave_38_melee.yml", + "wave=38:spawnPoint=northeast:boss=wood_league_wave_38_melee.yml", + "wave=38:spawnPoint=northeast:boss=wood_league_wave_38_melee.yml", + "wave=38:spawnPoint=northeast:boss=wood_league_wave_38_melee.yml", + + "wave=39:spawnPoint=north:boss=wood_league_wave_39_ranged.yml", + "wave=39:spawnPoint=north:boss=wood_league_wave_39_ranged.yml", + "wave=39:spawnPoint=north:boss=wood_league_wave_39_ranged.yml", + "wave=39:spawnPoint=south:boss=wood_league_wave_39_ranged.yml", + "wave=39:spawnPoint=south:boss=wood_league_wave_39_ranged.yml", + "wave=39:spawnPoint=south:boss=wood_league_wave_39_ranged.yml", + "wave=39:spawnPoint=east:boss=wood_league_wave_39_ranged.yml", + "wave=39:spawnPoint=east:boss=wood_league_wave_39_ranged.yml", + "wave=39:spawnPoint=east:boss=wood_league_wave_39_ranged.yml", + "wave=39:spawnPoint=west:boss=wood_league_wave_39_ranged.yml", + "wave=39:spawnPoint=west:boss=wood_league_wave_39_ranged.yml", + "wave=39:spawnPoint=west:boss=wood_league_wave_39_ranged.yml", + "wave=39:spawnPoint=northeast:boss=wood_league_wave_39_ranged.yml", + "wave=39:spawnPoint=northeast:boss=wood_league_wave_39_ranged.yml", + "wave=39:spawnPoint=northeast:boss=wood_league_wave_39_ranged.yml", + + "wave=40:spawnPoint=center:boss=wood_league_wave_40_boss.yml", + + "wave=41:spawnPoint=north:boss=wood_league_wave_41_ranged.yml", + "wave=41:spawnPoint=north:boss=wood_league_wave_41_melee.yml", + "wave=41:spawnPoint=north:boss=wood_league_wave_41_melee.yml", + "wave=41:spawnPoint=north:boss=wood_league_wave_41_healer.yml", + "wave=41:spawnPoint=south:boss=wood_league_wave_41_ranged.yml", + "wave=41:spawnPoint=south:boss=wood_league_wave_41_melee.yml", + "wave=41:spawnPoint=south:boss=wood_league_wave_41_melee.yml", + "wave=41:spawnPoint=south:boss=wood_league_wave_41_healer.yml", + "wave=41:spawnPoint=east:boss=wood_league_wave_41_ranged.yml", + "wave=41:spawnPoint=east:boss=wood_league_wave_41_melee.yml", + "wave=41:spawnPoint=east:boss=wood_league_wave_41_melee.yml", + "wave=41:spawnPoint=east:boss=wood_league_wave_41_healer.yml", + "wave=41:spawnPoint=west:boss=wood_league_wave_41_ranged.yml", + "wave=41:spawnPoint=west:boss=wood_league_wave_41_melee.yml", + "wave=41:spawnPoint=west:boss=wood_league_wave_41_melee.yml", + "wave=41:spawnPoint=west:boss=wood_league_wave_41_healer.yml", + "wave=41:spawnPoint=northeast:boss=wood_league_wave_41_ranged.yml", + "wave=41:spawnPoint=northeast:boss=wood_league_wave_41_melee.yml", + "wave=41:spawnPoint=northeast:boss=wood_league_wave_41_melee.yml", + "wave=41:spawnPoint=northeast:boss=wood_league_wave_41_healer.yml", + + "wave=42:spawnPoint=north:boss=wood_league_wave_42_ranged.yml", + "wave=42:spawnPoint=north:boss=wood_league_wave_42_melee.yml", + "wave=42:spawnPoint=north:boss=wood_league_wave_42_melee.yml", + "wave=42:spawnPoint=north:boss=wood_league_wave_42_healer.yml", + "wave=42:spawnPoint=south:boss=wood_league_wave_42_ranged.yml", + "wave=42:spawnPoint=south:boss=wood_league_wave_42_melee.yml", + "wave=42:spawnPoint=south:boss=wood_league_wave_42_melee.yml", + "wave=42:spawnPoint=south:boss=wood_league_wave_42_healer.yml", + "wave=42:spawnPoint=east:boss=wood_league_wave_42_ranged.yml", + "wave=42:spawnPoint=east:boss=wood_league_wave_42_melee.yml", + "wave=42:spawnPoint=east:boss=wood_league_wave_42_melee.yml", + "wave=42:spawnPoint=east:boss=wood_league_wave_42_healer.yml", + "wave=42:spawnPoint=west:boss=wood_league_wave_42_ranged.yml", + "wave=42:spawnPoint=west:boss=wood_league_wave_42_melee.yml", + "wave=42:spawnPoint=west:boss=wood_league_wave_42_melee.yml", + "wave=42:spawnPoint=west:boss=wood_league_wave_42_healer.yml", + "wave=42:spawnPoint=northeast:boss=wood_league_wave_42_ranged.yml", + "wave=42:spawnPoint=northeast:boss=wood_league_wave_42_melee.yml", + "wave=42:spawnPoint=northeast:boss=wood_league_wave_42_melee.yml", + "wave=42:spawnPoint=northeast:boss=wood_league_wave_42_healer.yml", + "wave=42:spawnPoint=southwest:boss=wood_league_wave_42_ranged.yml", + "wave=42:spawnPoint=southwest:boss=wood_league_wave_42_melee.yml", + "wave=42:spawnPoint=southwest:boss=wood_league_wave_42_melee.yml", + "wave=42:spawnPoint=southwest:boss=wood_league_wave_42_healer.yml", + + "wave=43:spawnPoint=north:boss=wood_league_wave_43_ranged.yml", + "wave=43:spawnPoint=north:boss=wood_league_wave_43_melee.yml", + "wave=43:spawnPoint=north:boss=wood_league_wave_43_melee.yml", + "wave=43:spawnPoint=north:boss=wood_league_wave_43_healer.yml", + "wave=43:spawnPoint=south:boss=wood_league_wave_43_ranged.yml", + "wave=43:spawnPoint=south:boss=wood_league_wave_43_melee.yml", + "wave=43:spawnPoint=south:boss=wood_league_wave_43_melee.yml", + "wave=43:spawnPoint=south:boss=wood_league_wave_43_healer.yml", + "wave=43:spawnPoint=east:boss=wood_league_wave_43_ranged.yml", + "wave=43:spawnPoint=east:boss=wood_league_wave_43_melee.yml", + "wave=43:spawnPoint=east:boss=wood_league_wave_43_melee.yml", + "wave=43:spawnPoint=east:boss=wood_league_wave_43_healer.yml", + "wave=43:spawnPoint=west:boss=wood_league_wave_43_ranged.yml", + "wave=43:spawnPoint=west:boss=wood_league_wave_43_melee.yml", + "wave=43:spawnPoint=west:boss=wood_league_wave_43_melee.yml", + "wave=43:spawnPoint=west:boss=wood_league_wave_43_healer.yml", + "wave=43:spawnPoint=northeast:boss=wood_league_wave_43_ranged.yml", + "wave=43:spawnPoint=northeast:boss=wood_league_wave_43_melee.yml", + "wave=43:spawnPoint=northeast:boss=wood_league_wave_43_melee.yml", + "wave=43:spawnPoint=northeast:boss=wood_league_wave_43_healer.yml", + "wave=43:spawnPoint=southwest:boss=wood_league_wave_43_ranged.yml", + "wave=43:spawnPoint=southwest:boss=wood_league_wave_43_melee.yml", + "wave=43:spawnPoint=southwest:boss=wood_league_wave_43_melee.yml", + "wave=43:spawnPoint=southwest:boss=wood_league_wave_43_healer.yml", + + "wave=44:spawnPoint=north:boss=wood_league_wave_44_ranged.yml", + "wave=44:spawnPoint=north:boss=wood_league_wave_44_melee.yml", + "wave=44:spawnPoint=north:boss=wood_league_wave_44_melee.yml", + "wave=44:spawnPoint=north:boss=wood_league_wave_44_healer.yml", + "wave=44:spawnPoint=south:boss=wood_league_wave_44_ranged.yml", + "wave=44:spawnPoint=south:boss=wood_league_wave_44_melee.yml", + "wave=44:spawnPoint=south:boss=wood_league_wave_44_melee.yml", + "wave=44:spawnPoint=south:boss=wood_league_wave_44_healer.yml", + "wave=44:spawnPoint=east:boss=wood_league_wave_44_ranged.yml", + "wave=44:spawnPoint=east:boss=wood_league_wave_44_melee.yml", + "wave=44:spawnPoint=east:boss=wood_league_wave_44_melee.yml", + "wave=44:spawnPoint=east:boss=wood_league_wave_44_healer.yml", + "wave=44:spawnPoint=west:boss=wood_league_wave_44_ranged.yml", + "wave=44:spawnPoint=west:boss=wood_league_wave_44_melee.yml", + "wave=44:spawnPoint=west:boss=wood_league_wave_44_melee.yml", + "wave=44:spawnPoint=west:boss=wood_league_wave_44_healer.yml", + "wave=44:spawnPoint=northeast:boss=wood_league_wave_44_ranged.yml", + "wave=44:spawnPoint=northeast:boss=wood_league_wave_44_melee.yml", + "wave=44:spawnPoint=northeast:boss=wood_league_wave_44_melee.yml", + "wave=44:spawnPoint=northeast:boss=wood_league_wave_44_healer.yml", + "wave=44:spawnPoint=southwest:boss=wood_league_wave_44_ranged.yml", + "wave=44:spawnPoint=southwest:boss=wood_league_wave_44_melee.yml", + "wave=44:spawnPoint=southwest:boss=wood_league_wave_44_melee.yml", + "wave=44:spawnPoint=southwest:boss=wood_league_wave_44_healer.yml", + + "wave=45:spawnPoint=center:boss=wood_league_wave_45_miniboss.yml", + + "wave=46:spawnPoint=north:boss=wood_league_wave_46_ranged.yml", + "wave=46:spawnPoint=north:boss=wood_league_wave_46_melee.yml", + "wave=46:spawnPoint=north:boss=wood_league_wave_46_melee.yml", + "wave=46:spawnPoint=north:boss=wood_league_wave_46_healer.yml", + "wave=46:spawnPoint=south:boss=wood_league_wave_46_ranged.yml", + "wave=46:spawnPoint=south:boss=wood_league_wave_46_melee.yml", + "wave=46:spawnPoint=south:boss=wood_league_wave_46_melee.yml", + "wave=46:spawnPoint=south:boss=wood_league_wave_46_healer.yml", + "wave=46:spawnPoint=east:boss=wood_league_wave_46_ranged.yml", + "wave=46:spawnPoint=east:boss=wood_league_wave_46_melee.yml", + "wave=46:spawnPoint=east:boss=wood_league_wave_46_melee.yml", + "wave=46:spawnPoint=east:boss=wood_league_wave_46_healer.yml", + "wave=46:spawnPoint=west:boss=wood_league_wave_46_ranged.yml", + "wave=46:spawnPoint=west:boss=wood_league_wave_46_melee.yml", + "wave=46:spawnPoint=west:boss=wood_league_wave_46_melee.yml", + "wave=46:spawnPoint=west:boss=wood_league_wave_46_healer.yml", + "wave=46:spawnPoint=northeast:boss=wood_league_wave_46_ranged.yml", + "wave=46:spawnPoint=northeast:boss=wood_league_wave_46_melee.yml", + "wave=46:spawnPoint=northeast:boss=wood_league_wave_46_melee.yml", + "wave=46:spawnPoint=northeast:boss=wood_league_wave_46_healer.yml", + "wave=46:spawnPoint=southwest:boss=wood_league_wave_46_ranged.yml", + "wave=46:spawnPoint=southwest:boss=wood_league_wave_46_melee.yml", + "wave=46:spawnPoint=southwest:boss=wood_league_wave_46_melee.yml", + "wave=46:spawnPoint=southwest:boss=wood_league_wave_46_healer.yml", + "wave=46:spawnPoint=northwest:boss=wood_league_wave_46_ranged.yml", + "wave=46:spawnPoint=northwest:boss=wood_league_wave_46_melee.yml", + "wave=46:spawnPoint=northwest:boss=wood_league_wave_46_melee.yml", + "wave=46:spawnPoint=northwest:boss=wood_league_wave_46_healer.yml", + "wave=46:spawnPoint=southeast:boss=wood_league_wave_46_ranged.yml", + "wave=46:spawnPoint=southeast:boss=wood_league_wave_46_melee.yml", + "wave=46:spawnPoint=southeast:boss=wood_league_wave_46_melee.yml", + "wave=46:spawnPoint=southeast:boss=wood_league_wave_46_healer.yml", + + "wave=47:spawnPoint=north:boss=wood_league_wave_47_ranged.yml", + "wave=47:spawnPoint=north:boss=wood_league_wave_47_melee.yml", + "wave=47:spawnPoint=north:boss=wood_league_wave_47_melee.yml", + "wave=47:spawnPoint=north:boss=wood_league_wave_47_healer.yml", + "wave=47:spawnPoint=south:boss=wood_league_wave_47_ranged.yml", + "wave=47:spawnPoint=south:boss=wood_league_wave_47_melee.yml", + "wave=47:spawnPoint=south:boss=wood_league_wave_47_melee.yml", + "wave=47:spawnPoint=south:boss=wood_league_wave_47_healer.yml", + "wave=47:spawnPoint=east:boss=wood_league_wave_47_ranged.yml", + "wave=47:spawnPoint=east:boss=wood_league_wave_47_melee.yml", + "wave=47:spawnPoint=east:boss=wood_league_wave_47_melee.yml", + "wave=47:spawnPoint=east:boss=wood_league_wave_47_healer.yml", + "wave=47:spawnPoint=west:boss=wood_league_wave_47_ranged.yml", + "wave=47:spawnPoint=west:boss=wood_league_wave_47_melee.yml", + "wave=47:spawnPoint=west:boss=wood_league_wave_47_melee.yml", + "wave=47:spawnPoint=west:boss=wood_league_wave_47_healer.yml", + "wave=47:spawnPoint=northeast:boss=wood_league_wave_47_ranged.yml", + "wave=47:spawnPoint=northeast:boss=wood_league_wave_47_melee.yml", + "wave=47:spawnPoint=northeast:boss=wood_league_wave_47_melee.yml", + "wave=47:spawnPoint=northeast:boss=wood_league_wave_47_healer.yml", + "wave=47:spawnPoint=southwest:boss=wood_league_wave_47_ranged.yml", + "wave=47:spawnPoint=southwest:boss=wood_league_wave_47_melee.yml", + "wave=47:spawnPoint=southwest:boss=wood_league_wave_47_melee.yml", + "wave=47:spawnPoint=southwest:boss=wood_league_wave_47_healer.yml", + + "wave=48:spawnPoint=north:boss=wood_league_wave_48_melee.yml", + "wave=48:spawnPoint=north:boss=wood_league_wave_48_melee.yml", + "wave=48:spawnPoint=north:boss=wood_league_wave_48_melee.yml", + "wave=48:spawnPoint=north:boss=wood_league_wave_48_healer.yml", + "wave=48:spawnPoint=south:boss=wood_league_wave_48_melee.yml", + "wave=48:spawnPoint=south:boss=wood_league_wave_48_melee.yml", + "wave=48:spawnPoint=south:boss=wood_league_wave_48_melee.yml", + "wave=48:spawnPoint=south:boss=wood_league_wave_48_healer.yml", + "wave=48:spawnPoint=east:boss=wood_league_wave_48_melee.yml", + "wave=48:spawnPoint=east:boss=wood_league_wave_48_melee.yml", + "wave=48:spawnPoint=east:boss=wood_league_wave_48_melee.yml", + "wave=48:spawnPoint=east:boss=wood_league_wave_48_healer.yml", + "wave=48:spawnPoint=west:boss=wood_league_wave_48_melee.yml", + "wave=48:spawnPoint=west:boss=wood_league_wave_48_melee.yml", + "wave=48:spawnPoint=west:boss=wood_league_wave_48_melee.yml", + "wave=48:spawnPoint=west:boss=wood_league_wave_48_healer.yml", + "wave=48:spawnPoint=northeast:boss=wood_league_wave_48_melee.yml", + "wave=48:spawnPoint=northeast:boss=wood_league_wave_48_melee.yml", + "wave=48:spawnPoint=northeast:boss=wood_league_wave_48_melee.yml", + "wave=48:spawnPoint=northeast:boss=wood_league_wave_48_healer.yml", + "wave=48:spawnPoint=southwest:boss=wood_league_wave_48_melee.yml", + "wave=48:spawnPoint=southwest:boss=wood_league_wave_48_melee.yml", + "wave=48:spawnPoint=southwest:boss=wood_league_wave_48_melee.yml", + "wave=48:spawnPoint=southwest:boss=wood_league_wave_48_healer.yml", + + "wave=49:spawnPoint=north:boss=wood_league_wave_49_ranged.yml", + "wave=49:spawnPoint=north:boss=wood_league_wave_49_ranged.yml", + "wave=49:spawnPoint=north:boss=wood_league_wave_49_ranged.yml", + "wave=49:spawnPoint=north:boss=wood_league_wave_49_healer.yml", + "wave=49:spawnPoint=south:boss=wood_league_wave_49_ranged.yml", + "wave=49:spawnPoint=south:boss=wood_league_wave_49_ranged.yml", + "wave=49:spawnPoint=south:boss=wood_league_wave_49_ranged.yml", + "wave=49:spawnPoint=south:boss=wood_league_wave_49_healer.yml", + "wave=49:spawnPoint=east:boss=wood_league_wave_49_ranged.yml", + "wave=49:spawnPoint=east:boss=wood_league_wave_49_ranged.yml", + "wave=49:spawnPoint=east:boss=wood_league_wave_49_ranged.yml", + "wave=49:spawnPoint=east:boss=wood_league_wave_49_healer.yml", + "wave=49:spawnPoint=west:boss=wood_league_wave_49_ranged.yml", + "wave=49:spawnPoint=west:boss=wood_league_wave_49_ranged.yml", + "wave=49:spawnPoint=west:boss=wood_league_wave_49_ranged.yml", + "wave=49:spawnPoint=west:boss=wood_league_wave_49_healer.yml", + "wave=49:spawnPoint=northeast:boss=wood_league_wave_49_ranged.yml", + "wave=49:spawnPoint=northeast:boss=wood_league_wave_49_ranged.yml", + "wave=49:spawnPoint=northeast:boss=wood_league_wave_49_ranged.yml", + "wave=49:spawnPoint=northeast:boss=wood_league_wave_49_healer.yml", + "wave=49:spawnPoint=southwest:boss=wood_league_wave_49_ranged.yml", + "wave=49:spawnPoint=southwest:boss=wood_league_wave_49_ranged.yml", + "wave=49:spawnPoint=southwest:boss=wood_league_wave_49_ranged.yml", + "wave=49:spawnPoint=southwest:boss=wood_league_wave_49_healer.yml", + + "wave=50:spawnPoint=center:boss=wood_league_wave_50_boss.yml" + )); + super.setSpawnPoints(Arrays.asList( + "name=north:location=em_adventurers_guild,219.5,71,273.5", + "name=south:location=em_adventurers_guild,219.5,71,316.5", + "name=west:location=em_adventurers_guild,197.5,71,295.5", + "name=east:location=em_adventurers_guild,240.5,71,295.5", + "name=center:location=em_adventurers_guild,219.5,71,295.5", + "name=northeast:location=em_adventurers_guild,233.5,71,281.5", + "name=southeast:location=em_adventurers_guild,233.5,71,309.5", + "name=northwest:location=em_adventurers_guild,205.5,71,281.5", + "name=southwest:location=em_adventurers_guild,205.5,71,309.5")); + + super.setDelayBetweenWaves(5); + super.setRawArenaRewards(Arrays.asList( + "upgrade_item:level=10:amount=1-2:ignorePlayerLevel=true:chance=1:wave=10", + "upgrade_item:level=20:amount=1-2:ignorePlayerLevel=true:chance=1:wave=20", + "upgrade_item:level=30:amount=1-2:ignorePlayerLevel=true:chance=1:wave=30", + "upgrade_item:level=40:amount=1-2:ignorePlayerLevel=true:chance=1:wave=40", + "upgrade_item:level=50:amount=1-2:ignorePlayerLevel=true:chance=1:wave=50", + + "scrap:level=5:amount=5-15:ignorePlayerLevel=true:chance=1:wave=5", + "scrap:level=10:amount=5-15:ignorePlayerLevel=true:chance=1:wave=10", + "scrap:level=15:amount=5-15:ignorePlayerLevel=true:chance=1:wave=15", + "scrap:level=20:amount=5-15:ignorePlayerLevel=true:chance=1:wave=20", + "scrap:level=25:amount=5-15:ignorePlayerLevel=true:chance=1:wave=25", + "scrap:level=30:amount=5-15:ignorePlayerLevel=true:chance=1:wave=30", + "scrap:level=35:amount=5-15:ignorePlayerLevel=true:chance=1:wave=35", + "scrap:level=40:amount=5-15:ignorePlayerLevel=true:chance=1:wave=40", + "scrap:level=45:amount=5-15:ignorePlayerLevel=true:chance=1:wave=45", + "scrap:level=50:amount=5-15:ignorePlayerLevel=true:chance=1:wave=50", + + "currencyAmount=3:wave=1", + "currencyAmount=15:wave=2", + "currencyAmount=30:wave=3", + "currencyAmount=45:wave=4", + "currencyAmount=60:wave=5", + "currencyAmount=75:wave=6", + "currencyAmount=90:wave=7", + "currencyAmount=105:wave=8", + "currencyAmount=120:wave=9", + "currencyAmount=135:wave=10", + "currencyAmount=150:wave=11", + "currencyAmount=165:wave=12", + "currencyAmount=180:wave=13", + "currencyAmount=195:wave=14", + "currencyAmount=210:wave=15", + "currencyAmount=225:wave=16", + "currencyAmount=240:wave=17", + "currencyAmount=255:wave=18", + "currencyAmount=270:wave=19", + "currencyAmount=285:wave=20", + "currencyAmount=300:wave=21", + "currencyAmount=315:wave=22", + "currencyAmount=330:wave=23", + "currencyAmount=345:wave=24", + "currencyAmount=360:wave=25", + "currencyAmount=375:wave=26", + "currencyAmount=390:wave=27", + "currencyAmount=405:wave=28", + "currencyAmount=420:wave=29", + "currencyAmount=435:wave=30", + "currencyAmount=450:wave=31", + "currencyAmount=465:wave=32", + "currencyAmount=480:wave=33", + "currencyAmount=495:wave=34", + "currencyAmount=510:wave=35", + "currencyAmount=525:wave=36", + "currencyAmount=540:wave=37", + "currencyAmount=555:wave=38", + "currencyAmount=570:wave=39", + "currencyAmount=585:wave=40", + "currencyAmount=600:wave=41", + "currencyAmount=615:wave=42", + "currencyAmount=630:wave=43", + "currencyAmount=645:wave=44", + "currencyAmount=660:wave=45", + "currencyAmount=675:wave=46", + "currencyAmount=690:wave=47", + "currencyAmount=705:wave=48", + "currencyAmount=720:wave=49", + "currencyAmount=800:wave=50", + + "level=10:filename=summon_merchant_scroll.yml:wave=10", + + "filename=invictus_sword.yml:itemlevel=50:wave=50", + "filename=invictus_helmet.yml:itemlevel=50:wave=50", + "filename=invictus_chestplate.yml:itemlevel=50:wave=50", + "filename=invictus_leggings.yml:itemlevel=50:wave=50", + "filename=invictus_boots.yml:itemlevel=50:wave=50", + "filename=invictus_pickaxe.yml:itemlevel=50:wave=50:chance=0.2", + "filename=invictus_shovel.yml:itemlevel=50:wave=50:chance=0.2", + + "filename=challengers_sword.yml:itemlevel=40:wave=40", + "filename=challengers_helmet.yml:itemlevel=40:wave=40", + "filename=challengers_chestplate.yml:itemlevel=40:wave=40", + "filename=challengers_leggings.yml:itemlevel=40:wave=40", + "filename=challengers_boots.yml:itemlevel=40:wave=40", + + "filename=veterans_sword.yml:itemlevel=30:wave=30", + "filename=veterans_helmet.yml:itemlevel=30:wave=30", + "filename=veterans_chestplate.yml:itemlevel=30:wave=30", + "filename=veterans_leggings.yml:itemlevel=30:wave=30", + "filename=veterans_boots.yml:itemlevel=30:wave=30", + + "filename=grunts_sword.yml:itemlevel=20:wave=20", + "filename=grunts_helmet.yml:itemlevel=20:wave=20", + "filename=grunts_chestplate.yml:itemlevel=20:wave=20", + "filename=grunts_leggings.yml:itemlevel=20:wave=20", + "filename=grunts_boots.yml:itemlevel=20:wave=20", + + "filename=novices_sword.yml:itemlevel=10:wave=10", + "filename=novices_helmet.yml:itemlevel=10:wave=10", + "filename=novices_chestplate.yml:itemlevel=10:wave=10", + "filename=novices_leggings.yml:itemlevel=10:wave=10", + "filename=novices_boots.yml:itemlevel=10:wave=10" + + )); + super.setArenaMessages(new ArrayList<>(Arrays.asList( + "wave=1:message=&8[Gladius] &fToday's main event! A legendary fighter came all the way to the arena to test his might against the toughest monsters from all the land! But before that, here's a rookie fighting some zombies.", + "wave=2:message=&8[Gladius] &fWould you look at that - they know how to flail their arms! That was just the warmup. Let's start putting on some pressure!", + "wave=3:message=&8[Gladius] &fSo you think you know how to fight? Well this wave will turn on the &cheat&f! Ha ha ha ha ha!", + "wave=4:message=&8[Gladius] &fAlright, I guess they can take the heat. Strap in, ladies and gentlemen! We might be in for a show!", + "wave=5:message=&8[Gladius] &fI found this &cweird creature &foutside, and I thought putting it in the arena would be funny!", + "wave=6:message=&8[Gladius] &fSeems like you can handle small groups of enemies just fine. Let's see how you do against a &cmild swarm&f!", + "wave=7:message=&8[Gladius] &fSo you truly believe you stand a chance in the arena? We shall see...", + "wave=8:message=&8[Gladius] &fNot bad, but what if every enemy is a &cmelee &fenemy?", + "wave=9:message=&8[Gladius] &fNice, nice, but what if they're all &cranged &finstead?", + "wave=10:message=&8[Gladius] &fCareful now, a &cbad doggo &fseems to have wandered into the arena! Where did it even come from?", + "wave=11:message=&8[Gladius] &fAlright folks we got animal control to deal with the bad doggos, we're back in business!", + "wave=12:message=&8[Gladius] &fIt seems like the audience is clamoring for &cmore&f! Well, let's give it to them!", + "wave=13:message=&8[Gladius] &fWhat's this? The arena custodians have elected to liven things up by coating the creatures with &2poison&f! Sounds a bit ironic if you ask me...", + "wave=14:message=&8[Gladius] &fWell that was... boring! Whoever gave those guys poison is fired! Come up with something better next time!", + "wave=15:message=&8[Gladius] &fAnd here we have this year's prize-winning &4hog&f! It got first place for ugliness and meanness! Everyone give a round of applause for &4Mr. Oinkers&f!", + "wave=16:message=&8[Gladius] &fMr. Oinkers is now bacon! Here come &cMr. Oinkers' fans&f, flooding the arena to get their revenge!", + "wave=17:message=&8[Gladius] &fOur arena challenger seems to think they have a shot at victory! But can they handle even &cmore powerful &ffoes?", + "wave=18:message=&8[Gladius] &fThe &cfencing club &fand the &carchery club &fare having a contest! Let's see which group can take down the challenger!", + "wave=19:message=&8[Gladius] &fThe fencing club has been has been beat into submission. Let's see what the &carchery club&f has for us!", + "wave=20:message=&8[Gladius] &fThe archery club also missed the mark! It seems like our challenger has begun attracting the attention of some of our top gladiators! Introducing &2Zoltan, the Pride of the Zombies&f!", + "wave=21:message=&8[Gladius] &fUnbelievable! Zoltan has been lobotomized! Do we have a potential new champion on our hands?", + "wave=22:message=&8[Gladius] &fSpectators are starting to place their bets! How far can today's contestant go?", + "wave=23:message=&8[Gladius] &fDon't let your attention &8wither &faway, this wave's enemies all have &cwithering attacks&f!", + "wave=24:message=&8[Gladius] &fWe're seeing some of the biggest names in arena history emerge to put an end to this challenger's winning streak! Stay tuned!", + "wave=25:message=&8[Gladius] &fHere comes &bAgdluak&f, the archer from the Great North! Beware of its &bfrost&f!", + "wave=26:message=&8[Gladius] &fThat was a pretty cool fight! I am &cswarming &fwith excitement to see what's next!", + "wave=27:message=&8[Gladius] &fThe arena necromancers are putting their latest creations to the test! &cZombies immune to arrows, skeletons that freeze their opponents &f- what will they think of next!?", + "wave=28:message=&8[Gladius] &fIt's time to show off those &cfencing &fskills! Remember, it's all about the legwork!", + "wave=29:message=&8[Gladius] &fAnd now, let's have some &ctarget practice&f! The target is the challenger!", + "wave=30:message=&8[Gladius] &fA true arena champion approaches! The &2Southern Viper &fseeks to use his trademark &cthousand venoms&f to consign foes to an agonizing death!", + "wave=31:message=&8[Gladius] &fThe Southern Viper has fallen! The crowd goes wild! What a day, ladies and gentlemen! What a day!", + "wave=32:message=&8[Gladius] &fI have been told that the arena custodians are done messing around and are staring to let loose! Can our challenger survive this?", + "wave=33:message=&8[Gladius] &fSeems like some enemies got their hands on some of Southern Viper's &cpoisons&f! You do not want to get hit by those, ladies and gentlemen!", + "wave=34:message=&8[Gladius] &fBobby, make sure you put 1,000 Elite Coins on these contestants dying for me - no, no, 1,000 Elite Coins - wait was this thing on? I mean, onwards to the next wave!", + "wave=35:message=&8[Gladius] &fLadies and gentlemen, what a rare treat! The &aWood League Jester &fhas taken the stage! What delightful &ctricks &fdoes he have for us today?", + "wave=36:message=&8[Gladius] &fWhat a lovely show ladies and gentlemen, give it up for &aThe Jester&f!", + "wave=37:message=&8[Gladius] &fBobby, how is my bet doing? What do you mean 10,000 Elite Coins?!, I told you to put 1,000 on there! Uh, pump them, &cpump the powers up&f!", + "wave=38:message=&8[Gladius] &fBobby you're killing me here! Uh, dump some &cswordsmen &fout there, I need to deal with something real quick...", + "wave=39:message=&8[Gladius] &fWhat do you mean no refunds? I didn't even want to - ahem, I mean, a legion of &carchers &fhave come from afar to show off their skills!", + "wave=40:message=&8[Gladius] &fLadies and gentlemen, as an act of impartial, honest showmanship, I have invited the strongest fighter I can summon! Meet &4Crucios, the Bearer of Curses&f!", + "wave=41:message=&8[Gladius] &fCrucios has been defeated!? What has the world come to?", + "wave=42:message=&8[Gladius] &fA wealthy (for now) patron has decided to provide free healthcare to arena enemies! Will they do better with &2healing&f?", + "wave=43:message=&8[Gladius] &f&cWither&f, &cpoison, &cfire&f - throw in everything you have! Do you even know how much is on the line!?", + "wave=44:message=&8[Gladius] &fThis is clearly not working. Give me a moment to think of something...", + "wave=45:message=&8[Gladius] &fHere is one of the top gladiators of the Wood League Arena! &cThousand Blades &fapproaches once again with his &cinnumerable projectiles&f! He better win!", + "wave=46:message=&8[Gladius] &fThousand Blades has been broken! It just seems like you can't get competent gladiators these days! That's fine, you'll see! You'll all see! &cRelease the horde!", + "wave=47:message=&8[Gladius] &fThey're still standing! Throw in &cmore powers&f! Throw in all of the powers!", + "wave=48:message=&8[Gladius] &fWe're running low on options here! Send in all of the remaining &cswordsmen &f!", + "wave=49:message=&8[Gladius] &fWe're scraping the bottom of the barrel... Send everything we have left! Move forth, &carchers&f!", + "wave=50:message=&8[Gladius] &fI guess this is it for me... I have no option but to declare - wait, who is that in the distance? Is that &4Uther, the Champion of the Wood League Arena&f? Ladies and gentlemen, game, set, and match! Our contestant has no chance of victory here! They shall face &eeradication &fby our champion!", + "wave=51:message=&8[Gladius the Destitute] &fUnbelievable, Uther has been vanquished! We have a new arena champion! I would be incredibly excited if I wasn't so terribly in debt now!" + ))); + setMaximumPlayerCount(5); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/CustomBossesConfig.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/CustomBossesConfig.java new file mode 100644 index 000000000..f3d31cc62 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/CustomBossesConfig.java @@ -0,0 +1,48 @@ +package com.magmaguy.elitemobs.config.custombosses; + +import com.magmaguy.elitemobs.config.CustomConfig; +import com.magmaguy.elitemobs.mobconstructor.custombosses.RegionalBossEntity; +import com.magmaguy.elitemobs.utils.InfoMessage; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class CustomBossesConfig extends CustomConfig { + + private static HashMap customBosses = new HashMap<>(); + + public CustomBossesConfig() { + super("custombosses", "com.magmaguy.elitemobs.config.custombosses.premade", CustomBossesConfigFields.class); + customBosses = new HashMap<>(); + for (String key : super.getCustomConfigFieldsHashMap().keySet()) + if (super.getCustomConfigFieldsHashMap().get(key).isEnabled()) { + CustomBossesConfigFields customBossesConfigFields = (CustomBossesConfigFields) super.getCustomConfigFieldsHashMap().get(key); + customBosses.put(key, customBossesConfigFields); + } + //This one initializes mobs, which require all mobs to be initialized for phases / reinforcements + for (CustomBossesConfigFields customBossesConfigFields : customBosses.values()) { + if (customBossesConfigFields.isRegionalBoss()) { + CustomBossesConfigFields.getRegionalElites().put(customBossesConfigFields.getFilename(), customBossesConfigFields); + //Reinforcement elites are only temporary and situational, don't initialize them + if (!customBossesConfigFields.isReinforcement()) { + //Initialize the regional bosses in the world + List locations = customBossesConfigFields.processStringList("spawnLocations", new ArrayList<>(), new ArrayList<>(), false); + if (locations.isEmpty()) + new InfoMessage(customBossesConfigFields.getFilename() + " does not have a set location yet! It will not spawn. Did you install its minidungeon?"); + for (String string : locations) + new RegionalBossEntity(customBossesConfigFields, string).initialize(); + } + } + } + } + + public static HashMap getCustomBosses() { + return customBosses; + } + + public static CustomBossesConfigFields getCustomBoss(String fileName) { + return customBosses.get(fileName); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/CustomBossesConfigFields.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/CustomBossesConfigFields.java new file mode 100644 index 000000000..77e5caca0 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/CustomBossesConfigFields.java @@ -0,0 +1,395 @@ +package com.magmaguy.elitemobs.config.custombosses; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.CustomConfigFields; +import com.magmaguy.elitemobs.config.CustomConfigFieldsInterface; +import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; +import com.magmaguy.elitemobs.items.customloottable.CustomLootTable; +import com.magmaguy.elitemobs.utils.WarningMessage; +import lombok.Getter; +import lombok.Setter; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.*; + +public class CustomBossesConfigFields extends CustomConfigFields implements CustomConfigFieldsInterface { + + @Getter + private static Map regionalElites = new HashMap<>(); + @Getter + private CustomLootTable customLootTable = null; + @Getter + @Setter + private EntityType entityType = EntityType.ZOMBIE; + @Getter + @Setter + private String name = "Default Name"; + @Setter + private String level = "dynamic"; + @Getter + @Setter + private boolean isPersistent = false; + @Getter + @Setter + private double healthMultiplier = 1; + @Getter + @Setter + private double damageMultiplier = 1; + @Getter + @Setter + private boolean frozen = false; + @Getter + @Setter + private boolean reinforcement = false; + @Getter + @Setter + private List onDeathCommands = new ArrayList<>(); + @Getter + @Setter + private List onSpawnCommands = new ArrayList<>(); + @Getter + @Setter + private List onCombatEnterCommands = new ArrayList<>(); + @Getter + @Setter + private List onCombatLeaveCommands = new ArrayList<>(); + @Getter + @Setter + private List uniqueLootList = new ArrayList<>(); + @Getter + @Setter + private List powers = new ArrayList<>(); + @Getter + @Setter + private List onDamageMessages = new ArrayList<>(); + @Getter + @Setter + private List onDamagedMessages = new ArrayList<>(); + @Getter + @Setter + private List trails = new ArrayList<>(); + @Getter + @Setter + private List phases = new ArrayList<>(); + @Getter + @Setter + private String locationMessage = null; + @Getter + @Setter + private String mountedEntity = null; + @Getter + @Setter + private String spawnMessage = null; + @Getter + @Setter + private String deathMessage = null; + @Getter + @Setter + private List deathMessages = new ArrayList<>(); + @Getter + @Setter + private String escapeMessage = null; + @Getter + @Setter + private boolean baby = false; + @Getter + @Setter + private boolean dropsEliteMobsLoot = true; + @Getter + @Setter + private boolean dropsVanillaLoot = true; + @Getter + @Setter + private boolean dropsRandomLoot = true; + /** + * Integration with LibsDisguises. Only used if that plugin is loaded. + */ + @Getter + @Setter + private String disguise = null; + @Getter + @Setter + private String customDisguiseData = null; + @Getter + @Setter + private String customModel = null; + /** + * Announcement priority: + * 0 - no messages + * 1 - spawn/kill/escape messages + * 2 - spawn/kill/escape messages + player tracking + * 3 - spawn/kill/escape messages + player tracking + DiscordSRV discord notifications + *

+ * Default is 1 since the spawn messages have to be added to config files intentionally and it's weird to have to + * enabled them elsewhere on purpose + */ + @Getter + @Setter + private int announcementPriority = 0; + @Getter + @Setter + private Integer followDistance = 0; + @Getter + @Setter + private int spawnCooldown = 0; + @Getter + @Setter + private int timeout = 0; + @Getter + @Setter + private double leashRadius = 0; + @Getter + @Setter + private ItemStack helmet = null; + @Getter + @Setter + private ItemStack chestplate = null; + @Getter + @Setter + private ItemStack leggings = null; + @Getter + @Setter + private ItemStack boots = null; + @Getter + @Setter + private ItemStack mainHand = null; + @Getter + @Setter + private ItemStack offHand = null; + @Getter + private boolean regionalBoss = false; + @Getter + @Setter + private boolean cullReinforcements = true; + @Getter + @Setter + private HashMap damageModifiers = new HashMap(); + @Getter + @Setter + private boolean normalizedCombat = false; + @Getter + @Setter + private Double movementSpeedAttribute = null; + + //this saves files for regional boss respawn cooldowns + @Getter + @Setter + private boolean filesOutOfSync = false; + @Getter + private List onSpawnBlockStates = new ArrayList<>(), onRemoveBlockStates = new ArrayList<>(); + + + /** + * Creates a new default pre-made Custom Boss. The boss is further customized through a builder pattern. + */ + public CustomBossesConfigFields(String fileName, + EntityType entityType, + boolean isEnabled, + String name, + String level) { + super(fileName, isEnabled); + this.entityType = entityType; + this.name = name; + this.level = level; + } + + public CustomBossesConfigFields(String fileName, + boolean isEnabled) { + super(fileName, isEnabled); + } + + + //This method unifies all level placeholders down to $level and applies a custom level for quest display purposes + public String getCleanName(int level) { + return ChatColorConverter.convert(getName().replace("$level", level + "") + .replace("$normalLevel", ChatColorConverter.convert("&2[&a" + level + "&2]&f")) + .replace("$minibossLevel", ChatColorConverter.convert("&6〖&e" + level + "&6〗&f")) + .replace("$bossLevel", ChatColorConverter.convert("&4『&c" + level + "&4』&f")) + .replace("$reinforcementLevel", ChatColorConverter.convert("&8〔&7") + level + "&8〕&f") + .replace("$eventBossLevel", ChatColorConverter.convert("&4「&c" + level + "&4」&f"))); + } + + public void runtimeSetLeashRadius(double leashRadius) { + this.leashRadius = leashRadius; + this.fileConfiguration.set("leashRadius", leashRadius); + ConfigurationEngine.fileSaverCustomValues(fileConfiguration, file); + } + + public double getDamageModifier(Material material) { + return damageModifiers.get(material) == null ? 1 : damageModifiers.get(material); + } + + public int getLevel() { + if (level.equalsIgnoreCase("dynamic")) { + return -1; + } else { + try { + return Integer.valueOf(level); + } catch (Exception ex) { + new WarningMessage("Regional Elite Mob level for " + getFilename() + " is neither numeric nor dynamic. Fix the configuration for it."); + return 1; + } + } + } + + public void setOnSpawnBlockStates(List onSpawnBlockStates) { + this.onSpawnBlockStates = onSpawnBlockStates; + fileConfiguration.set("onSpawnBlockStates", onSpawnBlockStates); + try { + fileConfiguration.save(file); + } catch (Exception ex) { + new WarningMessage("Failed to save on spawn block states!", true); + } + } + + public void setOnRemoveBlockStates(List onRemoveBlockStates) { + this.onRemoveBlockStates = onRemoveBlockStates; + fileConfiguration.set("onRemoveBlockStates", onRemoveBlockStates); + try { + fileConfiguration.save(file); + } catch (Exception ex) { + new WarningMessage("Failed to save on remove block states!", true); + } + } + + @Override + public void processConfigFields() { + this.isEnabled = processBoolean("isEnabled", isEnabled, true, true); + this.entityType = processEnum("entityType", entityType, EntityType.ZOMBIE, EntityType.class, true); + this.name = processString("name", name, "Default Name", true); + //Levels are strings because "dynamic" is a valid value + this.level = processString("level", level, "dynamic", true); + this.isPersistent = processBoolean("isPersistent", isPersistent, false, false); + this.healthMultiplier = processDouble("healthMultiplier", healthMultiplier, 1D, false); + this.damageMultiplier = processDouble("damageMultiplier", damageMultiplier, 1D, false); + this.baby = processBoolean("isBaby", baby, false, false); + this.dropsEliteMobsLoot = processBoolean("dropsEliteMobsLoot", dropsEliteMobsLoot, true, false); + this.dropsVanillaLoot = processBoolean("dropsVanillaLoot", dropsVanillaLoot, true, false); + this.dropsRandomLoot = processBoolean("dropsRandomLoot", dropsRandomLoot, true, false); + this.frozen = processBoolean("frozen", frozen, false, false); + this.reinforcement = processBoolean("reinforcement", reinforcement, false, false); + this.onDeathCommands = processStringList("onDeathCommands", onDeathCommands, new ArrayList<>(), false); + this.onSpawnCommands = processStringList("onSpawnCommands", onSpawnCommands, new ArrayList<>(), false); + this.onCombatEnterCommands = processStringList("onCombatEnterCommands", onCombatEnterCommands, new ArrayList<>(), false); + this.onCombatLeaveCommands = processStringList("onCombatLeaveCommands", onCombatLeaveCommands, new ArrayList<>(), false); + this.deathMessages = processStringList("deathMessages", deathMessages, new ArrayList<>(), false); + this.uniqueLootList = processStringList("uniqueLootList", uniqueLootList, new ArrayList<>(), false); + this.customLootTable = new CustomLootTable(this); + + //this can't be converted directly to an enum list because there are some special string features in here + this.powers = processStringList("powers", powers, new ArrayList<>(), false); + this.onDamageMessages = processStringList("onDamageMessages", onDamageMessages, new ArrayList<>(), false); + this.onDamagedMessages = processStringList("onDamagedMessages", onDamagedMessages, new ArrayList<>(), false); + this.trails = processStringList("trails", trails, new ArrayList<>(), false); + this.phases = processStringList("phases", phases, new ArrayList<>(), false); + this.locationMessage = processString("locationMessage", locationMessage, null, false); + this.mountedEntity = processString("mountedEntity", mountedEntity, null, false); + this.spawnMessage = processString("spawnMessage", spawnMessage, null, false); + this.deathMessage = processString("deathMessage", deathMessage, null, false); + this.escapeMessage = processString("escapeMessage", escapeMessage, null, false); + this.disguise = processString("disguise", disguise, null, false); + this.customDisguiseData = processString("customDisguiseData", customDisguiseData, null, false); + this.customModel = processString("customModel", customModel, null, false); + this.announcementPriority = processInt("announcementPriority", announcementPriority, 0, false); + this.followDistance = processInt("followDistance", followDistance, 0, false); + this.spawnCooldown = processInt("spawnCooldown", spawnCooldown, 0, false); + this.timeout = processInt("timeout", timeout, 0, false); + this.leashRadius = processDouble("leashRadius", leashRadius, 0, false); + this.helmet = processItemStack("helmet", helmet, null, false); + this.chestplate = processItemStack("chestplate", chestplate, null, false); + this.leggings = processItemStack("leggings", leggings, null, false); + this.boots = processItemStack("boots", boots, null, false); + this.mainHand = processItemStack("mainHand", mainHand, null, false); + this.offHand = processItemStack("offHand", offHand, null, false); + this.regionalBoss = processBoolean("isRegionalBoss", regionalBoss, false, false); + this.onSpawnBlockStates = processStringList("onSpawnBlockStates", onSpawnBlockStates, new ArrayList<>(), false); + this.onRemoveBlockStates = processStringList("onRemoveBlockStates", onRemoveBlockStates, new ArrayList<>(), false); + + cullReinforcements = processBoolean("cullReinforcements", cullReinforcements, true, false); + damageModifiers = processDamageModifiers("damageModifiers", damageModifiers); + + if (MobCombatSettingsConfig.isNormalizeRegionalBosses() && isRegionalBoss()) + this.normalizedCombat = true; + else + this.normalizedCombat = processBoolean("normalizedCombat", normalizedCombat, false, false); + + this.movementSpeedAttribute = processDouble("movementSpeedAttribute", movementSpeedAttribute, null, false); + } + + private HashMap processDamageModifiers(String path, HashMap pluginDefaults) { + HashMap hashMap = new HashMap<>(); + if (!fileConfiguration.contains(path)) + return pluginDefaults; + + for (String rawDamageModifier : fileConfiguration.getStringList(path)) { + String[] parsedStrings; + Material material = null; + Double multiplier = null; + if (rawDamageModifier.contains(",")) { + parsedStrings = rawDamageModifier.split(","); + for (String parsedDamageModifier : parsedStrings) { + if (parsedDamageModifier.contains("material:")) + try { + material = Material.getMaterial(parsedDamageModifier.replace("material:", "")); + } catch (Exception ex) { + new WarningMessage("Boss " + getFilename() + " has invalid entry " + parsedDamageModifier + " !"); + } + else if (parsedDamageModifier.contains("multiplier:")) + try { + multiplier = Double.parseDouble(parsedDamageModifier.replace("multiplier:", "")); + } catch (Exception ex) { + new WarningMessage("Boss " + getFilename() + " has invalid entry " + parsedDamageModifier + " !"); + } + else + new WarningMessage("Entry " + parsedDamageModifier + " is invalid for boss file " + getFilename() + " !"); + } + + } else { + parsedStrings = rawDamageModifier.split(":"); + for (String parsedDamageModifier : parsedStrings) { + if (parsedDamageModifier.contains("material=")) + try { + material = Material.getMaterial(parsedDamageModifier.replace("material=", "")); + } catch (Exception ex) { + new WarningMessage("Boss " + getFilename() + " has invalid entry " + parsedDamageModifier + " !"); + } + else if (parsedDamageModifier.contains("multiplier=")) + try { + multiplier = Double.parseDouble(parsedDamageModifier.replace("multiplier=", "")); + } catch (Exception ex) { + new WarningMessage("Boss " + getFilename() + " has invalid entry " + parsedDamageModifier + " !"); + } + else + new WarningMessage("Entry " + parsedDamageModifier + " is invalid for boss file " + getFilename() + " !"); + } + + } + if (material != null && multiplier != null) + hashMap.put(material, multiplier); + } + if (!hashMap.isEmpty()) + fileConfiguration.addDefault(path, deserializeDamageModifiers(hashMap)); + return hashMap; + } + + private List deserializeDamageModifiers(HashMap damageModifiers) { + List deserializedDamageModifiers = new ArrayList<>(); + damageModifiers.forEach((key, value) -> deserializedDamageModifiers.add("material=" + key.toString() + ":" + "multiplier=" + value)); + return deserializedDamageModifiers; + } + + protected List majorBossDeathString(String slainLine) { + return Arrays.asList( + "&e&l---------------------------------------------", + "&4" + slainLine, + "&c&l 1st Damager: $damager1name &cwith $damager1damage damage!", + "&6&l 2nd Damager: $damager2name &6with $damager2damage damage!", + "&e&l 3rd Damager: $damager3name &ewith $damager3damage damage!", + "&aSlayers: $players", + "&e&l---------------------------------------------"); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/AlphaWerewolfP1Boss.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/AlphaWerewolfP1Boss.java new file mode 100644 index 000000000..75688efb9 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/AlphaWerewolfP1Boss.java @@ -0,0 +1,53 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; + +public class AlphaWerewolfP1Boss extends CustomBossesConfigFields { + public AlphaWerewolfP1Boss() { + super("alpha_werewolf_p1", + EntityType.VINDICATOR, + true, + "$eventBossLevel &7Enraged Vindicator", + "dynamic"); + setPersistent(true); + setHealthMultiplier(4); + setDamageMultiplier(4); + setPhases(Arrays.asList("alpha_werewolf_p2.yml:0.99")); + setPowers(Arrays.asList("spirit_walk.yml", + "summonable:summonType=GLOBAL:filename=gamma_werewolf.yml:amount=1:customSpawn=normal_surface_spawn.yml", + "summonable:summonType=GLOBAL:filename=omega_wolf.yml:amount=5:customSpawn=normal_surface_spawn.yml")); + setSpawnMessage("&cThe howls of an Alpha Werewolf are heard!"); + setDeathMessage("&aThe Alpha Werewolf has been stopped by $players!"); + setDeathMessages(Arrays.asList( + "&e&l---------------------------------------------", + "&4The Alpha Wolf has been put down!", + "&c&l 1st Damager: $damager1name &cwith $damager1damage damage!", + "&6&l 2nd Damager: $damager2name &6with $damager2damage damage!", + "&e&l 3rd Damager: $damager3name &ewith $damager3damage damage!", + "&aSlayers: $players", + "&e&l---------------------------------------------")); + setEscapeMessage("&4Dawn breaks, the Alpha Wolf vanishes without a trace!"); + setLocationMessage("&7Enraged Vindicator: $distance blocks away!"); + setUniqueLootList(Arrays.asList( + "werewolf_bone.yml:0.2", + "werewolf_bone.yml:0.2", + "werewolf_bone.yml:0.2", + "werewolf_bone.yml:0.2", + "werewolf_bone.yml:0.2", + "wolfsbane.yml:0.2")); + setTrails(Collections.singletonList(Material.BONE.toString())); + setAnnouncementPriority(2); + HashMap damageModifiers = new HashMap<>(); + damageModifiers.put(Material.IRON_SWORD, 2D); + damageModifiers.put(Material.IRON_AXE, 2D); + setDamageModifiers(damageModifiers); + setFollowDistance(100); + } +} + diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/AlphaWerewolfP2Boss.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/AlphaWerewolfP2Boss.java new file mode 100644 index 000000000..841e95cf0 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/AlphaWerewolfP2Boss.java @@ -0,0 +1,55 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; + +public class AlphaWerewolfP2Boss extends CustomBossesConfigFields { + public AlphaWerewolfP2Boss() { + super("alpha_werewolf_p2", + EntityType.VINDICATOR, + true, + "$eventBossLevel &7Alpha Werewolf", + "dynamic"); + setPersistent(true); + setHealthMultiplier(4); + setDamageMultiplier(4); + setPowers(Arrays.asList("attack_blinding.yml", "ground_pound.yml", "moonwalk.yml", "spirit_walk.yml", + "summonable:summonType=ON_HIT:filename=beta_wolf.yml:amount=5:chance=0.1:inheritAggro=true:spawnNearby=true", + "summonable:summonType=ON_HIT:filename=gamma_werewolf.yml:amount=1:chance=0.1:inheritAggro=true:spawnNearby=true", + "summonable:summonType=GLOBAL:filename=gamma_werewolf.yml:amount=1:customSpawn=normal_surface_spawn.yml", + "summonable:summonType=GLOBAL:filename=omega_wolf.yml:amount=5:customSpawn=normal_surface_spawn.yml")); + setSpawnMessage("&cThe howls of an Alpha Werewolf are heard!"); + setDeathMessage("&aThe Alpha Werewolf has been stopped by $players!"); + setDeathMessages(Arrays.asList( + "&e&l---------------------------------------------", + "&4The Alpha Wolf has been put down!", + "&c&l 1st Damager: $damager1name &cwith $damager1damage damage!", + "&6&l 2nd Damager: $damager2name &6with $damager2damage damage!", + "&e&l 3rd Damager: $damager3name &ewith $damager3damage damage!", + "&aSlayers: $players", + "&e&l---------------------------------------------")); + setEscapeMessage("&4Dawn breaks, the Alpha Wolf vanishes without a trace!"); + setLocationMessage("&7Alpha Wolf: $distance blocks away!"); + setUniqueLootList(Arrays.asList( + "werewolf_bone.yml:0.2", + "werewolf_bone.yml:0.2", + "werewolf_bone.yml:0.2", + "werewolf_bone.yml:0.2", + "werewolf_bone.yml:0.2", + "wolfsbane.yml:0.2")); + setTrails(Collections.singletonList(Material.BONE.toString())); + setDisguise("custom:alpha_werewolf_p2"); + setCustomDisguiseData("player alpha_werewolf_p2 setskin {\"id\":\"50f47a40-9557-4ef8-9986-9c97215116e4\",\"name\":\"Unknown\",\"properties\":[{\"name\":\"textures\",\"value\":\"ewogICJ0aW1lc3RhbXAiIDogMTU5NjY5NjY4Njg4OCwKICAicHJvZmlsZUlkIiA6ICIwNmE4NjAyZDAwODk0YWQxOTcyMGQ3NGE1OGU1MDZjZiIsCiAgInByb2ZpbGVOYW1lIiA6ICJfMW5kcmFfIiwKICAic2lnbmF0dXJlUmVxdWlyZWQiIDogdHJ1ZSwKICAidGV4dHVyZXMiIDogewogICAgIlNLSU4iIDogewogICAgICAidXJsIiA6ICJodHRwOi8vdGV4dHVyZXMubWluZWNyYWZ0Lm5ldC90ZXh0dXJlLzU1ZWFhMDlkNDVlMzFhNmM0YzFjYTc3MWNkZWE4ZDlmM2Y2MWJjMTI1MGI5ZTg5NGY3ZmQ1YzIxM2YxOGE0YjUiCiAgICB9CiAgfQp9\",\"signature\":\"psopRAKIS71E2Chl8hKBKXJG6yvtDxP+e0yUY6iDRlPC8M/0Vs+lL1dnArQSKO68PZ6KlaiYRdMhEWHVTdbz3wXniNK8KNi+Aitl3MYXGD7BRfxENJE4GOjyvAYyWgxyU3s2D8gZbBMkrNYBcNI7SvhLUT67libXG0WOUCBLGE29mtRRS74eHEC0P55CoVXJtxksxBr3wM4p55hQepQoDV+zrGmokwNZjgxlNaMP0v6R6LWyBxfwnCTVNRa8PS+YmMtxXkqa9Dl9aDAzit41J455F9Ei/Md4wahZ89pauLzBnWrjlJLriv5yg/pCWBOlUqreLaiN3y+gFmMa1TjI52FMyPn56/GW5U+Eud90nL9I4NignfJzdGgDqjP2e7xcgRvmEb344+97/fTPy721vgsMXMAlEPwQg7HadTCUOpRGn918gGRTbLdZGPRvcZxRKVV6unM1bB25XaRNC5GZtOHRDO61YmX5c5URIy6ectjmhPrw3u6Yx8q/5N5+OIsoADANTUh9decoaCT4Z5T12s6YtsBy7qay3fTt4oVj4pWO3zWvLJ+8NmGKlyX+SHz7xcxXhFOUgXoX7V+5ICN87zn4IsQ7j4Ihn8uSrEbX05tnfBELbQFz7MGULvqwnR2GiEYyVULOB4y1fISoRNNx1TtbtAOMEB3dnKlHgdzkdhM=\"}],\"legacy\":false}"); + setAnnouncementPriority(2); + HashMap damageModifiers = new HashMap<>(); + damageModifiers.put(Material.IRON_SWORD, 2D); + damageModifiers.put(Material.IRON_AXE, 2D); + setDamageModifiers(damageModifiers); + setFollowDistance(100); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/ArmorGoblinBoss.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/ArmorGoblinBoss.java new file mode 100644 index 000000000..b54457d3f --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/ArmorGoblinBoss.java @@ -0,0 +1,51 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; +import java.util.Collections; + +public class ArmorGoblinBoss extends CustomBossesConfigFields { + public ArmorGoblinBoss() { + super("armor_goblin", + EntityType.ZOMBIE, + true, + "$eventBossLevel &3Armor Goblin", + "dynamic"); + setHealthMultiplier(4); + setDamageMultiplier(4); + setHelmet(new ItemStack(Material.DIAMOND_HELMET)); + setChestplate(new ItemStack(Material.DIAMOND_CHESTPLATE)); + setLeggings(new ItemStack(Material.DIAMOND_LEGGINGS)); + setBoots(new ItemStack(Material.DIAMOND_BOOTS)); + setMainHand(new ItemStack(Material.SHIELD)); + setOffHand(new ItemStack(Material.SHIELD)); + setBaby(true); + setPowers(Arrays.asList("gold_explosion.yml", "gold_shotgun.yml", "spirit_walk.yml")); + setSpawnMessage("&cAn Armor Goblin has been sighted!"); + setDeathMessage("&aAn Armor Goblin has been slain by $players!"); + setDeathMessages(Arrays.asList( + "&e&l---------------------------------------------", + "&eThe Armor Goblin has been pillaged!", + "&c&l 1st Damager: $damager1name &cwith $damager1damage damage!", + "&6&l 2nd Damager: $damager2name &6with $damager2damage damage!", + "&e&l 3rd Damager: $damager3name &ewith $damager3damage damage!", + "&aSlayers: $players", + "&e&l---------------------------------------------")); + setEscapeMessage("&4An Armor Goblin has escaped!"); + setLocationMessage("&cArmor Goblin: $distance blocks away!"); + setTrails(Collections.singletonList(Material.GOLD_NUGGET.toString())); + setAnnouncementPriority(2); + setPersistent(true); + setUniqueLootList(Arrays.asList( + "goblin_helmet.yml:0.2", + "goblin_chestplate.yml:0.2", + "goblin_leggings.yml:0.2", + "goblin_boots.yml:0.2" + )); + setFollowDistance(100); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/BalrogConfig.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/BalrogConfig.java new file mode 100644 index 000000000..d65df6d93 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/BalrogConfig.java @@ -0,0 +1,26 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Particle; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; +import java.util.Collections; + +public class BalrogConfig extends CustomBossesConfigFields { + public BalrogConfig() { + super("balrog", + EntityType.SILVERFISH, + true, + "$eventBossLevel &4Balrog", + "dynamic"); + setPowers(Collections.singletonList("summonable:summonType=ON_HIT:chance=0.5:filename=raug.yml")); + setUniqueLootList(Collections.singletonList("dwarven_greed.yml:1")); + setTrails(Arrays.asList(Particle.SMOKE_LARGE.toString(), + Particle.SMOKE_LARGE.toString(), + Particle.SMOKE_LARGE.toString(), + Particle.SMOKE_LARGE.toString(), + Particle.FLAME.toString(), + Particle.FLAME.toString())); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/BeastMasterBoss.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/BeastMasterBoss.java new file mode 100644 index 000000000..1b0b2ff0b --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/BeastMasterBoss.java @@ -0,0 +1,36 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class BeastMasterBoss extends CustomBossesConfigFields { + public BeastMasterBoss() { + super("beast_master", + EntityType.VINDICATOR, + true, + "$eventBossLevel &6Beast Master", + "dynamic"); + setHealthMultiplier(2); + setDamageMultiplier(2); + setSpawnMessage("&cThe Beast Master has been sighted!"); + setDeathMessage("&aThe Best Master has been slain by $players!"); + setDeathMessages(Arrays.asList( + "&e&l---------------------------------------------", + "&eThe Beast Master has been savaged!", + "&c&l 1st Damager: $damager1name &cwith $damager1damage damage!", + "&6&l 2nd Damager: $damager2name &6with $damager2damage damage!", + "&e&l 3rd Damager: $damager3name &ewith $damager3damage damage!", + "&aSlayers: $players", + "&e&l---------------------------------------------")); + setEscapeMessage("&4The Beast Master has returned to the wilds!"); + setLocationMessage("&cBeast Master: $distance blocks away!"); + setAnnouncementPriority(2); + setPersistent(true); + setPowers(Arrays.asList("attack_poison.yml", "ground_pound.yml", "bonus_loot.yml", + "summonable:summonType=ON_HIT:filename=wild_wolf.yml:spawnNearby=true:inheritAggro=true:inheritLevel=true:chance=0.2")); + setUniqueLootList(Arrays.asList("summon_wolf_scroll.yml:1")); + setFollowDistance(100); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/BetaWolfBoss.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/BetaWolfBoss.java new file mode 100644 index 000000000..032284375 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/BetaWolfBoss.java @@ -0,0 +1,28 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; +import java.util.HashMap; + +public class BetaWolfBoss extends CustomBossesConfigFields { + public BetaWolfBoss() { + super("beta_wolf", + EntityType.WOLF, + true, + "$reinforcementLevel &7Beta Wolf", + "dynamic"); + setDropsEliteMobsLoot(false); + setDropsVanillaLoot(false); + setHealthMultiplier(0.5); + setDamageMultiplier(0.5); + setPowers(Arrays.asList("attack_poison.yml")); + HashMap damageModifiers = new HashMap<>(); + damageModifiers.put(Material.IRON_SWORD, 2D); + damageModifiers.put(Material.IRON_AXE, 2D); + setDamageModifiers(damageModifiers); + setFollowDistance(100); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/BinderOfWorldsPhase1EndermiteReinforcementConfig.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/BinderOfWorldsPhase1EndermiteReinforcementConfig.java new file mode 100644 index 000000000..fe4b2ca97 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/BinderOfWorldsPhase1EndermiteReinforcementConfig.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.entity.EntityType; + +public class BinderOfWorldsPhase1EndermiteReinforcementConfig extends CustomBossesConfigFields { + public BinderOfWorldsPhase1EndermiteReinforcementConfig() { + super("binder_of_worlds_phase_1_endermite_reinforcement", + EntityType.ENDERMITE, + true, + "$reinforcementLevel &5Reality Corruptor", + "200"); + setTimeout(2); + setDropsVanillaLoot(false); + setDropsEliteMobsLoot(false); + setHealthMultiplier(0.1); + setDamageMultiplier(0.5); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/BinderOfWorldsPhase3EndermanReinforcementConfig.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/BinderOfWorldsPhase3EndermanReinforcementConfig.java new file mode 100644 index 000000000..c5386e80c --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/BinderOfWorldsPhase3EndermanReinforcementConfig.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.entity.EntityType; + +public class BinderOfWorldsPhase3EndermanReinforcementConfig extends CustomBossesConfigFields { + public BinderOfWorldsPhase3EndermanReinforcementConfig() { + super("binder_of_worlds_phase_3_enderman_reinforcement", + EntityType.ENDERMAN, + true, + "$reinforcementLevel &5Reality Slayer", + "200"); + setDropsVanillaLoot(false); + setDropsEliteMobsLoot(true); + setFollowDistance(200); + setDamageMultiplier(2); + setHealthMultiplier(5); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/BinderOfWorldsPhase3GhastReinforcementConfig.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/BinderOfWorldsPhase3GhastReinforcementConfig.java new file mode 100644 index 000000000..d620af015 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/BinderOfWorldsPhase3GhastReinforcementConfig.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.entity.EntityType; + +public class BinderOfWorldsPhase3GhastReinforcementConfig extends CustomBossesConfigFields { + public BinderOfWorldsPhase3GhastReinforcementConfig() { + super("binder_of_worlds_phase_3_ghast_reinforcement", + EntityType.GHAST, + true, + "$reinforcementLevel &5Reality Shredder", + "200"); + setDropsVanillaLoot(false); + setDropsEliteMobsLoot(false); + setTimeout(2); + setFollowDistance(200); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/BlayyzeConfig.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/BlayyzeConfig.java new file mode 100644 index 000000000..a0b1004ab --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/BlayyzeConfig.java @@ -0,0 +1,37 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class BlayyzeConfig extends CustomBossesConfigFields { + public BlayyzeConfig() { + super("blayyze", + EntityType.BLAZE, + true, + "$eventBossLevel &6Blayyze", + "dynamic"); + setTimeout(30); + setPersistent(true); + setHealthMultiplier(4); + setDamageMultiplier(0.5); + setPowers(Arrays.asList("meteor_shower.yml", "summon_embers.yml", "bullet_hell.yml", "spirit_walk.yml")); + setSpawnMessage("&cSomething came out of the meteorite's crater..."); + setDeathMessage("&6$players completed first contact."); + setDeathMessages(Arrays.asList( + "&e&l---------------------------------------------", + "&6The Blayyze has been repelled!", + "&c&l 1st Damager: $damager1name &cwith $damager1damage damage!", + "&6&l 2nd Damager: $damager2name &6with $damager2damage damage!", + "&e&l 3rd Damager: $damager3name &ewith $damager3damage damage!", + "&aSlayers: $players", + "&e&l---------------------------------------------")); + setEscapeMessage("&6The ayyliens have been taken to area 51!"); + setLocationMessage("&6????: $distance blocks away"); + setUniqueLootList(Arrays.asList("meteor_shower_scroll.yml:1")); + setTrails(Arrays.asList(Material.FIRE_CHARGE.toString())); + setAnnouncementPriority(2); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/CharmsGoblinBoss.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/CharmsGoblinBoss.java new file mode 100644 index 000000000..ff40a8980 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/CharmsGoblinBoss.java @@ -0,0 +1,58 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; +import java.util.Collections; + +public class CharmsGoblinBoss extends CustomBossesConfigFields { + public CharmsGoblinBoss() { + super("charms_goblin.yml", + EntityType.ZOMBIE, + true, + "$eventBossLevel &2Charms Goblin", + "dynamic"); + setHealthMultiplier(4); + setDamageMultiplier(4); + setHelmet(new ItemStack(Material.IRON_HELMET)); + setChestplate(new ItemStack(Material.IRON_CHESTPLATE)); + setLeggings(new ItemStack(Material.IRON_LEGGINGS)); + setBoots(new ItemStack(Material.IRON_BOOTS)); + setBaby(true); + setPowers(Arrays.asList("gold_explosion.yml", "gold_shotgun.yml", "spirit_walk.yml")); + setSpawnMessage("&cA Charms Goblin has been sighted!"); + setDeathMessage("&aA Charms Goblin has been slain by $players!"); + setDeathMessages(Arrays.asList( + "&e&l---------------------------------------------", + "&eThe Charms Goblin has been pillaged!", + "&c&l 1st Damager: $damager1name &cwith $damager1damage damage!", + "&6&l 2nd Damager: $damager2name &6with $damager2damage damage!", + "&e&l 3rd Damager: $damager3name &ewith $damager3damage damage!", + "&aSlayers: $players", + "&e&l---------------------------------------------")); + setEscapeMessage("&4A Charms Goblin has escaped!"); + setLocationMessage("&cCharms Goblin: $distance blocks away!"); + setTrails(Collections.singletonList(Material.GOLD_NUGGET.toString())); + setAnnouncementPriority(2); + setPersistent(true); + setUniqueLootList(Arrays.asList( + "berserker_charm.yml:0.2", + "chameleon_charm.yml:0.2", + "cheetah_charm.yml:0.2", + "elephant_charm.yml:0.2", + "firefly_charm.yml:0.2", + "fishy_charm.yml:0.2", + "lucky_charms.yml:0.2", + "owl_charm.yml:0.2", + "rabbit_charm.yml:0.2", + "salamander_charm.yml:0.2", + "scorpion_charm.yml:0.2", + "shulker_charm.yml:0.2", + "slowpoke_charm.yml:0.2", + "vampiric_charm.yml:0.2")); + setFollowDistance(100); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/CoinsGoblinBoss.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/CoinsGoblinBoss.java new file mode 100644 index 000000000..a8c63c738 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/CoinsGoblinBoss.java @@ -0,0 +1,43 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; +import java.util.Collections; + +public class CoinsGoblinBoss extends CustomBossesConfigFields { + public CoinsGoblinBoss() { + super("coins_goblin", + EntityType.ZOMBIE, + true, + "$eventBossLevel &eCoins Goblin", + "dynamic"); + setHealthMultiplier(4); + setDamageMultiplier(4); + setHelmet(new ItemStack(Material.GOLDEN_HELMET)); + setChestplate(new ItemStack(Material.GOLDEN_CHESTPLATE)); + setLeggings(new ItemStack(Material.GOLDEN_LEGGINGS)); + setBoots(new ItemStack(Material.GOLDEN_BOOTS)); + setBaby(true); + setPowers(Arrays.asList("gold_explosion.yml", "gold_shotgun.yml", "spirit_walk.yml", "bonus_coins.yml:20")); + setSpawnMessage("&cA Coins Goblin has been sighted!"); + setDeathMessage("&aA Coins Goblin has been slain by $players!"); + setDeathMessages(Arrays.asList( + "&e&l---------------------------------------------", + "&eThe Coins Goblin has been pillaged!", + "&c&l 1st Damager: $damager1name &cwith $damager1damage damage!", + "&6&l 2nd Damager: $damager2name &6with $damager2damage damage!", + "&e&l 3rd Damager: $damager3name &ewith $damager3damage damage!", + "&aSlayers: $players", + "&e&l---------------------------------------------")); + setEscapeMessage("&4A Coins Goblin has escaped!"); + setLocationMessage("&cCoins Goblin: $distance blocks away!"); + setTrails(Collections.singletonList(Material.GOLD_NUGGET.toString())); + setAnnouncementPriority(2); + setPersistent(true); + setFollowDistance(100); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/EmberConfig.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/EmberConfig.java new file mode 100644 index 000000000..0da41f50c --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/EmberConfig.java @@ -0,0 +1,21 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Particle; +import org.bukkit.entity.EntityType; + +import java.util.Collections; + +public class EmberConfig extends CustomBossesConfigFields { + public EmberConfig() { + super("ember", + EntityType.BLAZE, + true, + "$reinforcementLevel &cEmber", + "dynamic"); + setHealthMultiplier(0.3); + setDamageMultiplier(0.3); + setDropsEliteMobsLoot(false); + setTrails(Collections.singletonList(Particle.SPELL_WITCH.toString())); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/FireFaeConfig.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/FireFaeConfig.java new file mode 100644 index 000000000..417e3f396 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/FireFaeConfig.java @@ -0,0 +1,22 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Particle; +import org.bukkit.entity.EntityType; + +import java.util.Collections; + +public class FireFaeConfig extends CustomBossesConfigFields { + public FireFaeConfig() { + super("fire_fae", + EntityType.VEX, + true, + "$eventBossLevel &cFire Fae", + "dynamic"); + setHealthMultiplier(0.3); + setDamageMultiplier(0.3); + setPowers(Collections.singletonList("attack_fire.yml")); + setUniqueLootList(Collections.singletonList("the_feller.yml:0.3")); + setTrails(Collections.singletonList(Particle.FLAME.toString())); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/GamaWerewolfBoss.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/GamaWerewolfBoss.java new file mode 100644 index 000000000..f6b5b6568 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/GamaWerewolfBoss.java @@ -0,0 +1,29 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; +import java.util.HashMap; + +public class GamaWerewolfBoss extends CustomBossesConfigFields { + public GamaWerewolfBoss() { + super("gamma_werewolf", + EntityType.WOLF, + true, + "$reinforcementLevel &7Gamma Werewolf", + "dynamic"); + setHealthMultiplier(1.5); + setDamageMultiplier(1.5); + setPowers(Arrays.asList("ground_pound.yml", + "summonable:summonType=ON_COMBAT_ENTER:filename=omega_wolf.yml:amount=2:inheritAggro=true:spawnNearby=true")); + setDisguise("custom:gamma_werewolf"); + setCustomDisguiseData("player gamma_werewolf setskin {\"id\":\"5f5fff79-687e-46ad-8020-e618a6ec8871\",\"name\":\"Unknown\",\"properties\":[{\"name\":\"textures\",\"value\":\"ewogICJ0aW1lc3RhbXAiIDogMTYyNzE4OTcxMTA4MCwKICAicHJvZmlsZUlkIiA6ICJkMGFkNThjOTNiMzY0ZjgyOWRjZWEzMTAzMzE5MTgyMSIsCiAgInByb2ZpbGVOYW1lIiA6ICJfU2FwcGhpcmVfTHVuYV8iLAogICJzaWduYXR1cmVSZXF1aXJlZCIgOiB0cnVlLAogICJ0ZXh0dXJlcyIgOiB7CiAgICAiU0tJTiIgOiB7CiAgICAgICJ1cmwiIDogImh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZnQubmV0L3RleHR1cmUvNjgxZjRmMGRiNWUzZDQzYmU2ZWMwNzE3Njc0MDMxN2Y4ZTQxZWJiNjU0YzYwZTU4MzVhZGYyMzE5MzUzMTE3IgogICAgfQogIH0KfQ==\",\"signature\":\"d9XXwZOzBUfoV04rV2XOoSRI1GYolEe2ABeNXL8Yft56L+ci/tzM+DWya9yzTjP1cS4wQ1B23rAX2CQfcSC9HF/LPTtwzE+gmGt0EVGH+S3jvcXPl/Vb2igfK6LmINqhjpqEIhvF8NePF3oZ01S6Bwc46v1SMRQ3LpWC9cPPrIeVc48RrpsxknQVzszuKHeiDv3H1x4pdhpR3EdLlAPMyapijio1yjYCRgxd9TWN/4EcbtKTWy2AeEwU/eATYiNFYcFPdOQ3FGjiveUkeq8dGGe8huZvFCNcSizuws70HaIQrJceosRfnwiuJUBUVkYS9cPCVmV+dDOBOCYt7falct2wuHQWFXcD6e9Umqts26lzLbccDY0VQnb9k32Ip/6m95v8sg7AP1OcEN9PNrD5MV+p+CSkzfqfoS2nDcBg69hhi6DYqPBzlqVmDAdRJs2MX5kQoYwM5Zqi6LJDWqVNkNixc/MBnzkS92PcG93cd6eMPjE6p4gWRLoU9hbuUo+6xxh4vItBJj+65UgRvVk48fJJSEKn61be8Jhp6nuhmJ4AUYfGcBun9Q0Wn7py+YsBAZs6Abt3+Nr56V7dOxhiR2hINmhklZVOsiv5UDTzlWhpUe0yBjp92ELfzt7mbLzv5he6SUaxK1OytYchA8nJbTEZnsLpOiXaJs+wKgz1u9s=\"}],\"legacy\":false}"); + HashMap damageModifiers = new HashMap<>(); + damageModifiers.put(Material.IRON_SWORD, 2D); + damageModifiers.put(Material.IRON_AXE, 2D); + setDamageModifiers(damageModifiers); + setFollowDistance(100); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/IceFaeConfig.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/IceFaeConfig.java new file mode 100644 index 000000000..2b767ac61 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/IceFaeConfig.java @@ -0,0 +1,22 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Particle; +import org.bukkit.entity.EntityType; + +import java.util.Collections; + +public class IceFaeConfig extends CustomBossesConfigFields { + public IceFaeConfig() { + super("ice_fae", + EntityType.VEX, + true, + "$eventBossLevel &bIce Fae", + "dynamic"); + setHealthMultiplier(0.3); + setDamageMultiplier(0.3); + setPowers(Collections.singletonList("attack_freeze.yml")); + setUniqueLootList(Collections.singletonList("the_feller.yml:0.3")); + setTrails(Collections.singletonList(Particle.WATER_DROP.toString())); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/ImperialBeeGuardConfig.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/ImperialBeeGuardConfig.java new file mode 100644 index 000000000..2d2059627 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/ImperialBeeGuardConfig.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import com.magmaguy.elitemobs.utils.VersionChecker; +import org.bukkit.Particle; +import org.bukkit.entity.EntityType; + +import java.util.Collections; + +public class ImperialBeeGuardConfig extends CustomBossesConfigFields { + public ImperialBeeGuardConfig() { + super("imperial_bee_guard", + EntityType.ZOMBIE, + true, + "$reinforcementLevel &eImperial Bee Soldier", + "dynamic"); + if (!VersionChecker.serverVersionOlderThan(15, 0)) + setEntityType(EntityType.BEE); + setDropsEliteMobsLoot(false); + setDropsVanillaLoot(false); + setHealthMultiplier(0.1); + setDamageMultiplier(0.1); + setTrails(Collections.singletonList(Particle.SMOKE_LARGE.toString())); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/KillerRabbitOfCaerbannogConfig.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/KillerRabbitOfCaerbannogConfig.java new file mode 100644 index 000000000..087ddf7cb --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/KillerRabbitOfCaerbannogConfig.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Particle; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; +import java.util.Collections; + +public class KillerRabbitOfCaerbannogConfig extends CustomBossesConfigFields { + public KillerRabbitOfCaerbannogConfig() { + super("killer_rabbit_of_caerbannog", + EntityType.RABBIT, + true, + "$eventBossLevel &cKiller Rabbit of Caerbannog", + "dynamic"); + setUniqueLootList(Collections.singletonList("rabbit_charm.yml:1")); + setTrails(Arrays.asList(Particle.SMOKE_LARGE.toString(), + Particle.SMOKE_LARGE.toString(), + Particle.SMOKE_LARGE.toString(), + Particle.SMOKE_LARGE.toString(), + Particle.FLAME.toString(), + Particle.FLAME.toString())); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/KrakenConfig.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/KrakenConfig.java new file mode 100644 index 000000000..8da023946 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/KrakenConfig.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Particle; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; +import java.util.Collections; + +public class KrakenConfig extends CustomBossesConfigFields { + public KrakenConfig() { + super("kraken", + EntityType.ELDER_GUARDIAN, + true, + "$eventBossLevel &3Kraken", + "dynamic"); + setUniqueLootList(Collections.singletonList("rod_of_the_depths.yml:1")); + setTrails(Arrays.asList(Particle.SMOKE_LARGE.toString(), + Particle.SMOKE_LARGE.toString(), + Particle.SMOKE_LARGE.toString(), + Particle.SMOKE_LARGE.toString(), + Particle.FLAME.toString(), + Particle.FLAME.toString())); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/LightningFaeConfig.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/LightningFaeConfig.java new file mode 100644 index 000000000..aef9045bd --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/LightningFaeConfig.java @@ -0,0 +1,22 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Particle; +import org.bukkit.entity.EntityType; + +import java.util.Collections; + +public class LightningFaeConfig extends CustomBossesConfigFields { + public LightningFaeConfig() { + super("lightning_fae", + EntityType.VEX, + true, + "$eventBossLevel &eLightning Fae", + "dynamic"); + setHealthMultiplier(0.3); + setDamageMultiplier(0.3); + setPowers(Collections.singletonList("attack_lightning.yml")); + setUniqueLootList(Collections.singletonList("the_feller.yml:0.3")); + setTrails(Collections.singletonList(Particle.SPELL.toString())); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/NecronomiconSkeletonConfig.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/NecronomiconSkeletonConfig.java new file mode 100644 index 000000000..7ce48756f --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/NecronomiconSkeletonConfig.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.entity.EntityType; + +public class NecronomiconSkeletonConfig extends CustomBossesConfigFields { + public NecronomiconSkeletonConfig() { + super("necronomicon_skeleton", + EntityType.SKELETON, + true, + "$reinforcementLevel &7Summoned Skeleton", + "dynamic"); + setHealthMultiplier(0.3); + setDamageMultiplier(0.1); + setDropsVanillaLoot(false); + setDropsEliteMobsLoot(false); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/NecronomiconZombieConfig.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/NecronomiconZombieConfig.java new file mode 100644 index 000000000..57e9d02d7 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/NecronomiconZombieConfig.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.entity.EntityType; + +public class NecronomiconZombieConfig extends CustomBossesConfigFields { + public NecronomiconZombieConfig() { + super("necronomicon_zombie", + EntityType.ZOMBIE, + true, + "$reinforcementLevel &7Summoned Zombie", + "dynamic"); + setHealthMultiplier(0.3); + setDamageMultiplier(0.1); + setDropsVanillaLoot(false); + setDropsEliteMobsLoot(false); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/OmegaWolfBoss.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/OmegaWolfBoss.java new file mode 100644 index 000000000..325dce764 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/OmegaWolfBoss.java @@ -0,0 +1,24 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; +import java.util.HashMap; + +public class OmegaWolfBoss extends CustomBossesConfigFields { + public OmegaWolfBoss() { + super("omega_wolf", + EntityType.WOLF, + true, + "$reinforcementLevel &7Omega Wolf", + "dynamic"); + setPowers(Arrays.asList("attack_poison.yml", "moonwalk.yml")); + HashMap damageModifiers = new HashMap<>(); + damageModifiers.put(Material.IRON_SWORD, 2D); + damageModifiers.put(Material.IRON_AXE, 2D); + setDamageModifiers(damageModifiers); + setFollowDistance(100); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/PillagerCaravanBeastBoss.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/PillagerCaravanBeastBoss.java new file mode 100644 index 000000000..57f6a41b5 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/PillagerCaravanBeastBoss.java @@ -0,0 +1,20 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class PillagerCaravanBeastBoss extends CustomBossesConfigFields { + public PillagerCaravanBeastBoss() { + super("pillager_caravan_beast", + EntityType.RAVAGER, + true, + "$reinforcementLevel &cCaravan Beast", + "dynamic"); + setDropsEliteMobsLoot(false); + setDropsVanillaLoot(false); + setFollowDistance(100); + setPowers(Arrays.asList("attack_confusing.yml")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/PillagerCaravanGuardBoss.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/PillagerCaravanGuardBoss.java new file mode 100644 index 000000000..ce4467e88 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/PillagerCaravanGuardBoss.java @@ -0,0 +1,21 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class PillagerCaravanGuardBoss extends CustomBossesConfigFields { + public PillagerCaravanGuardBoss() { + super("pillager_caravan_guard", + EntityType.PILLAGER, + true, + "$reinforcementLevel &cCaravan Guard", + "dynamic"); + setDropsEliteMobsLoot(false); + setDropsVanillaLoot(false); + setMountedEntity("pillager_caravan_beast.yml"); + setFollowDistance(100); + setPowers(Arrays.asList("attack_poison.yml")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/PillagerCaravanLeaderBoss.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/PillagerCaravanLeaderBoss.java new file mode 100644 index 000000000..0545a68e8 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/PillagerCaravanLeaderBoss.java @@ -0,0 +1,33 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class PillagerCaravanLeaderBoss extends CustomBossesConfigFields { + public PillagerCaravanLeaderBoss() { + super("pillager_caravan_leader", + EntityType.PILLAGER, + true, + "$eventBossLevel &cPillager Caravan Leader", + "dynamic"); + setPersistent(true); + setPowers(Arrays.asList("bonus_loot.yml", "arrow_fireworks.yml", "arrow_rain.yml", + "summonable:summonType=ON_COMBAT_ENTER:filename=pillager_caravan_guard.yml:spawnNearby=true:inheritLevel=true", + "summonable:summonType=ON_COMBAT_ENTER:filename=pillager_caravan_guard.yml:spawnNearby=true:inheritLevel=true")); + setMountedEntity("pillager_caravan_beast.yml"); + setFollowDistance(100); + setDamageMultiplier(2); + setHealthMultiplier(2); + setUniqueLootList(Arrays.asList("summon_merchant_scroll.yml:0.5", + "summon_merchant_scroll.yml:0.5", + "summon_merchant_scroll.yml:0.5", + "summon_merchant_scroll.yml:0.5", + "summon_merchant_scroll.yml:0.5")); + setSpawnMessage("&cA pillager caravan has been sighted!"); + majorBossDeathString("The pillager caravan has been vanquished!"); + setLocationMessage("&cPillager Caravan: $distance blocks away!"); + setAnnouncementPriority(2); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/QueenBeeBoss.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/QueenBeeBoss.java new file mode 100644 index 000000000..d83ad4839 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/QueenBeeBoss.java @@ -0,0 +1,29 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import com.magmaguy.elitemobs.utils.VersionChecker; +import org.bukkit.Particle; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; +import java.util.Collections; + +public class QueenBeeBoss extends CustomBossesConfigFields { + public QueenBeeBoss() { + super("queen_bee", + EntityType.ZOMBIE, + true, + "$eventBossLevel &6Queen Bee", + "dynamic"); + if (!VersionChecker.serverVersionOlderThan(15, 0)) + setEntityType(EntityType.BEE); + setPowers(Collections.singletonList("summonable:summonType=ON_HIT:chance=0.5:filename=imperial_bee_guard.yml")); + setUniqueLootList(Collections.singletonList("the_stinger.yml:1")); + setTrails(Arrays.asList(Particle.SMOKE_LARGE.toString(), + Particle.SMOKE_LARGE.toString(), + Particle.SMOKE_LARGE.toString(), + Particle.SMOKE_LARGE.toString(), + Particle.FLAME.toString(), + Particle.FLAME.toString())); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/RaugConfig.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/RaugConfig.java new file mode 100644 index 000000000..157ae3c93 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/RaugConfig.java @@ -0,0 +1,20 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Particle; +import org.bukkit.entity.EntityType; + +import java.util.Collections; + +public class RaugConfig extends CustomBossesConfigFields { + public RaugConfig() { + super("raug", + EntityType.SILVERFISH, + true, + "$reinforcementLevel &4Raug", + "dynamic"); + setHealthMultiplier(0.1); + setDamageMultiplier(0.1); + setTrails(Collections.singletonList(Particle.SMOKE_LARGE.toString())); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/SnoopyConfig.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/SnoopyConfig.java new file mode 100644 index 000000000..af48a1b27 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/SnoopyConfig.java @@ -0,0 +1,33 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; + +import java.util.Collections; + +/** + * In the loving memory of Snoopy, the best boy + * January 2006 - January 2021 + * Gone but not forgotten. + */ +public class SnoopyConfig extends CustomBossesConfigFields { + public SnoopyConfig() { + super("snoopy", + EntityType.WOLF, + true, + "&6{&4☠&6} &fSnoopy", + "dynamic"); + setTimeout(3); + setHealthMultiplier(10); + setDamageMultiplier(5); + setPowers(Collections.singletonList("invulnerability_fire.yml")); + setDropsVanillaLoot(false); + setDropsEliteMobsLoot(false); + setTrails(Collections.singletonList(Material.BONE.toString())); + setOnDamagedMessages(Collections.singletonList("Woof!")); + setOnDamageMessages(Collections.singletonList("Woof!")); + setSpawnMessage("&aAn extremely rare Snoopy has been sighted!"); + setAnnouncementPriority(3); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/SummonableWolfConfig.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/SummonableWolfConfig.java new file mode 100644 index 000000000..bab10f5dc --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/SummonableWolfConfig.java @@ -0,0 +1,24 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; + +import java.util.Collections; + +public class SummonableWolfConfig extends CustomBossesConfigFields { + public SummonableWolfConfig() { + super("summonable_wolf", + EntityType.WOLF, + true, + "$normalLevel Wolfy", + "dynamic"); + setTimeout(3); + setHealthMultiplier(3); + setDropsVanillaLoot(false); + setDropsEliteMobsLoot(false); + setTrails(Collections.singletonList(Material.BONE.toString())); + setOnDamagedMessages(Collections.singletonList("Woof!")); + setOnDamageMessages(Collections.singletonList("Woof!")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/TestCustomBossesConfig.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/TestCustomBossesConfig.java new file mode 100644 index 000000000..ef4727d1d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/TestCustomBossesConfig.java @@ -0,0 +1,50 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import com.magmaguy.elitemobs.utils.VersionChecker; +import org.bukkit.Material; +import org.bukkit.Particle; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; +import java.util.Collections; + +public class TestCustomBossesConfig extends CustomBossesConfigFields { + public TestCustomBossesConfig() { + super("test_boss", + EntityType.ZOMBIE, + true, + "$eventBossLevel &6Test boss", + "dynamic"); + setTimeout(10); + setHealthMultiplier(2); + setDamageMultiplier(0.5); + setHelmet(new ItemStack(Material.GOLDEN_HELMET)); + setChestplate(new ItemStack(Material.IRON_CHESTPLATE)); + setLeggings(new ItemStack(Material.LEATHER_LEGGINGS)); + setBoots(new ItemStack(Material.CHAINMAIL_BOOTS)); + setMainHand(new ItemStack(Material.GOLDEN_AXE)); + setOffHand(new ItemStack(Material.SHIELD)); + setPowers(Collections.singletonList("invulnerability_knockback.yml")); + setSpawnMessage("A test boss has been spawned!"); + setDeathMessage("A test boss has been slain by $players!"); + setDeathMessages(Arrays.asList( + "&e&l---------------------------------------------", + "&eThe Test Boss has been debugged!", + "&c&l 1st Damager: $damager1name &cwith $damager1damage damage!", + "&6&l 2nd Damager: $damager2name &6with $damager2damage damage!", + "&e&l 3rd Damager: $damager3name &ewith $damager3damage damage!", + "&aSlayers: $players", + "&e&l---------------------------------------------")); + setEscapeMessage("A test boss entity has escaped!"); + setLocationMessage("Test entity: $distance"); + setUniqueLootList(Collections.singletonList("magmaguys_toothpick.yml:1")); + if (!VersionChecker.serverVersionOlderThan(18, 0)) + setTrails(Collections.singletonList(Particle.BLOCK_MARKER.toString())); + setOnDamageMessages(Collections.singletonList("I've hit you!")); + setOnDamagedMessages(Collections.singletonList("I've been hit!")); + setOnDeathCommands(Collections.singletonList("broadcast $players has killed $name! That was level $level!")); + setAnnouncementPriority(3); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/TheLivingDeadConfig.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/TheLivingDeadConfig.java new file mode 100644 index 000000000..f494ae5d2 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/TheLivingDeadConfig.java @@ -0,0 +1,24 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class TheLivingDeadConfig extends CustomBossesConfigFields { + public TheLivingDeadConfig() { + super("the_living_dead", + EntityType.HUSK, + true, + "$reinforcementLevel &6The Living Dead", + "dynamic"); + setHelmet(ItemStackGenerator.generateItemStack(Material.CHAINMAIL_HELMET)); + setChestplate(ItemStackGenerator.generateItemStack(Material.CHAINMAIL_CHESTPLATE)); + setLeggings(ItemStackGenerator.generateItemStack(Material.CHAINMAIL_LEGGINGS)); + setBoots(ItemStackGenerator.generateItemStack(Material.CHAINMAIL_BOOTS)); + setPowers(Arrays.asList("attack_fire.yml", "corpse.yml", "ground_pound.yml")); + setFollowDistance(100); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/TheReturnedConfig.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/TheReturnedConfig.java new file mode 100644 index 000000000..61a7e7482 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/TheReturnedConfig.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.entity.EntityType; + +public class TheReturnedConfig extends CustomBossesConfigFields { + public TheReturnedConfig() { + super("the_returned", + EntityType.HUSK, + true, + "$reinforcementLevel &6The Returned", + "dynamic"); + setHealthMultiplier(0.5); + setDamageMultiplier(0.5); + setDropsEliteMobsLoot(false); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/TotemZombie1Boss.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/TotemZombie1Boss.java new file mode 100644 index 000000000..c4b1f30ab --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/TotemZombie1Boss.java @@ -0,0 +1,35 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import com.magmaguy.elitemobs.utils.VersionChecker; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class TotemZombie1Boss extends CustomBossesConfigFields { + public TotemZombie1Boss() { + super("totem_zombie_1", EntityType.ZOMBIE, true, "$eventBossLevel Head Zombie", "dynamic"); + setPersistent(true); + setMountedEntity("totem_zombie_2.yml"); + setPowers(Arrays.asList("skeleton_tracking_arrow.yml", "attack_fireball.yml", "hyper_loot.yml")); + setCullReinforcements(false); + setFollowDistance(100); + if (!VersionChecker.serverVersionOlderThan(16, 0)) { + setHelmet(new ItemStack(Material.NETHERITE_HELMET)); + setChestplate(new ItemStack(Material.NETHERITE_CHESTPLATE)); + setLeggings(new ItemStack(Material.NETHERITE_LEGGINGS)); + setBoots(new ItemStack(Material.NETHERITE_BOOTS)); + setMainHand(new ItemStack(Material.NETHERITE_SWORD)); + } + setDamageMultiplier(2); + setHealthMultiplier(2); + setSpawnMessage("&cA Dr. Craftenmine abomination has been sighted!"); + setDeathMessage("&aDr. Craftenmine's abomination been terminated by $players!"); + setDeathMessages(majorBossDeathString("The Zombie Totem been slain!")); + setEscapeMessage("&4Dr. Craftenmine's creation has escaped!"); + setLocationMessage("&cZombie Totem: $distance blocks away!"); + setAnnouncementPriority(2); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/TotemZombie2Boss.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/TotemZombie2Boss.java new file mode 100644 index 000000000..b488fe0db --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/TotemZombie2Boss.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class TotemZombie2Boss extends CustomBossesConfigFields { + public TotemZombie2Boss() { + super("totem_zombie_2", EntityType.ZOMBIE, true, "$eventBossLevel Totem Zombie", "dynamic"); + setMountedEntity("totem_zombie_3.yml"); + setPowers(Arrays.asList("arrow_rain.yml", "attack_arrow.yml", "bonus_loot.yml")); + setCullReinforcements(false); + setFollowDistance(100); + setHelmet(new ItemStack(Material.DIAMOND_HELMET)); + setChestplate(new ItemStack(Material.DIAMOND_CHESTPLATE)); + setLeggings(new ItemStack(Material.DIAMOND_LEGGINGS)); + setBoots(new ItemStack(Material.DIAMOND_BOOTS)); + setMainHand(new ItemStack(Material.DIAMOND_SWORD)); + setDamageMultiplier(1.5); + setHealthMultiplier(1.5); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/TotemZombie3Boss.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/TotemZombie3Boss.java new file mode 100644 index 000000000..5d88cd999 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/TotemZombie3Boss.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class TotemZombie3Boss extends CustomBossesConfigFields { + public TotemZombie3Boss() { + super("totem_zombie_3", EntityType.ZOMBIE, true, "$eventBossLevel Totem Zombie", "dynamic"); + setMountedEntity("totem_zombie_4.yml"); + setPowers(Arrays.asList("attack_lightning.yml", "attack_web.yml", "bonus_loot.yml")); + setCullReinforcements(false); + setFollowDistance(100); + setHelmet(new ItemStack(Material.IRON_HELMET)); + setChestplate(new ItemStack(Material.IRON_CHESTPLATE)); + setLeggings(new ItemStack(Material.IRON_LEGGINGS)); + setBoots(new ItemStack(Material.IRON_BOOTS)); + setMainHand(new ItemStack(Material.IRON_SWORD)); + setDamageMultiplier(1.5); + setHealthMultiplier(1.5); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/TotemZombie4Boss.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/TotemZombie4Boss.java new file mode 100644 index 000000000..3a89d3c59 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/TotemZombie4Boss.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class TotemZombie4Boss extends CustomBossesConfigFields { + public TotemZombie4Boss() { + super("totem_zombie_4", EntityType.ZOMBIE, true, "$eventBossLevel Totem Zombie", "dynamic"); + setMountedEntity("totem_zombie_5.yml"); + setPowers(Arrays.asList("attack_push.yml", "attack_poison.yml", "bonus_loot.yml")); + setCullReinforcements(false); + setFollowDistance(100); + setHelmet(new ItemStack(Material.CHAINMAIL_HELMET)); + setChestplate(new ItemStack(Material.CHAINMAIL_CHESTPLATE)); + setLeggings(new ItemStack(Material.CHAINMAIL_LEGGINGS)); + setBoots(new ItemStack(Material.CHAINMAIL_BOOTS)); + setMainHand(new ItemStack(Material.STONE_SWORD)); + setDamageMultiplier(1.5); + setHealthMultiplier(1.5); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/TotemZombie5Boss.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/TotemZombie5Boss.java new file mode 100644 index 000000000..e23732afe --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/TotemZombie5Boss.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class TotemZombie5Boss extends CustomBossesConfigFields { + public TotemZombie5Boss() { + super("totem_zombie_5", EntityType.ZOMBIE, true, "$eventBossLevel Totem Zombie", "dynamic"); + setMountedEntity("totem_zombie_6.yml"); + setPowers(Arrays.asList("attack_gravity.yml", "attack_blinding.yml", "bonus_loot.yml")); + setCullReinforcements(false); + setFollowDistance(100); + setHelmet(new ItemStack(Material.LEATHER_HELMET)); + setChestplate(new ItemStack(Material.LEATHER_CHESTPLATE)); + setLeggings(new ItemStack(Material.LEATHER_LEGGINGS)); + setBoots(new ItemStack(Material.LEATHER_BOOTS)); + setMainHand(new ItemStack(Material.WOODEN_SWORD)); + setDamageMultiplier(1.5); + setHealthMultiplier(1.5); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/TotemZombie6Boss.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/TotemZombie6Boss.java new file mode 100644 index 000000000..db144bf24 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/TotemZombie6Boss.java @@ -0,0 +1,21 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class TotemZombie6Boss extends CustomBossesConfigFields { + public TotemZombie6Boss() { + super("totem_zombie_6", EntityType.ZOMBIE, true, "$eventBossLevel Totem Zombie", "dynamic"); + setBaby(true); + setHelmet(new ItemStack(Material.LEATHER_HELMET)); + setPowers(Arrays.asList("attack_wither.yml", "bonus_loot.yml")); + setCullReinforcements(false); + setFollowDistance(100); + setDamageMultiplier(1.5); + setHealthMultiplier(1.5); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/TreasureGoblinBoss.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/TreasureGoblinBoss.java new file mode 100644 index 000000000..ed4c39ceb --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/TreasureGoblinBoss.java @@ -0,0 +1,43 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; +import java.util.Collections; + +public class TreasureGoblinBoss extends CustomBossesConfigFields { + public TreasureGoblinBoss() { + super("treasure_goblin", + EntityType.ZOMBIE, + true, + "$eventBossLevel &eTreasure Goblin", + "dynamic"); + setHealthMultiplier(4); + setDamageMultiplier(4); + setHelmet(new ItemStack(Material.GOLDEN_HELMET)); + setChestplate(new ItemStack(Material.GOLDEN_CHESTPLATE)); + setLeggings(new ItemStack(Material.GOLDEN_LEGGINGS)); + setBoots(new ItemStack(Material.GOLDEN_BOOTS)); + setBaby(true); + setPowers(Arrays.asList("gold_explosion.yml", "gold_shotgun.yml", "hyper_loot.yml", "spirit_walk.yml")); + setSpawnMessage("&cA Treasure Goblin has been sighted!"); + setDeathMessage("&aA Treasure Goblin has been slain by $players!"); + setDeathMessages(Arrays.asList( + "&e&l---------------------------------------------", + "&eThe Treasure Goblin has been pillaged!", + "&c&l 1st Damager: $damager1name &cwith $damager1damage damage!", + "&6&l 2nd Damager: $damager2name &6with $damager2damage damage!", + "&e&l 3rd Damager: $damager3name &ewith $damager3damage damage!", + "&aSlayers: $players", + "&e&l---------------------------------------------")); + setEscapeMessage("&4A Treasure Goblin has escaped!"); + setLocationMessage("&cTreasure Goblin: $distance blocks away!"); + setTrails(Collections.singletonList(Material.GOLD_NUGGET.toString())); + setAnnouncementPriority(2); + setPersistent(true); + setFollowDistance(100); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WeaponsGoblinBoss.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WeaponsGoblinBoss.java new file mode 100644 index 000000000..dae7b5565 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WeaponsGoblinBoss.java @@ -0,0 +1,54 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import com.magmaguy.elitemobs.utils.VersionChecker; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; +import java.util.Collections; + +public class WeaponsGoblinBoss extends CustomBossesConfigFields { + public WeaponsGoblinBoss() { + super("weapons_goblin", + EntityType.ZOMBIE, + true, + "$eventBossLevel &cWeapons Goblin", + "dynamic"); + setHealthMultiplier(4); + setDamageMultiplier(4); + if (!VersionChecker.serverVersionOlderThan(16, 0)) { + setHelmet(new ItemStack(Material.NETHERITE_HELMET)); + setChestplate(new ItemStack(Material.NETHERITE_CHESTPLATE)); + setLeggings(new ItemStack(Material.NETHERITE_LEGGINGS)); + setBoots(new ItemStack(Material.NETHERITE_BOOTS)); + setMainHand(new ItemStack(Material.NETHERITE_SWORD)); + setOffHand(new ItemStack(Material.NETHERITE_AXE)); + } + setBaby(true); + setPowers(Arrays.asList("gold_explosion.yml", "gold_shotgun.yml", "spirit_walk.yml")); + setSpawnMessage("&cA Weapons Goblin has been sighted!"); + setDeathMessage("&aA Weapons Goblin has been slain by $players!"); + setDeathMessages(Arrays.asList( + "&e&l---------------------------------------------", + "&eThe Weapons Goblin has been pillaged!", + "&c&l 1st Damager: $damager1name &cwith $damager1damage damage!", + "&6&l 2nd Damager: $damager2name &6with $damager2damage damage!", + "&e&l 3rd Damager: $damager3name &ewith $damager3damage damage!", + "&aSlayers: $players", + "&e&l---------------------------------------------")); + setEscapeMessage("&4A Weapons Goblin has escaped!"); + setLocationMessage("&cWeapons Goblin: $distance blocks away!"); + setTrails(Collections.singletonList(Material.GOLD_NUGGET.toString())); + setAnnouncementPriority(2); + setPersistent(true); + setUniqueLootList(Arrays.asList( + "goblin_slasher.yml:0.2", + "goblin_cleaver.yml:0.2", + "goblin_poker.yml:0.2", + "goblin_shooter.yml:0.2", + "goblin_ballista.yml:0.2")); + setFollowDistance(100); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WildWolfBoss.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WildWolfBoss.java new file mode 100644 index 000000000..586f0b64b --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WildWolfBoss.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.entity.EntityType; + +public class WildWolfBoss extends CustomBossesConfigFields { + public WildWolfBoss() { + super("wild_wolf.yml", + EntityType.WOLF, + true, + "$reinforcementLevel &7Wild Wolf", + "dynamic"); + setHealthMultiplier(0.2); + setDamageMultiplier(0.2); + setDropsEliteMobsLoot(false); + setDropsVanillaLoot(false); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave10Boss.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave10Boss.java new file mode 100644 index 000000000..1e9ff9119 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave10Boss.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave10Boss extends CustomBossesConfigFields { + public WoodLeagueWave10Boss(){ + super("wood_league_wave_10_boss", + EntityType.WOLF, + true, + "$bossLevel &4Bad Doggo", + "10"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.STICK)); + setPowers(Arrays.asList("ground_pound.yml", + "summonable:summonType=ON_HIT:filename=wood_league_wave_10_reinforcement.yml:amount=2:chance=0.1:inheritAggro=true:spawnNearby=true")); + setMovementSpeedAttribute(0.6D); + setHealthMultiplier(5D); + setDamageMultiplier(2D); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave10Reinforcement.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave10Reinforcement.java new file mode 100644 index 000000000..925fa6701 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave10Reinforcement.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +public class WoodLeagueWave10Reinforcement extends CustomBossesConfigFields { + public WoodLeagueWave10Reinforcement(){ + super("wood_league_wave_10_reinforcement", + EntityType.WOLF, + true, + "$reinforcementLevel &cBad Pupper", + "10"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.STICK)); + setMovementSpeedAttribute(0.6D); + setHealthMultiplier(0.25D); + setDamageMultiplier(0.8D); + setDropsRandomLoot(false); + setDropsEliteMobsLoot(false); + setDropsVanillaLoot(false); + setNormalizedCombat(true); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave11Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave11Melee.java new file mode 100644 index 000000000..d35b7858c --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave11Melee.java @@ -0,0 +1,21 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave11Melee extends CustomBossesConfigFields { + public WoodLeagueWave11Melee(){ + super("wood_league_wave_11_melee", + EntityType.ZOMBIE, + true, + "$normalLevel &4Arena Zombie", + "11"); + setFollowDistance(60); + setPowers(Arrays.asList("corpse.yml")); + setHelmet(new ItemStack(Material.STICK)); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave11Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave11Ranged.java new file mode 100644 index 000000000..287303534 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave11Ranged.java @@ -0,0 +1,22 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave11Ranged extends CustomBossesConfigFields { + public WoodLeagueWave11Ranged(){ + super("wood_league_wave_11_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Arena Crossbowman", + "11"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.STICK)); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("attack_vacuum.yml")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave12Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave12Melee.java new file mode 100644 index 000000000..b5f44d82a --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave12Melee.java @@ -0,0 +1,21 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave12Melee extends CustomBossesConfigFields { + public WoodLeagueWave12Melee(){ + super("wood_league_wave_12_melee", + EntityType.ZOMBIE, + true, + "$normalLevel &4Arena Zombie", + "12"); + setFollowDistance(60); + setPowers(Arrays.asList("corpse.yml")); + setHelmet(new ItemStack(Material.STICK)); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave12Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave12Ranged.java new file mode 100644 index 000000000..aad82c3b4 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave12Ranged.java @@ -0,0 +1,22 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave12Ranged extends CustomBossesConfigFields { + public WoodLeagueWave12Ranged(){ + super("wood_league_wave_12_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Arena Crossbowman", + "12"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.STICK)); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("attack_vacuum.yml")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave13Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave13Melee.java new file mode 100644 index 000000000..d47b48a37 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave13Melee.java @@ -0,0 +1,21 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave13Melee extends CustomBossesConfigFields { + public WoodLeagueWave13Melee(){ + super("wood_league_wave_13_melee", + EntityType.ZOMBIE, + true, + "$normalLevel &4Arena Zombie", + "13"); + setFollowDistance(60); + setPowers(Arrays.asList("corpse.yml", "attack_poison.yml")); + setHelmet(new ItemStack(Material.STICK)); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave13Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave13Ranged.java new file mode 100644 index 000000000..742d2b1c6 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave13Ranged.java @@ -0,0 +1,22 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave13Ranged extends CustomBossesConfigFields { + public WoodLeagueWave13Ranged() { + super("wood_league_wave_13_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Arena Crossbowman", + "13"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.STICK)); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("attack_vacuum.yml", "attack_poison.yml")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave14Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave14Melee.java new file mode 100644 index 000000000..fa7ab706b --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave14Melee.java @@ -0,0 +1,21 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave14Melee extends CustomBossesConfigFields { + public WoodLeagueWave14Melee(){ + super("wood_league_wave_14_melee", + EntityType.ZOMBIE, + true, + "$normalLevel &4Arena Zombie", + "14"); + setFollowDistance(60); + setPowers(Arrays.asList("corpse.yml")); + setHelmet(new ItemStack(Material.STICK)); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave14Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave14Ranged.java new file mode 100644 index 000000000..be9ddc601 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave14Ranged.java @@ -0,0 +1,22 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave14Ranged extends CustomBossesConfigFields { + public WoodLeagueWave14Ranged(){ + super("wood_league_wave_14_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Arena Crossbowman", + "14"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.STICK)); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("attack_vacuum.yml")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave15Miniboss.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave15Miniboss.java new file mode 100644 index 000000000..b80d44fd0 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave15Miniboss.java @@ -0,0 +1,28 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import com.magmaguy.elitemobs.utils.VersionChecker; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave15Miniboss extends CustomBossesConfigFields { + public WoodLeagueWave15Miniboss(){ + super("wood_league_wave_15_miniboss", + EntityType.ZOMBIE, + true, + "$bossLevel &4Mr. Oinkers", + "15"); + if (!VersionChecker.serverVersionOlderThan(16,0)) + setEntityType(EntityType.ZOGLIN); + setFollowDistance(60); + setHelmet(new ItemStack(Material.STICK)); + setPowers(Arrays.asList("gold_explosion.yml", "gold_shotgun.yml")); + setMovementSpeedAttribute(0.6D); + setHealthMultiplier(3D); + setDamageMultiplier(2D); + setOnDamagedMessages(Arrays.asList("Oink!?")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave16Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave16Melee.java new file mode 100644 index 000000000..30918b6a1 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave16Melee.java @@ -0,0 +1,23 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave16Melee extends CustomBossesConfigFields { + public WoodLeagueWave16Melee(){ + super("wood_league_wave_16_melee", + EntityType.ZOMBIE, + true, + "$normalLevel Mr. Oinkers Fan", + "16"); + setFollowDistance(60); + setPowers(Arrays.asList("corpse.yml")); + setHelmet(new ItemStack(Material.STICK)); + setDamageMultiplier(0.5D); + setHealthMultiplier(0.75D); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave16Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave16Ranged.java new file mode 100644 index 000000000..3da5304f0 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave16Ranged.java @@ -0,0 +1,24 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave16Ranged extends CustomBossesConfigFields { + public WoodLeagueWave16Ranged(){ + super("wood_league_wave_16_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Mr. Oinkers Fan", + "16"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.STICK)); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("attack_vacuum.yml")); + setDamageMultiplier(0.5D); + setHealthMultiplier(0.75D); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave17Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave17Melee.java new file mode 100644 index 000000000..e30582e5f --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave17Melee.java @@ -0,0 +1,21 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave17Melee extends CustomBossesConfigFields { + public WoodLeagueWave17Melee(){ + super("wood_league_wave_17_melee", + EntityType.ZOMBIE, + true, + "$normalLevel &4Arena Zombie", + "17"); + setFollowDistance(60); + setPowers(Arrays.asList("corpse.yml", "attack_fire.yml")); + setHelmet(new ItemStack(Material.STICK)); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave17Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave17Ranged.java new file mode 100644 index 000000000..8efb3b002 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave17Ranged.java @@ -0,0 +1,22 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave17Ranged extends CustomBossesConfigFields { + public WoodLeagueWave17Ranged(){ + super("wood_league_wave_17_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Arena Crossbowman", + "17"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.STICK)); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("attack_vacuum.yml", "skeleton_tracking_arrow.yml")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave18Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave18Melee.java new file mode 100644 index 000000000..d3c50bc36 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave18Melee.java @@ -0,0 +1,22 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave18Melee extends CustomBossesConfigFields { + public WoodLeagueWave18Melee(){ + super("wood_league_wave_18_melee", + EntityType.ZOMBIE, + true, + "$normalLevel &4Fencing Club Enthusiast", + "18"); + setFollowDistance(60); + setPowers(Arrays.asList("corpse.yml", "attack_fire.yml")); + setHelmet(new ItemStack(Material.STICK)); + setMainHand(new ItemStack(Material.DIAMOND_SWORD)); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave19Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave19Ranged.java new file mode 100644 index 000000000..590963e24 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave19Ranged.java @@ -0,0 +1,22 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave19Ranged extends CustomBossesConfigFields { + public WoodLeagueWave19Ranged(){ + super("wood_league_wave_19_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Archery Club Enthusiast", + "19"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.STICK)); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("attack_vacuum.yml", "skeleton_tracking_arrow.yml")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave1Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave1Melee.java new file mode 100644 index 000000000..3f7d94bc3 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave1Melee.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +public class WoodLeagueWave1Melee extends CustomBossesConfigFields { + public WoodLeagueWave1Melee() { + super("wood_league_wave_1_melee", + EntityType.ZOMBIE, + true, + "$normalLevel Arena Zombie", + "1"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.STICK)); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave1Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave1Ranged.java new file mode 100644 index 000000000..e36f37e66 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave1Ranged.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +public class WoodLeagueWave1Ranged extends CustomBossesConfigFields { + public WoodLeagueWave1Ranged() { + super("wood_league_wave_1_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Arena Crossbowman", + "1"); + setMainHand(new ItemStack(Material.CROSSBOW)); + setFollowDistance(60); + setHelmet(new ItemStack(Material.STICK)); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave20Boss.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave20Boss.java new file mode 100644 index 000000000..999cd16e9 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave20Boss.java @@ -0,0 +1,29 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave20Boss extends CustomBossesConfigFields { + public WoodLeagueWave20Boss(){ + super("wood_league_wave_20_boss", + EntityType.ZOMBIE, + true, + "$bossLevel &2Zoltan", + "20"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.GOLDEN_HELMET)); + setChestplate(new ItemStack(Material.GOLDEN_CHESTPLATE)); + setLeggings(new ItemStack(Material.GOLDEN_LEGGINGS)); + setBoots(new ItemStack(Material.GOLDEN_BOOTS)); + setMainHand(new ItemStack(Material.GOLDEN_AXE)); + setOffHand(new ItemStack(Material.BOW)); + setPowers(Arrays.asList("skeleton_tracking_arrow.yml", "zombie_bloat.yml", "shield_wall.yml", "bullet_hell.yml")); + setMovementSpeedAttribute(0.6D); + setHealthMultiplier(5D); + setDamageMultiplier(2D); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave21Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave21Melee.java new file mode 100644 index 000000000..df8c3585e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave21Melee.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave21Melee extends CustomBossesConfigFields { + public WoodLeagueWave21Melee() { + super("wood_league_wave_21_melee", + EntityType.ZOMBIE, + true, + "$normalLevel &4Arena Zombie", + "21"); + setFollowDistance(60); + setPowers(Arrays.asList("corpse.yml", "attack_fire.yml")); + setHelmet(new ItemStack(Material.LEATHER_HELMET)); + setChestplate(new ItemStack(Material.LEATHER_CHESTPLATE)); + setLeggings(new ItemStack(Material.LEATHER_LEGGINGS)); + setBoots(new ItemStack(Material.LEATHER_BOOTS)); + setMainHand(new ItemStack(Material.IRON_SWORD)); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave21Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave21Ranged.java new file mode 100644 index 000000000..819108533 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave21Ranged.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave21Ranged extends CustomBossesConfigFields { + public WoodLeagueWave21Ranged(){ + super("wood_league_wave_21_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Arena Crossbowman", + "21"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.LEATHER_HELMET)); + setChestplate(new ItemStack(Material.LEATHER_CHESTPLATE)); + setLeggings(new ItemStack(Material.LEATHER_LEGGINGS)); + setBoots(new ItemStack(Material.LEATHER_BOOTS)); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("attack_vacuum.yml", "skeleton_tracking_arrow.yml")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave22Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave22Melee.java new file mode 100644 index 000000000..c5e672cab --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave22Melee.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave22Melee extends CustomBossesConfigFields { + public WoodLeagueWave22Melee(){ + super("wood_league_wave_22_melee", + EntityType.ZOMBIE, + true, + "$normalLevel &4Arena Zombie", + "22"); + setFollowDistance(60); + setPowers(Arrays.asList("corpse.yml", "attack_fire.yml")); + setHelmet(new ItemStack(Material.LEATHER_HELMET)); + setChestplate(new ItemStack(Material.LEATHER_CHESTPLATE)); + setLeggings(new ItemStack(Material.LEATHER_LEGGINGS)); + setBoots(new ItemStack(Material.LEATHER_BOOTS)); + setMainHand(new ItemStack(Material.IRON_SWORD)); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave22Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave22Ranged.java new file mode 100644 index 000000000..834b677f4 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave22Ranged.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave22Ranged extends CustomBossesConfigFields { + public WoodLeagueWave22Ranged(){ + super("wood_league_wave_22_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Arena Crossbowman", + "22"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.LEATHER_HELMET)); + setChestplate(new ItemStack(Material.LEATHER_CHESTPLATE)); + setLeggings(new ItemStack(Material.LEATHER_LEGGINGS)); + setBoots(new ItemStack(Material.LEATHER_BOOTS)); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("attack_vacuum.yml", "skeleton_tracking_arrow.yml")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave23Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave23Melee.java new file mode 100644 index 000000000..14e4c9635 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave23Melee.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave23Melee extends CustomBossesConfigFields { + public WoodLeagueWave23Melee(){ + super("wood_league_wave_23_melee", + EntityType.ZOMBIE, + true, + "$normalLevel &4Arena Zombie", + "23"); + setFollowDistance(60); + setPowers(Arrays.asList("corpse.yml", "attack_fire.yml", "attack_wither.yml")); + setHelmet(new ItemStack(Material.LEATHER_HELMET)); + setChestplate(new ItemStack(Material.LEATHER_CHESTPLATE)); + setLeggings(new ItemStack(Material.LEATHER_LEGGINGS)); + setBoots(new ItemStack(Material.LEATHER_BOOTS)); + setMainHand(new ItemStack(Material.IRON_SWORD)); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave23Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave23Ranged.java new file mode 100644 index 000000000..a40527411 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave23Ranged.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave23Ranged extends CustomBossesConfigFields { + public WoodLeagueWave23Ranged(){ + super("wood_league_wave_23_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Arena Crossbowman", + "23"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.LEATHER_HELMET)); + setChestplate(new ItemStack(Material.LEATHER_CHESTPLATE)); + setLeggings(new ItemStack(Material.LEATHER_LEGGINGS)); + setBoots(new ItemStack(Material.LEATHER_BOOTS)); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("attack_vacuum.yml", "skeleton_tracking_arrow.yml", "attack_wither.yml")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave24Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave24Melee.java new file mode 100644 index 000000000..d17797246 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave24Melee.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave24Melee extends CustomBossesConfigFields { + public WoodLeagueWave24Melee(){ + super("wood_league_wave_24_melee", + EntityType.ZOMBIE, + true, + "$normalLevel &4Arena Zombie", + "24"); + setFollowDistance(60); + setPowers(Arrays.asList("corpse.yml", "attack_fire.yml")); + setHelmet(new ItemStack(Material.LEATHER_HELMET)); + setChestplate(new ItemStack(Material.LEATHER_CHESTPLATE)); + setLeggings(new ItemStack(Material.LEATHER_LEGGINGS)); + setBoots(new ItemStack(Material.LEATHER_BOOTS)); + setMainHand(new ItemStack(Material.IRON_SWORD)); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave24Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave24Ranged.java new file mode 100644 index 000000000..427f0c5ba --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave24Ranged.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave24Ranged extends CustomBossesConfigFields { + public WoodLeagueWave24Ranged() { + super("wood_league_wave_24_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Arena Crossbowman", + "24"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.LEATHER_HELMET)); + setChestplate(new ItemStack(Material.LEATHER_CHESTPLATE)); + setLeggings(new ItemStack(Material.LEATHER_LEGGINGS)); + setBoots(new ItemStack(Material.LEATHER_BOOTS)); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("attack_vacuum.yml", "skeleton_tracking_arrow.yml")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave25Miniboss.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave25Miniboss.java new file mode 100644 index 000000000..e654ae8b5 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave25Miniboss.java @@ -0,0 +1,24 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave25Miniboss extends CustomBossesConfigFields { + public WoodLeagueWave25Miniboss() { + super("wood_league_wave_25_miniboss", + EntityType.PILLAGER, + true, + "$minibossLevel &bAgdluak", + "25"); + setPowers(Arrays.asList("frost_cone.yml", "attack_freeze.yml", "arrow_rain.yml")); + setHealthMultiplier(3D); + setDamageMultiplier(2D); + setFollowDistance(60); + setMovementSpeedAttribute(0.6D); + setMainHand(new ItemStack(Material.CROSSBOW)); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave26Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave26Melee.java new file mode 100644 index 000000000..40a087f19 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave26Melee.java @@ -0,0 +1,27 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave26Melee extends CustomBossesConfigFields { + public WoodLeagueWave26Melee(){ + super("wood_league_wave_26_melee", + EntityType.ZOMBIE, + true, + "$normalLevel &4Arena Zombie", + "26"); + setFollowDistance(60); + setPowers(Arrays.asList("corpse.yml", "attack_fire.yml")); + setHelmet(new ItemStack(Material.LEATHER_HELMET)); + setChestplate(new ItemStack(Material.LEATHER_CHESTPLATE)); + setLeggings(new ItemStack(Material.LEATHER_LEGGINGS)); + setBoots(new ItemStack(Material.LEATHER_BOOTS)); + setMainHand(new ItemStack(Material.IRON_SWORD)); + setDamageMultiplier(0.5D); + setHealthMultiplier(0.75D); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave26Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave26Ranged.java new file mode 100644 index 000000000..27ccc6fd0 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave26Ranged.java @@ -0,0 +1,27 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave26Ranged extends CustomBossesConfigFields { + public WoodLeagueWave26Ranged(){ + super("wood_league_wave_26_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Arena Crossbowman", + "26"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.LEATHER_HELMET)); + setChestplate(new ItemStack(Material.LEATHER_CHESTPLATE)); + setLeggings(new ItemStack(Material.LEATHER_LEGGINGS)); + setBoots(new ItemStack(Material.LEATHER_BOOTS)); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("attack_vacuum.yml", "skeleton_tracking_arrow.yml")); + setDamageMultiplier(0.5D); + setHealthMultiplier(0.75D); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave27Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave27Melee.java new file mode 100644 index 000000000..f3973aa1f --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave27Melee.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave27Melee extends CustomBossesConfigFields { + public WoodLeagueWave27Melee() { + super("wood_league_wave_27_melee", + EntityType.ZOMBIE, + true, + "$normalLevel &4Arena Zombie", + "27"); + setFollowDistance(60); + setPowers(Arrays.asList("corpse.yml", "attack_fire.yml", "invulnerability_arrow.yml")); + setHelmet(new ItemStack(Material.LEATHER_HELMET)); + setChestplate(new ItemStack(Material.LEATHER_CHESTPLATE)); + setLeggings(new ItemStack(Material.LEATHER_LEGGINGS)); + setBoots(new ItemStack(Material.LEATHER_BOOTS)); + setMainHand(new ItemStack(Material.IRON_SWORD)); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave27Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave27Ranged.java new file mode 100644 index 000000000..510dfdaa1 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave27Ranged.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave27Ranged extends CustomBossesConfigFields { + public WoodLeagueWave27Ranged(){ + super("wood_league_wave_27_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Arena Crossbowman", + "27"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.LEATHER_HELMET)); + setChestplate(new ItemStack(Material.LEATHER_CHESTPLATE)); + setLeggings(new ItemStack(Material.LEATHER_LEGGINGS)); + setBoots(new ItemStack(Material.LEATHER_BOOTS)); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("attack_freeze.yml", "skeleton_tracking_arrow.yml")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave28Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave28Melee.java new file mode 100644 index 000000000..2d49773fb --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave28Melee.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave28Melee extends CustomBossesConfigFields { + public WoodLeagueWave28Melee(){ + super("wood_league_wave_28_melee", + EntityType.ZOMBIE, + true, + "$normalLevel &4Arena Zombie", + "28"); + setFollowDistance(60); + setPowers(Arrays.asList("corpse.yml", "attack_fire.yml", "invulnerability_arrow.yml")); + setHelmet(new ItemStack(Material.LEATHER_HELMET)); + setChestplate(new ItemStack(Material.LEATHER_CHESTPLATE)); + setLeggings(new ItemStack(Material.LEATHER_LEGGINGS)); + setBoots(new ItemStack(Material.LEATHER_BOOTS)); + setMainHand(new ItemStack(Material.IRON_SWORD)); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave29Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave29Ranged.java new file mode 100644 index 000000000..cc137fec1 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave29Ranged.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave29Ranged extends CustomBossesConfigFields { + public WoodLeagueWave29Ranged(){ + super("wood_league_wave_29_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Arena Crossbowman", + "29"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.LEATHER_HELMET)); + setChestplate(new ItemStack(Material.LEATHER_CHESTPLATE)); + setLeggings(new ItemStack(Material.LEATHER_LEGGINGS)); + setBoots(new ItemStack(Material.LEATHER_BOOTS)); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("attack_freeze.yml", "skeleton_tracking_arrow.yml")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave2Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave2Melee.java new file mode 100644 index 000000000..db1e9aae7 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave2Melee.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +public class WoodLeagueWave2Melee extends CustomBossesConfigFields { + public WoodLeagueWave2Melee() { + super("wood_league_wave_2_melee", + EntityType.ZOMBIE, + true, + "$normalLevel Arena Zombie", + "2"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.STICK)); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave2Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave2Ranged.java new file mode 100644 index 000000000..9779a3442 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave2Ranged.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +public class WoodLeagueWave2Ranged extends CustomBossesConfigFields { + public WoodLeagueWave2Ranged(){ + super("wood_league_wave_2_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Arena Crossbowman", + "2"); + setMainHand(new ItemStack(Material.CROSSBOW)); + setFollowDistance(60); + setHelmet(new ItemStack(Material.STICK)); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave30Boss.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave30Boss.java new file mode 100644 index 000000000..c1279015a --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave30Boss.java @@ -0,0 +1,29 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave30Boss extends CustomBossesConfigFields { + public WoodLeagueWave30Boss() { + super("wood_league_wave_30_boss", + EntityType.SKELETON, + true, + "$bossLevel &2The Southern Viper", + "30"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.LEATHER_HELMET)); + setChestplate(new ItemStack(Material.LEATHER_CHESTPLATE)); + setLeggings(new ItemStack(Material.LEATHER_LEGGINGS)); + setBoots(new ItemStack(Material.LEATHER_BOOTS)); + setMainHand(new ItemStack(Material.BOW)); + setOffHand(new ItemStack(Material.TOTEM_OF_UNDYING)); + setPowers(Arrays.asList("attack_fire.yml", "attack_poison.yml", "shield_wall.yml", "attack_wither.yml", "skeleton_tracking_arrow.yml")); + setMovementSpeedAttribute(0.6D); + setHealthMultiplier(5D); + setDamageMultiplier(2D); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave31Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave31Melee.java new file mode 100644 index 000000000..cbd29bc94 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave31Melee.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave31Melee extends CustomBossesConfigFields { + public WoodLeagueWave31Melee(){ + super("wood_league_wave_31_melee", + EntityType.ZOMBIE, + true, + "$normalLevel &4Arena Zombie", + "31"); + setFollowDistance(60); + setPowers(Arrays.asList("corpse.yml", "attack_fire.yml", "invulnerability_arrow.yml")); + setHelmet(new ItemStack(Material.IRON_HELMET)); + setChestplate(new ItemStack(Material.IRON_CHESTPLATE)); + setLeggings(new ItemStack(Material.IRON_LEGGINGS)); + setBoots(new ItemStack(Material.IRON_BOOTS)); + setMainHand(new ItemStack(Material.GOLDEN_SWORD)); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave31Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave31Ranged.java new file mode 100644 index 000000000..a67b5f71d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave31Ranged.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave31Ranged extends CustomBossesConfigFields { + public WoodLeagueWave31Ranged() { + super("wood_league_wave_31_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Arena Crossbowman", + "31"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.IRON_HELMET)); + setChestplate(new ItemStack(Material.IRON_CHESTPLATE)); + setLeggings(new ItemStack(Material.IRON_LEGGINGS)); + setBoots(new ItemStack(Material.IRON_BOOTS)); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("attack_freeze.yml", "skeleton_tracking_arrow.yml")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave32Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave32Melee.java new file mode 100644 index 000000000..c12af4a3c --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave32Melee.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave32Melee extends CustomBossesConfigFields { + public WoodLeagueWave32Melee(){ + super("wood_league_wave_32_melee", + EntityType.ZOMBIE, + true, + "$normalLevel &4Arena Zombie", + "32"); + setFollowDistance(60); + setPowers(Arrays.asList("corpse.yml", "attack_fire.yml", "invulnerability_arrow.yml")); + setHelmet(new ItemStack(Material.IRON_HELMET)); + setChestplate(new ItemStack(Material.IRON_CHESTPLATE)); + setLeggings(new ItemStack(Material.IRON_LEGGINGS)); + setBoots(new ItemStack(Material.IRON_BOOTS)); + setMainHand(new ItemStack(Material.GOLDEN_SWORD)); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave32Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave32Ranged.java new file mode 100644 index 000000000..8d30acd51 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave32Ranged.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave32Ranged extends CustomBossesConfigFields { + public WoodLeagueWave32Ranged(){ + super("wood_league_wave_32_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Arena Crossbowman", + "32"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.IRON_HELMET)); + setChestplate(new ItemStack(Material.IRON_CHESTPLATE)); + setLeggings(new ItemStack(Material.IRON_LEGGINGS)); + setBoots(new ItemStack(Material.IRON_BOOTS)); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("attack_freeze.yml", "skeleton_tracking_arrow.yml")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave33Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave33Melee.java new file mode 100644 index 000000000..a3b6b5a8d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave33Melee.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave33Melee extends CustomBossesConfigFields { + public WoodLeagueWave33Melee(){ + super("wood_league_wave_33_melee", + EntityType.ZOMBIE, + true, + "$normalLevel &4Arena Zombie", + "33"); + setFollowDistance(60); + setPowers(Arrays.asList("corpse.yml", "attack_fire.yml", "invulnerability_arrow.yml", "attack_poison.yml")); + setHelmet(new ItemStack(Material.IRON_HELMET)); + setChestplate(new ItemStack(Material.IRON_CHESTPLATE)); + setLeggings(new ItemStack(Material.IRON_LEGGINGS)); + setBoots(new ItemStack(Material.IRON_BOOTS)); + setMainHand(new ItemStack(Material.GOLDEN_SWORD)); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave33Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave33Ranged.java new file mode 100644 index 000000000..380ea7098 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave33Ranged.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave33Ranged extends CustomBossesConfigFields { + public WoodLeagueWave33Ranged(){ + super("wood_league_wave_33_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Arena Crossbowman", + "33"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.IRON_HELMET)); + setChestplate(new ItemStack(Material.IRON_CHESTPLATE)); + setLeggings(new ItemStack(Material.IRON_LEGGINGS)); + setBoots(new ItemStack(Material.IRON_BOOTS)); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("attack_freeze.yml", "skeleton_tracking_arrow.yml", "attack_blinding.yml")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave34Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave34Melee.java new file mode 100644 index 000000000..c82445e0a --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave34Melee.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave34Melee extends CustomBossesConfigFields { + public WoodLeagueWave34Melee(){ + super("wood_league_wave_34_melee", + EntityType.ZOMBIE, + true, + "$normalLevel &4Arena Zombie", + "34"); + setFollowDistance(60); + setPowers(Arrays.asList("corpse.yml", "attack_fire.yml", "invulnerability_arrow.yml")); + setHelmet(new ItemStack(Material.IRON_HELMET)); + setChestplate(new ItemStack(Material.IRON_CHESTPLATE)); + setLeggings(new ItemStack(Material.IRON_LEGGINGS)); + setBoots(new ItemStack(Material.IRON_BOOTS)); + setMainHand(new ItemStack(Material.GOLDEN_SWORD)); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave34Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave34Ranged.java new file mode 100644 index 000000000..9cabe64c6 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave34Ranged.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave34Ranged extends CustomBossesConfigFields { + public WoodLeagueWave34Ranged(){ + super("wood_league_wave_34_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Arena Crossbowman", + "34"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.IRON_HELMET)); + setChestplate(new ItemStack(Material.IRON_CHESTPLATE)); + setLeggings(new ItemStack(Material.IRON_LEGGINGS)); + setBoots(new ItemStack(Material.IRON_BOOTS)); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("attack_freeze.yml", "skeleton_tracking_arrow.yml")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave35Miniboss.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave35Miniboss.java new file mode 100644 index 000000000..028952945 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave35Miniboss.java @@ -0,0 +1,24 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave35Miniboss extends CustomBossesConfigFields { + public WoodLeagueWave35Miniboss(){ + super("wood_league_wave_35_miniboss", + EntityType.VINDICATOR, + true, + "$minibossLevel &6The Jester", + "35"); + setPowers(Arrays.asList("attack_confusing.yml", "attack_push.yml", "attack_gravity.yml", "fireworks_barrage.yml", "arrow_fireworks.yml")); + setHealthMultiplier(3D); + setDamageMultiplier(2D); + setFollowDistance(60); + setMovementSpeedAttribute(0.6D); + setMainHand(new ItemStack(Material.GOLDEN_AXE)); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave36Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave36Melee.java new file mode 100644 index 000000000..72fac9d41 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave36Melee.java @@ -0,0 +1,27 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave36Melee extends CustomBossesConfigFields { + public WoodLeagueWave36Melee(){ + super("wood_league_wave_36_melee", + EntityType.ZOMBIE, + true, + "$normalLevel &4Arena Zombie", + "36"); + setFollowDistance(60); + setPowers(Arrays.asList("corpse.yml", "attack_fire.yml", "invulnerability_arrow.yml")); + setHelmet(new ItemStack(Material.IRON_HELMET)); + setChestplate(new ItemStack(Material.IRON_CHESTPLATE)); + setLeggings(new ItemStack(Material.IRON_LEGGINGS)); + setBoots(new ItemStack(Material.IRON_BOOTS)); + setMainHand(new ItemStack(Material.GOLDEN_SWORD)); + setDamageMultiplier(0.5D); + setHealthMultiplier(0.75D); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave36Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave36Ranged.java new file mode 100644 index 000000000..bf737166e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave36Ranged.java @@ -0,0 +1,27 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave36Ranged extends CustomBossesConfigFields { + public WoodLeagueWave36Ranged(){ + super("wood_league_wave_36_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Arena Crossbowman", + "36"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.IRON_HELMET)); + setChestplate(new ItemStack(Material.IRON_CHESTPLATE)); + setLeggings(new ItemStack(Material.IRON_LEGGINGS)); + setBoots(new ItemStack(Material.IRON_BOOTS)); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("attack_freeze.yml", "skeleton_tracking_arrow.yml")); + setDamageMultiplier(0.5D); + setHealthMultiplier(0.75D); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave37Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave37Melee.java new file mode 100644 index 000000000..dd51c9e6e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave37Melee.java @@ -0,0 +1,26 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave37Melee extends CustomBossesConfigFields { + public WoodLeagueWave37Melee(){ + super("wood_league_wave_37_melee", + EntityType.ZOMBIE, + true, + "$normalLevel &4Arena Zombie", + "37"); + setFollowDistance(60); + setPowers(Arrays.asList("corpse.yml", "attack_fire.yml", "invulnerability_arrow.yml")); + setHelmet(new ItemStack(Material.IRON_HELMET)); + setChestplate(new ItemStack(Material.IRON_CHESTPLATE)); + setLeggings(new ItemStack(Material.IRON_LEGGINGS)); + setBoots(new ItemStack(Material.IRON_BOOTS)); + setMainHand(new ItemStack(Material.GOLDEN_SWORD)); + setMovementSpeedAttribute(0.3D); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave37Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave37Ranged.java new file mode 100644 index 000000000..5a906ecc7 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave37Ranged.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave37Ranged extends CustomBossesConfigFields { + public WoodLeagueWave37Ranged(){ + super("wood_league_wave_37_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Arena Crossbowman", + "37"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.IRON_HELMET)); + setChestplate(new ItemStack(Material.IRON_CHESTPLATE)); + setLeggings(new ItemStack(Material.IRON_LEGGINGS)); + setBoots(new ItemStack(Material.IRON_BOOTS)); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("attack_freeze.yml", "skeleton_tracking_arrow.yml", "shield_wall.yml")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave38Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave38Melee.java new file mode 100644 index 000000000..352824215 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave38Melee.java @@ -0,0 +1,26 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave38Melee extends CustomBossesConfigFields { + public WoodLeagueWave38Melee(){ + super("wood_league_wave_38_melee", + EntityType.ZOMBIE, + true, + "$normalLevel &4Arena Swordsman", + "38"); + setFollowDistance(60); + setPowers(Arrays.asList("corpse.yml", "attack_fire.yml", "invulnerability_arrow.yml")); + setHelmet(new ItemStack(Material.IRON_HELMET)); + setChestplate(new ItemStack(Material.IRON_CHESTPLATE)); + setLeggings(new ItemStack(Material.IRON_LEGGINGS)); + setBoots(new ItemStack(Material.IRON_BOOTS)); + setMainHand(new ItemStack(Material.GOLDEN_SWORD)); + setMovementSpeedAttribute(0.3D); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave39Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave39Ranged.java new file mode 100644 index 000000000..622f437c4 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave39Ranged.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave39Ranged extends CustomBossesConfigFields { + public WoodLeagueWave39Ranged(){ + super("wood_league_wave_39_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Arena Archer", + "39"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.IRON_HELMET)); + setChestplate(new ItemStack(Material.IRON_CHESTPLATE)); + setLeggings(new ItemStack(Material.IRON_LEGGINGS)); + setBoots(new ItemStack(Material.IRON_BOOTS)); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("attack_freeze.yml", "skeleton_tracking_arrow.yml", "shield_wall.yml")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave3Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave3Melee.java new file mode 100644 index 000000000..6fff07cc9 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave3Melee.java @@ -0,0 +1,21 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave3Melee extends CustomBossesConfigFields { + public WoodLeagueWave3Melee() { + super("wood_league_wave_3_melee", + EntityType.ZOMBIE, + true, + "$normalLevel Arena Zombie", + "3"); + setPowers(Arrays.asList("attack_fire.yml")); + setFollowDistance(60); + setHelmet(new ItemStack(Material.STICK)); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave3Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave3Ranged.java new file mode 100644 index 000000000..cb3e5f869 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave3Ranged.java @@ -0,0 +1,21 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave3Ranged extends CustomBossesConfigFields { + public WoodLeagueWave3Ranged() { + super("wood_league_wave_3_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Arena Crossbowman", + "3"); + setMainHand(new ItemStack(Material.CROSSBOW)); + setFollowDistance(60); + setPowers(Arrays.asList("attack_fire.yml")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave40Boss.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave40Boss.java new file mode 100644 index 000000000..832c63869 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave40Boss.java @@ -0,0 +1,29 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave40Boss extends CustomBossesConfigFields { + public WoodLeagueWave40Boss(){ + super("wood_league_wave_40_boss", + EntityType.SKELETON, + true, + "$bossLevel &cCrucio the Bearer of Curses", + "40"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.DIAMOND_HELMET)); + setChestplate(new ItemStack(Material.DIAMOND_CHESTPLATE)); + setLeggings(new ItemStack(Material.DIAMOND_LEGGINGS)); + setBoots(new ItemStack(Material.DIAMOND_BOOTS)); + setMainHand(new ItemStack(Material.DIAMOND_SWORD)); + setOffHand(new ItemStack(Material.SHIELD)); + setPowers(Arrays.asList("attack_wither.yml", "attack_poison.yml", "shield_wall.yml", "bullet_hell.yml", "skeleton_tracking_arrow.yml", "flame_pyre.yml")); + setMovementSpeedAttribute(0.6D); + setHealthMultiplier(5D); + setDamageMultiplier(2D); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave41Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave41Melee.java new file mode 100644 index 000000000..0b8c41a64 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave41Melee.java @@ -0,0 +1,26 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave41Melee extends CustomBossesConfigFields { + public WoodLeagueWave41Melee(){ + super("wood_league_wave_41_melee", + EntityType.ZOMBIE, + true, + "$normalLevel &4Arena Zombie", + "41"); + setFollowDistance(60); + setPowers(Arrays.asList("corpse.yml", "attack_fire.yml", "invulnerability_arrow.yml")); + setHelmet(new ItemStack(Material.DIAMOND_HELMET)); + setChestplate(new ItemStack(Material.DIAMOND_CHESTPLATE)); + setLeggings(new ItemStack(Material.DIAMOND_LEGGINGS)); + setBoots(new ItemStack(Material.DIAMOND_BOOTS)); + setMainHand(new ItemStack(Material.GOLDEN_SWORD)); + setMovementSpeedAttribute(0.3D); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave41Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave41Ranged.java new file mode 100644 index 000000000..82e580943 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave41Ranged.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave41Ranged extends CustomBossesConfigFields { + public WoodLeagueWave41Ranged(){ + super("wood_league_wave_41_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Arena Crossbowman", + "41"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.DIAMOND_HELMET)); + setChestplate(new ItemStack(Material.DIAMOND_CHESTPLATE)); + setLeggings(new ItemStack(Material.DIAMOND_LEGGINGS)); + setBoots(new ItemStack(Material.DIAMOND_BOOTS)); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("attack_freeze.yml", "skeleton_tracking_arrow.yml", "shield_wall.yml")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave42Healer.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave42Healer.java new file mode 100644 index 000000000..6e992f4c8 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave42Healer.java @@ -0,0 +1,22 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave42Healer extends CustomBossesConfigFields { + public WoodLeagueWave42Healer(){ + super("wood_league_wave_42_healer", + EntityType.PILLAGER, + true, + "$normalLevel Arena Healer", + "42"); + setFollowDistance(60); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("channel_healing.yml")); + setHealthMultiplier(.5D); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave42Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave42Melee.java new file mode 100644 index 000000000..5197d5306 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave42Melee.java @@ -0,0 +1,26 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave42Melee extends CustomBossesConfigFields { + public WoodLeagueWave42Melee() { + super("wood_league_wave_42_melee", + EntityType.ZOMBIE, + true, + "$normalLevel &4Arena Zombie", + "42"); + setFollowDistance(60); + setPowers(Arrays.asList("corpse.yml", "attack_fire.yml", "invulnerability_arrow.yml")); + setHelmet(new ItemStack(Material.DIAMOND_HELMET)); + setChestplate(new ItemStack(Material.DIAMOND_CHESTPLATE)); + setLeggings(new ItemStack(Material.DIAMOND_LEGGINGS)); + setBoots(new ItemStack(Material.DIAMOND_BOOTS)); + setMainHand(new ItemStack(Material.DIAMOND_SWORD)); + setMovementSpeedAttribute(0.3D); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave42Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave42Ranged.java new file mode 100644 index 000000000..c4cead483 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave42Ranged.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave42Ranged extends CustomBossesConfigFields { + public WoodLeagueWave42Ranged(){ + super("wood_league_wave_42_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Arena Crossbowman", + "42"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.DIAMOND_HELMET)); + setChestplate(new ItemStack(Material.DIAMOND_CHESTPLATE)); + setLeggings(new ItemStack(Material.DIAMOND_LEGGINGS)); + setBoots(new ItemStack(Material.DIAMOND_BOOTS)); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("attack_freeze.yml", "skeleton_tracking_arrow.yml", "shield_wall.yml")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave43Healer.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave43Healer.java new file mode 100644 index 000000000..4ba635c24 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave43Healer.java @@ -0,0 +1,22 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave43Healer extends CustomBossesConfigFields { + public WoodLeagueWave43Healer(){ + super("wood_league_wave_43_healer", + EntityType.PILLAGER, + true, + "$normalLevel Arena Healer", + "43"); + setFollowDistance(60); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("channel_healing.yml")); + setHealthMultiplier(.5D); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave43Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave43Melee.java new file mode 100644 index 000000000..b0609ffd0 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave43Melee.java @@ -0,0 +1,26 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave43Melee extends CustomBossesConfigFields { + public WoodLeagueWave43Melee(){ + super("wood_league_wave_43_melee", + EntityType.ZOMBIE, + true, + "$normalLevel &4Arena Zombie", + "43"); + setFollowDistance(60); + setPowers(Arrays.asList("corpse.yml", "attack_fire.yml", "invulnerability_arrow.yml", "attack_poison.yml")); + setHelmet(new ItemStack(Material.DIAMOND_HELMET)); + setChestplate(new ItemStack(Material.DIAMOND_CHESTPLATE)); + setLeggings(new ItemStack(Material.DIAMOND_LEGGINGS)); + setBoots(new ItemStack(Material.DIAMOND_BOOTS)); + setMainHand(new ItemStack(Material.DIAMOND_SWORD)); + setMovementSpeedAttribute(0.3D); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave43Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave43Ranged.java new file mode 100644 index 000000000..d8a479361 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave43Ranged.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave43Ranged extends CustomBossesConfigFields { + public WoodLeagueWave43Ranged(){ + super("wood_league_wave_43_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Arena Crossbowman", + "43"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.DIAMOND_HELMET)); + setChestplate(new ItemStack(Material.DIAMOND_CHESTPLATE)); + setLeggings(new ItemStack(Material.DIAMOND_LEGGINGS)); + setBoots(new ItemStack(Material.DIAMOND_BOOTS)); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("attack_freeze.yml", "skeleton_tracking_arrow.yml", "shield_wall.yml", "attack_wither.yml")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave44Healer.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave44Healer.java new file mode 100644 index 000000000..7e2ebfdc4 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave44Healer.java @@ -0,0 +1,22 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave44Healer extends CustomBossesConfigFields { + public WoodLeagueWave44Healer(){ + super("wood_league_wave_44_healer", + EntityType.PILLAGER, + true, + "$normalLevel Arena Healer", + "44"); + setFollowDistance(60); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("channel_healing.yml")); + setHealthMultiplier(.5D); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave44Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave44Melee.java new file mode 100644 index 000000000..d1365f9b2 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave44Melee.java @@ -0,0 +1,26 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave44Melee extends CustomBossesConfigFields { + public WoodLeagueWave44Melee(){ + super("wood_league_wave_44_melee", + EntityType.ZOMBIE, + true, + "$normalLevel &4Arena Zombie", + "44"); + setFollowDistance(60); + setPowers(Arrays.asList("corpse.yml", "attack_fire.yml", "invulnerability_arrow.yml")); + setHelmet(new ItemStack(Material.DIAMOND_HELMET)); + setChestplate(new ItemStack(Material.DIAMOND_CHESTPLATE)); + setLeggings(new ItemStack(Material.DIAMOND_LEGGINGS)); + setBoots(new ItemStack(Material.DIAMOND_BOOTS)); + setMainHand(new ItemStack(Material.DIAMOND_SWORD)); + setMovementSpeedAttribute(0.3D); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave44Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave44Ranged.java new file mode 100644 index 000000000..583f251a6 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave44Ranged.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave44Ranged extends CustomBossesConfigFields { + public WoodLeagueWave44Ranged(){ + super("wood_league_wave_44_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Arena Crossbowman", + "44"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.DIAMOND_HELMET)); + setChestplate(new ItemStack(Material.DIAMOND_CHESTPLATE)); + setLeggings(new ItemStack(Material.DIAMOND_LEGGINGS)); + setBoots(new ItemStack(Material.DIAMOND_BOOTS)); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("attack_freeze.yml", "skeleton_tracking_arrow.yml", "shield_wall.yml")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave45Miniboss.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave45Miniboss.java new file mode 100644 index 000000000..69939689e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave45Miniboss.java @@ -0,0 +1,24 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave45Miniboss extends CustomBossesConfigFields { + public WoodLeagueWave45Miniboss(){ + super("wood_league_wave_45_miniboss", + EntityType.VINDICATOR, + true, + "$minibossLevel &6Thousand Blades", + "45"); + setPowers(Arrays.asList("attack_arrow.yml", "arrow_rain.yml", "arrow_fireworks.yml", "attack_fireball.yml", "bullet_hell.yml", "meteor_shower.yml")); + setHealthMultiplier(3D); + setDamageMultiplier(2D); + setFollowDistance(60); + setMovementSpeedAttribute(0.6D); + setMainHand(new ItemStack(Material.GOLDEN_AXE)); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave46Healer.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave46Healer.java new file mode 100644 index 000000000..fbb5cae12 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave46Healer.java @@ -0,0 +1,24 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave46Healer extends CustomBossesConfigFields { + public WoodLeagueWave46Healer(){ + super("wood_league_wave_46_healer", + EntityType.PILLAGER, + true, + "$normalLevel Arena Healer", + "46"); + setFollowDistance(60); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("channel_healing.yml")); + setDamageMultiplier(0.5D); + setHealthMultiplier(0.75D); + setHealthMultiplier(.5D); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave46Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave46Melee.java new file mode 100644 index 000000000..f452653bb --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave46Melee.java @@ -0,0 +1,28 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave46Melee extends CustomBossesConfigFields { + public WoodLeagueWave46Melee(){ + super("wood_league_wave_46_melee", + EntityType.ZOMBIE, + true, + "$normalLevel &4Arena Zombie", + "46"); + setFollowDistance(60); + setPowers(Arrays.asList("corpse.yml", "attack_fire.yml", "invulnerability_arrow.yml")); + setHelmet(new ItemStack(Material.DIAMOND_HELMET)); + setChestplate(new ItemStack(Material.DIAMOND_CHESTPLATE)); + setLeggings(new ItemStack(Material.DIAMOND_LEGGINGS)); + setBoots(new ItemStack(Material.DIAMOND_BOOTS)); + setMainHand(new ItemStack(Material.DIAMOND_SWORD)); + setMovementSpeedAttribute(0.3D); + setDamageMultiplier(0.5D); + setHealthMultiplier(0.75D); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave46Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave46Ranged.java new file mode 100644 index 000000000..8442e477a --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave46Ranged.java @@ -0,0 +1,27 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave46Ranged extends CustomBossesConfigFields { + public WoodLeagueWave46Ranged(){ + super("wood_league_wave_46_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Arena Crossbowman", + "46"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.DIAMOND_HELMET)); + setChestplate(new ItemStack(Material.DIAMOND_CHESTPLATE)); + setLeggings(new ItemStack(Material.DIAMOND_LEGGINGS)); + setBoots(new ItemStack(Material.DIAMOND_BOOTS)); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("attack_freeze.yml", "skeleton_tracking_arrow.yml", "shield_wall.yml")); + setDamageMultiplier(0.5D); + setHealthMultiplier(0.75D); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave47Healer.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave47Healer.java new file mode 100644 index 000000000..b0352a7c5 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave47Healer.java @@ -0,0 +1,22 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave47Healer extends CustomBossesConfigFields { + public WoodLeagueWave47Healer(){ + super("wood_league_wave_47_healer", + EntityType.PILLAGER, + true, + "$normalLevel Arena Healer", + "47"); + setFollowDistance(60); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("channel_healing.yml")); + setHealthMultiplier(.5D); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave47Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave47Melee.java new file mode 100644 index 000000000..4de8807b7 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave47Melee.java @@ -0,0 +1,26 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave47Melee extends CustomBossesConfigFields { + public WoodLeagueWave47Melee(){ + super("wood_league_wave_47_melee", + EntityType.ZOMBIE, + true, + "$normalLevel &4Arena Zombie", + "47"); + setFollowDistance(60); + setPowers(Arrays.asList("corpse.yml", "attack_fire.yml", "invulnerability_arrow.yml")); + setHelmet(new ItemStack(Material.DIAMOND_HELMET)); + setChestplate(new ItemStack(Material.DIAMOND_CHESTPLATE)); + setLeggings(new ItemStack(Material.DIAMOND_LEGGINGS)); + setBoots(new ItemStack(Material.DIAMOND_BOOTS)); + setMainHand(new ItemStack(Material.DIAMOND_SWORD)); + setMovementSpeedAttribute(0.3D); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave47Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave47Ranged.java new file mode 100644 index 000000000..f98692495 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave47Ranged.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave47Ranged extends CustomBossesConfigFields { + public WoodLeagueWave47Ranged(){ + super("wood_league_wave_47_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Arena Crossbowman", + "47"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.DIAMOND_HELMET)); + setChestplate(new ItemStack(Material.DIAMOND_CHESTPLATE)); + setLeggings(new ItemStack(Material.DIAMOND_LEGGINGS)); + setBoots(new ItemStack(Material.DIAMOND_BOOTS)); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("attack_freeze.yml", "skeleton_tracking_arrow.yml", "shield_wall.yml")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave48Healer.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave48Healer.java new file mode 100644 index 000000000..8901a498d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave48Healer.java @@ -0,0 +1,22 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave48Healer extends CustomBossesConfigFields { + public WoodLeagueWave48Healer(){ + super("wood_league_wave_48_healer", + EntityType.PILLAGER, + true, + "$normalLevel Arena Healer", + "48"); + setFollowDistance(60); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("channel_healing.yml")); + setHealthMultiplier(.5D); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave48Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave48Melee.java new file mode 100644 index 000000000..ff5670d21 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave48Melee.java @@ -0,0 +1,26 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave48Melee extends CustomBossesConfigFields { + public WoodLeagueWave48Melee(){ + super("wood_league_wave_48_melee", + EntityType.ZOMBIE, + true, + "$normalLevel &4Arena Zombie", + "48"); + setFollowDistance(60); + setPowers(Arrays.asList("corpse.yml", "attack_fire.yml", "invulnerability_arrow.yml")); + setHelmet(new ItemStack(Material.DIAMOND_HELMET)); + setChestplate(new ItemStack(Material.DIAMOND_CHESTPLATE)); + setLeggings(new ItemStack(Material.DIAMOND_LEGGINGS)); + setBoots(new ItemStack(Material.DIAMOND_BOOTS)); + setMainHand(new ItemStack(Material.DIAMOND_SWORD)); + setMovementSpeedAttribute(0.3D); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave49Healer.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave49Healer.java new file mode 100644 index 000000000..63a6cb2b0 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave49Healer.java @@ -0,0 +1,22 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave49Healer extends CustomBossesConfigFields { + public WoodLeagueWave49Healer(){ + super("wood_league_wave_49_healer", + EntityType.PILLAGER, + true, + "$normalLevel Arena Healer", + "49"); + setFollowDistance(60); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("channel_healing.yml")); + setHealthMultiplier(.5D); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave49Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave49Ranged.java new file mode 100644 index 000000000..5d92daeb2 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave49Ranged.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave49Ranged extends CustomBossesConfigFields { + public WoodLeagueWave49Ranged(){ + super("wood_league_wave_49_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Arena Crossbowman", + "49"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.DIAMOND_HELMET)); + setChestplate(new ItemStack(Material.DIAMOND_CHESTPLATE)); + setLeggings(new ItemStack(Material.DIAMOND_LEGGINGS)); + setBoots(new ItemStack(Material.DIAMOND_BOOTS)); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("attack_freeze.yml", "skeleton_tracking_arrow.yml", "shield_wall.yml")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave4Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave4Melee.java new file mode 100644 index 000000000..f9e79ee04 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave4Melee.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +public class WoodLeagueWave4Melee extends CustomBossesConfigFields { + public WoodLeagueWave4Melee(){ + super("wood_league_wave_4_melee", + EntityType.ZOMBIE, + true, + "$normalLevel Arena Zombie", + "4"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.STICK)); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave4Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave4Ranged.java new file mode 100644 index 000000000..2f3a1cedc --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave4Ranged.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +public class WoodLeagueWave4Ranged extends CustomBossesConfigFields { + public WoodLeagueWave4Ranged(){ + super("wood_league_wave_4_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Arena Crossbowman", + "4"); + setMainHand(new ItemStack(Material.CROSSBOW)); + setFollowDistance(60); + setHelmet(new ItemStack(Material.STICK)); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave50Boss.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave50Boss.java new file mode 100644 index 000000000..b7eae6e7d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave50Boss.java @@ -0,0 +1,36 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import com.magmaguy.elitemobs.utils.VersionChecker; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.Arrays; + +public class WoodLeagueWave50Boss extends CustomBossesConfigFields { + public WoodLeagueWave50Boss() { + super("wood_league_wave_50_boss", + EntityType.WITHER_SKELETON, + true, + "$bossLevel &6Uther the Champion", + "50"); + setFollowDistance(60); + if (!VersionChecker.serverVersionOlderThan(16, 0)) + setMainHand(new ItemStack(Material.NETHERITE_AXE)); + setOffHand(new ItemStack(Material.SHIELD)); + setPowers(Arrays.asList("ground_pound.yml", + "shield_wall.yml", + "bullet_hell.yml", + "arrow_fireworks.yml", + "fireworks_barrage.yml", + "summonable:summonType=ON_COMBAT_ENTER:filename=wood_league_wave_50_reinforcement.yml:amount=2")); + setMovementSpeedAttribute(0.4D); + setHealthMultiplier(10D); + setDamageMultiplier(1D); + setPhases(new ArrayList<>(Arrays.asList( + "wood_league_wave_50_boss_p2.yml:0.66", + "wood_league_wave_50_boss_p3.yml:0.33"))); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave50BossP2.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave50BossP2.java new file mode 100644 index 000000000..a7e30f4c2 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave50BossP2.java @@ -0,0 +1,32 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import com.magmaguy.elitemobs.utils.VersionChecker; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave50BossP2 extends CustomBossesConfigFields { + public WoodLeagueWave50BossP2(){ + super("wood_league_wave_50_boss_p2", + EntityType.WITHER_SKELETON, + true, + "$bossLevel &6Uther the Champion", + "50"); + setFollowDistance(60); + if (!VersionChecker.serverVersionOlderThan(16, 0)) + setMainHand(new ItemStack(Material.NETHERITE_AXE)); + setOffHand(new ItemStack(Material.SHIELD)); + setPowers(Arrays.asList("firestorm.yml", + "flame_pyre.yml", + "flamethrower.yml", + "death_slice.yml", + "firestorm.yml", + "summonable:summonType=ON_COMBAT_ENTER:filename=wood_league_wave_50_reinforcement.yml:amount=2")); + setMovementSpeedAttribute(0.5D); + setHealthMultiplier(10D); + setDamageMultiplier(1D); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave50BossP3.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave50BossP3.java new file mode 100644 index 000000000..9f8462aea --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave50BossP3.java @@ -0,0 +1,32 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import com.magmaguy.elitemobs.utils.VersionChecker; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave50BossP3 extends CustomBossesConfigFields { + public WoodLeagueWave50BossP3() { + super("wood_league_wave_50_boss_p3", + EntityType.WITHER_SKELETON, + true, + "$bossLevel &6Uther the Champion", + "50"); + setFollowDistance(60); + if (!VersionChecker.serverVersionOlderThan(16, 0)) + setMainHand(new ItemStack(Material.NETHERITE_AXE)); + setOffHand(new ItemStack(Material.SHIELD)); + setPowers(Arrays.asList("attack_lightning.yml", + "lightning_bolts.yml", + "gold_explosion.yml", + "photon_ray.yml", + "thunderstorm.yml", + "summonable:summonType=ON_COMBAT_ENTER:filename=wood_league_wave_50_reinforcement.yml:amount=2")); + setMovementSpeedAttribute(0.6D); + setHealthMultiplier(10D); + setDamageMultiplier(1D); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave50Reinforcement.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave50Reinforcement.java new file mode 100644 index 000000000..2692eb3e2 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave50Reinforcement.java @@ -0,0 +1,28 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave50Reinforcement extends CustomBossesConfigFields { + public WoodLeagueWave50Reinforcement(){ + super("wood_league_wave_50_reinforcement", + EntityType.PILLAGER, + true, + "$reinforcementLevel &6Uther Stan", + "50"); + setFollowDistance(60); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("channel_healing.yml")); + setMovementSpeedAttribute(0.6D); + setHealthMultiplier(0.25D); + setDamageMultiplier(0.8D); + setDropsRandomLoot(false); + setDropsEliteMobsLoot(false); + setDropsVanillaLoot(false); + setNormalizedCombat(true); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave5Miniboss.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave5Miniboss.java new file mode 100644 index 000000000..022f9ed6e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave5Miniboss.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave5Miniboss extends CustomBossesConfigFields { + public WoodLeagueWave5Miniboss() { + super("wood_league_wave_5_miniboss", + EntityType.RAVAGER, + true, + "$minibossLevel &cWeird Cow", + "5"); + setPowers(Arrays.asList("attack_push.yml", "attack_gravity.yml")); + setOnDamagedMessages(Arrays.asList("Woof!")); + setHealthMultiplier(3D); + setDamageMultiplier(2D); + setFollowDistance(60); + setMovementSpeedAttribute(0.6D); + setHelmet(new ItemStack(Material.STICK)); + } +} \ No newline at end of file diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave6Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave6Melee.java new file mode 100644 index 000000000..84a7c18f1 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave6Melee.java @@ -0,0 +1,20 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +public class WoodLeagueWave6Melee extends CustomBossesConfigFields { + public WoodLeagueWave6Melee() { + super("wood_league_wave_6_melee", + EntityType.ZOMBIE, + true, + "$normalLevel Arena Zombie", + "6"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.STICK)); + setDamageMultiplier(0.5D); + setHealthMultiplier(0.75D); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave6Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave6Ranged.java new file mode 100644 index 000000000..8d990c0a0 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave6Ranged.java @@ -0,0 +1,21 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +public class WoodLeagueWave6Ranged extends CustomBossesConfigFields { + public WoodLeagueWave6Ranged(){ + super("wood_league_wave_6_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Arena Crossbowman", + "6"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.STICK)); + setMainHand(new ItemStack(Material.CROSSBOW)); + setDamageMultiplier(0.5D); + setHealthMultiplier(0.75D); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave7Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave7Melee.java new file mode 100644 index 000000000..f8f088c9b --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave7Melee.java @@ -0,0 +1,21 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave7Melee extends CustomBossesConfigFields { + public WoodLeagueWave7Melee(){ + super("wood_league_wave_7_melee", + EntityType.ZOMBIE, + true, + "$normalLevel Arena Zombie", + "7"); + setFollowDistance(60); + setPowers(Arrays.asList("corpse.yml")); + setHelmet(new ItemStack(Material.STICK)); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave7Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave7Ranged.java new file mode 100644 index 000000000..3ed8ec08c --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave7Ranged.java @@ -0,0 +1,22 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave7Ranged extends CustomBossesConfigFields { + public WoodLeagueWave7Ranged() { + super("wood_league_wave_7_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Arena Crossbowman", + "7"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.STICK)); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("attack_vacuum.yml")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave8Melee.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave8Melee.java new file mode 100644 index 000000000..2ee7bf93c --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave8Melee.java @@ -0,0 +1,21 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave8Melee extends CustomBossesConfigFields { + public WoodLeagueWave8Melee(){ + super("wood_league_wave_8_melee", + EntityType.ZOMBIE, + true, + "$normalLevel Arena Zombie", + "8"); + setFollowDistance(60); + setPowers(Arrays.asList("corpse.yml")); + setHelmet(new ItemStack(Material.STICK)); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave9Ranged.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave9Ranged.java new file mode 100644 index 000000000..a5ac6481d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/WoodLeagueWave9Ranged.java @@ -0,0 +1,22 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class WoodLeagueWave9Ranged extends CustomBossesConfigFields { + public WoodLeagueWave9Ranged(){ + super("wood_league_wave_9_ranged", + EntityType.PILLAGER, + true, + "$normalLevel Arena Crossbowman", + "9"); + setFollowDistance(60); + setHelmet(new ItemStack(Material.STICK)); + setMainHand(new ItemStack(Material.CROSSBOW)); + setPowers(Arrays.asList("attack_vacuum.yml")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/ZombieDadConfig.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/ZombieDadConfig.java new file mode 100644 index 000000000..ed597add0 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/ZombieDadConfig.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.entity.EntityType; + +public class ZombieDadConfig extends CustomBossesConfigFields { + public ZombieDadConfig() { + super("zombie_parents_dad", + EntityType.SKELETON, + true, + "$reinforcementLevel &7Zombie Dad", + "dynamic"); + setHealthMultiplier(0.5); + setDamageMultiplier(0.5); + setDropsVanillaLoot(false); + setDropsEliteMobsLoot(false); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/ZombieFriendConfig.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/ZombieFriendConfig.java new file mode 100644 index 000000000..50cacd3d6 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/ZombieFriendConfig.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.entity.EntityType; + +public class ZombieFriendConfig extends CustomBossesConfigFields { + public ZombieFriendConfig() { + super("zombie_friends_friend", + EntityType.ZOMBIE, + true, + "$reinforcementLevel &7Zombie Friend", + "dynamic"); + setHealthMultiplier(0.5); + setDamageMultiplier(0.5); + setDropsVanillaLoot(false); + setDropsEliteMobsLoot(false); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/ZombieKingBoss.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/ZombieKingBoss.java new file mode 100644 index 000000000..eea119d70 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/ZombieKingBoss.java @@ -0,0 +1,38 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.Material; +import org.bukkit.Particle; +import org.bukkit.entity.EntityType; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; +import java.util.Collections; + +public class ZombieKingBoss extends CustomBossesConfigFields { + public ZombieKingBoss() { + super("zombie_king", + EntityType.ZOMBIE, + true, + "$eventBossLevel &4Zombie King", + "dynamic"); + setPersistent(true); + setHealthMultiplier(4); + setDamageMultiplier(4); + setHelmet(new ItemStack(Material.DIAMOND_HELMET)); + setChestplate(new ItemStack(Material.DIAMOND_CHESTPLATE)); + setLeggings(new ItemStack(Material.DIAMOND_LEGGINGS)); + setBoots(new ItemStack(Material.DIAMOND_BOOTS)); + setMainHand(new ItemStack(Material.GOLDEN_AXE)); + setPowers(Arrays.asList("flame_pyre.yml", "flamethrower.yml", "summon_the_returned.yml", "spirit_walk.yml", + "summonable:summonType=GLOBAL:filename=the_living_dead.yml:amount=5:customSpawn=normal_surface_spawn.yml")); + setSpawnMessage("&cThe Zombie King has been sighted!"); + setDeathMessage("&aThe Zombie King has been slain by $players!"); + majorBossDeathString("The Zombie King has been slain!"); + setEscapeMessage("&4The Zombie King has escaped!"); + setLocationMessage("&cZombie King: $distance blocks away!"); + setUniqueLootList(Collections.singletonList("zombie_kings_axe.yml:1")); + setTrails(Collections.singletonList(Particle.FLAME.toString())); + setAnnouncementPriority(2); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/ZombieMomConfig.java b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/ZombieMomConfig.java new file mode 100644 index 000000000..82ea4c632 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/custombosses/premade/ZombieMomConfig.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.config.custombosses.premade; + +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import org.bukkit.entity.EntityType; + +public class ZombieMomConfig extends CustomBossesConfigFields { + public ZombieMomConfig() { + super("zombie_parents_mom", + EntityType.SKELETON, + true, + "$reinforcementLevel &7Zombie Mom", + "dynamic"); + setHealthMultiplier(0.5); + setDamageMultiplier(0.5); + setDropsVanillaLoot(false); + setDropsEliteMobsLoot(false); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customevents/CustomEventsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customevents/CustomEventsConfig.java new file mode 100644 index 000000000..b839953b2 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customevents/CustomEventsConfig.java @@ -0,0 +1,27 @@ +package com.magmaguy.elitemobs.config.customevents; + +import com.magmaguy.elitemobs.config.CustomConfig; + +import java.util.HashMap; + +public class CustomEventsConfig extends CustomConfig { + + private static HashMap customEvents; + + public CustomEventsConfig() { + super("customevents", "com.magmaguy.elitemobs.config.customevents.premade", CustomEventsConfigFields.class); + customEvents = new HashMap<>(); + for (String key : super.getCustomConfigFieldsHashMap().keySet()) + if (super.getCustomConfigFieldsHashMap().get(key).isEnabled()) + customEvents.put(key, (CustomEventsConfigFields) super.getCustomConfigFieldsHashMap().get(key)); + } + + public static HashMap getCustomEvents() { + return customEvents; + } + + public static CustomEventsConfigFields getCustomEvent(String fileName) { + return customEvents.get(fileName); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customevents/CustomEventsConfigFields.java b/src/main/java/com/magmaguy/elitemobs/config/customevents/CustomEventsConfigFields.java new file mode 100644 index 000000000..dcad7e6ad --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customevents/CustomEventsConfigFields.java @@ -0,0 +1,99 @@ +package com.magmaguy.elitemobs.config.customevents; + +import com.magmaguy.elitemobs.config.CustomConfigFields; +import com.magmaguy.elitemobs.config.CustomConfigFieldsInterface; +import com.magmaguy.elitemobs.events.CustomEvent; +import com.magmaguy.elitemobs.utils.WarningMessage; +import lombok.Getter; +import lombok.Setter; +import org.bukkit.Material; + +import java.util.ArrayList; +import java.util.List; + +public class CustomEventsConfigFields extends CustomConfigFields implements CustomConfigFieldsInterface { + + @Getter + @Setter + private CustomEvent.EventType eventType = CustomEvent.EventType.DEFAULT; + @Getter + @Setter + private List bossFilenames = new ArrayList<>(); + @Getter + @Setter + private String startMessage; + @Getter + @Setter + private String endMessage; + @Getter + @Setter + private List eventStartCommands = new ArrayList<>(); + @Getter + @Setter + private List eventEndCommands = new ArrayList<>(); + @Getter + @Setter + private int announcementPriority = 0; + @Getter + @Setter + private double chance = 0; + @Getter + @Setter + private List breakableMaterials = new ArrayList<>(); + @Getter + @Setter + private double localCooldown = 0; + @Getter + @Setter + private double globalCooldown = 0; + @Getter + @Setter + private double weight = 0; + @Getter + @Setter + private double eventDuration = 0; + @Getter + @Setter + private int eventEndTime = -1; + @Getter + @Setter + private boolean endEventWithBossDeath = true; + @Getter + @Setter + private String customSpawn = ""; + @Getter + @Setter + private int minimumPlayerCount = 1; + + public CustomEventsConfigFields(String filename, boolean isEnabled) { + super(filename, isEnabled); + } + + @Override + public void processConfigFields() { + this.isEnabled = processBoolean("isEnabled", isEnabled, true, true); + this.eventType = processEnum("eventType", eventType, CustomEvent.EventType.DEFAULT, CustomEvent.EventType.class, true); + if (eventType == CustomEvent.EventType.DEFAULT) { + new WarningMessage("Failed to determine a valid event type for " + filename + " ! This event will not be registered."); + return; + } + this.bossFilenames = processStringList("bossFilenames", bossFilenames, new ArrayList<>(), true); + if (bossFilenames == null) return; + this.startMessage = processString("startMessage", startMessage, null, false); + this.endMessage = processString("endMessage", endMessage, null, false); + this.eventStartCommands = processStringList("eventStartCommands", eventStartCommands, new ArrayList<>(), false); + this.eventEndCommands = processStringList("eventEndCommands", eventEndCommands, new ArrayList<>(), false); + this.announcementPriority = processInt("announcementPriority", announcementPriority, 0, false); + this.chance = processDouble("chance", chance, 0, false); + this.breakableMaterials = processEnumList("breakableMaterials", breakableMaterials, new ArrayList<>(), Material.class, false); + this.localCooldown = processDouble("localCooldown", localCooldown, 0, false); + this.globalCooldown = processDouble("globalCooldown", globalCooldown, 0, false); + this.weight = processDouble("weight", weight, 0, true); + this.eventDuration = processDouble("eventDuration", eventDuration, 0, false); + this.eventEndTime = processInt("eventEndTime", eventEndTime, -1, false); + this.endEventWithBossDeath = processBoolean("endEventWithBossDeath", endEventWithBossDeath, true, false); + this.customSpawn = processString("spawnType", customSpawn, "", false); + this.minimumPlayerCount = processInt("minimumPlayerCount", minimumPlayerCount, 1, false); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/ArmorGoblinEvent.java b/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/ArmorGoblinEvent.java new file mode 100644 index 000000000..e92c9131d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/ArmorGoblinEvent.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.customevents.premade; + +import com.magmaguy.elitemobs.config.customevents.CustomEventsConfigFields; +import com.magmaguy.elitemobs.events.CustomEvent; + +import java.util.Arrays; + +public class ArmorGoblinEvent extends CustomEventsConfigFields { + public ArmorGoblinEvent() { + super("armor_goblin", true); + setEventType(CustomEvent.EventType.TIMED); + setBossFilenames(Arrays.asList("armor_goblin.yml")); + setLocalCooldown(120D); + setGlobalCooldown(25D); + setWeight(100D); + setCustomSpawn("normal_surface_spawn.yml"); + setEventDuration(30); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/BalrogEvent.java b/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/BalrogEvent.java new file mode 100644 index 000000000..4ae7f9699 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/BalrogEvent.java @@ -0,0 +1,20 @@ +package com.magmaguy.elitemobs.config.customevents.premade; + +import com.magmaguy.elitemobs.config.customevents.CustomEventsConfigFields; +import com.magmaguy.elitemobs.events.CustomEvent; +import org.bukkit.Material; + +import java.util.Arrays; + +public class BalrogEvent extends CustomEventsConfigFields { + public BalrogEvent() { + super("balrog", + true); + setEventType(CustomEvent.EventType.BREAK_BLOCK); + setBossFilenames(Arrays.asList("balrog.yml")); + setChance(0.001); + setBreakableMaterials(Arrays.asList(Material.COAL_ORE, Material.IRON_ORE, Material.GOLD_ORE, Material.LAPIS_ORE, + Material.DIAMOND_ORE, Material.EMERALD_ORE, Material.REDSTONE_ORE)); + setEventDuration(20); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/BeastMasterEvent.java b/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/BeastMasterEvent.java new file mode 100644 index 000000000..8b46feb77 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/BeastMasterEvent.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.customevents.premade; + +import com.magmaguy.elitemobs.config.customevents.CustomEventsConfigFields; +import com.magmaguy.elitemobs.events.CustomEvent; + +import java.util.Arrays; + +public class BeastMasterEvent extends CustomEventsConfigFields { + public BeastMasterEvent() { + super("beast_master", true); + setEventType(CustomEvent.EventType.TIMED); + setBossFilenames(Arrays.asList("beast_master.yml")); + setLocalCooldown(120D); + setGlobalCooldown(25D); + setWeight(80); + setCustomSpawn("normal_surface_spawn.yml"); + setEventDuration(30); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/CharmsGoblinEvent.java b/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/CharmsGoblinEvent.java new file mode 100644 index 000000000..1c9f48d38 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/CharmsGoblinEvent.java @@ -0,0 +1,20 @@ +package com.magmaguy.elitemobs.config.customevents.premade; + +import com.magmaguy.elitemobs.config.customevents.CustomEventsConfigFields; +import com.magmaguy.elitemobs.events.CustomEvent; + +import java.util.Arrays; + +public class CharmsGoblinEvent extends CustomEventsConfigFields { + public CharmsGoblinEvent() { + super("charms_goblin", + true); + setEventType(CustomEvent.EventType.TIMED); + setBossFilenames(Arrays.asList("charms_goblin.yml")); + setLocalCooldown(120D); + setGlobalCooldown(25D); + setWeight(50); + setCustomSpawn("normal_surface_spawn.yml"); + setEventDuration(30); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/CoinsGoblinEvent.java b/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/CoinsGoblinEvent.java new file mode 100644 index 000000000..63335913e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/CoinsGoblinEvent.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.customevents.premade; + +import com.magmaguy.elitemobs.config.customevents.CustomEventsConfigFields; +import com.magmaguy.elitemobs.events.CustomEvent; + +import java.util.Arrays; + +public class CoinsGoblinEvent extends CustomEventsConfigFields { + public CoinsGoblinEvent() { + super("coins_goblin", true); + setEventType(CustomEvent.EventType.TIMED); + setBossFilenames(Arrays.asList("coins_goblin.yml")); + setLocalCooldown(120D); + setGlobalCooldown(25D); + setWeight(75); + setCustomSpawn("normal_surface_spawn.yml"); + setEventDuration(30); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/DeadMoonEvent.java b/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/DeadMoonEvent.java new file mode 100644 index 000000000..871ee2017 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/DeadMoonEvent.java @@ -0,0 +1,20 @@ +package com.magmaguy.elitemobs.config.customevents.premade; + +import com.magmaguy.elitemobs.config.customevents.CustomEventsConfigFields; +import com.magmaguy.elitemobs.events.CustomEvent; + +import java.util.Arrays; + +public class DeadMoonEvent extends CustomEventsConfigFields { + public DeadMoonEvent() { + super("dead_moon", true); + setEventType(CustomEvent.EventType.TIMED); + setBossFilenames(Arrays.asList("zombie_king.yml")); + setLocalCooldown(240D); + setGlobalCooldown(25D); + setWeight(50D); + setCustomSpawn("dead_moon_spawn.yml"); + setEventDuration(60D); + setEventEndTime(23999); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/FaeEvent.java b/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/FaeEvent.java new file mode 100644 index 000000000..ad659e0dc --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/FaeEvent.java @@ -0,0 +1,20 @@ +package com.magmaguy.elitemobs.config.customevents.premade; + +import com.magmaguy.elitemobs.config.customevents.CustomEventsConfigFields; +import com.magmaguy.elitemobs.events.CustomEvent; +import org.bukkit.Material; + +import java.util.Arrays; + +public class FaeEvent extends CustomEventsConfigFields { + public FaeEvent() { + super("fae", + true); + setEventType(CustomEvent.EventType.BREAK_BLOCK); + setBossFilenames(Arrays.asList("fire_fae.yml", "ice_fae.yml", "lightning_fae.yml")); + setChance(0.001); + setBreakableMaterials(Arrays.asList(Material.BIRCH_LOG, Material.ACACIA_LOG, Material.DARK_OAK_LOG, + Material.OAK_LOG, Material.SPRUCE_LOG, Material.JUNGLE_LOG)); + setEventDuration(20); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/FullMoonEvent.java b/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/FullMoonEvent.java new file mode 100644 index 000000000..565c5143a --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/FullMoonEvent.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.customevents.premade; + +import com.magmaguy.elitemobs.config.customevents.CustomEventsConfigFields; +import com.magmaguy.elitemobs.events.CustomEvent; + +import java.util.Arrays; + +public class FullMoonEvent extends CustomEventsConfigFields { + public FullMoonEvent() { + super("full_moon", true); + setEventType(CustomEvent.EventType.TIMED); + setBossFilenames(Arrays.asList("alpha_werewolf_p1.yml")); + setLocalCooldown(240D); + setGlobalCooldown(25D); + setWeight(50D); + setCustomSpawn("full_moon_spawn.yml"); + setEventDuration(60D); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/KillerRabbitOfCaerbannogEvent.java b/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/KillerRabbitOfCaerbannogEvent.java new file mode 100644 index 000000000..4ce498049 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/KillerRabbitOfCaerbannogEvent.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.customevents.premade; + +import com.magmaguy.elitemobs.config.customevents.CustomEventsConfigFields; +import com.magmaguy.elitemobs.events.CustomEvent; + +import java.util.Arrays; + +public class KillerRabbitOfCaerbannogEvent extends CustomEventsConfigFields { + public KillerRabbitOfCaerbannogEvent() { + super("killer_rabbit_of_caerbannog", + true); + setEventType(CustomEvent.EventType.TILL_SOIL); + setBossFilenames(Arrays.asList("killer_rabbit_of_caerbannog.yml")); + setChance(0.0001); + setEventDuration(20); + } +} \ No newline at end of file diff --git a/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/KrakenEvent.java b/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/KrakenEvent.java new file mode 100644 index 000000000..4084c2f0a --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/KrakenEvent.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.customevents.premade; + +import com.magmaguy.elitemobs.config.customevents.CustomEventsConfigFields; +import com.magmaguy.elitemobs.events.CustomEvent; + +import java.util.Arrays; + +public class KrakenEvent extends CustomEventsConfigFields { + public KrakenEvent() { + super("kraken", + true); + setEventType(CustomEvent.EventType.FISH); + setBossFilenames(Arrays.asList("kraken.yml")); + setChance(0.005); + setEventDuration(20); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/PillagerCaravanEvent.java b/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/PillagerCaravanEvent.java new file mode 100644 index 000000000..a5b65021b --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/PillagerCaravanEvent.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.customevents.premade; + +import com.magmaguy.elitemobs.config.customevents.CustomEventsConfigFields; +import com.magmaguy.elitemobs.events.CustomEvent; + +import java.util.Arrays; + +public class PillagerCaravanEvent extends CustomEventsConfigFields { + public PillagerCaravanEvent() { + super("pillager_caravan", true); + setEventType(CustomEvent.EventType.TIMED); + setBossFilenames(Arrays.asList("pillager_caravan_leader.yml")); + setLocalCooldown(120D); + setGlobalCooldown(25D); + setWeight(80D); + setCustomSpawn("normal_surface_spawn.yml"); + setEventDuration(30); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/QueenBeeEvent.java b/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/QueenBeeEvent.java new file mode 100644 index 000000000..4d603fabd --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/QueenBeeEvent.java @@ -0,0 +1,21 @@ +package com.magmaguy.elitemobs.config.customevents.premade; + +import com.magmaguy.elitemobs.config.customevents.CustomEventsConfigFields; +import com.magmaguy.elitemobs.events.CustomEvent; +import com.magmaguy.elitemobs.utils.VersionChecker; +import org.bukkit.Material; + +import java.util.Arrays; + +public class QueenBeeEvent extends CustomEventsConfigFields { + public QueenBeeEvent() { + super("queen_bee", + true); + setEventType(CustomEvent.EventType.BREAK_BLOCK); + setBossFilenames(Arrays.asList("queen_bee.yml")); + setChance(0.001); + if (!VersionChecker.serverVersionOlderThan(15, 0)) + setBreakableMaterials(Arrays.asList(Material.BEE_NEST)); + setEventDuration(20); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/TreasureGoblinEvent.java b/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/TreasureGoblinEvent.java new file mode 100644 index 000000000..8d8513629 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/TreasureGoblinEvent.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.customevents.premade; + +import com.magmaguy.elitemobs.config.customevents.CustomEventsConfigFields; +import com.magmaguy.elitemobs.events.CustomEvent; + +import java.util.Arrays; + +public class TreasureGoblinEvent extends CustomEventsConfigFields { + public TreasureGoblinEvent() { + super("treasure_goblin", true); + setEventType(CustomEvent.EventType.TIMED); + setBossFilenames(Arrays.asList("treasure_goblin.yml")); + setLocalCooldown(120D); + setGlobalCooldown(25D); + setWeight(100D); + setCustomSpawn("normal_surface_spawn.yml"); + setEventDuration(30); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/WeaponsGoblinEvent.java b/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/WeaponsGoblinEvent.java new file mode 100644 index 000000000..8adf6862a --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/WeaponsGoblinEvent.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.customevents.premade; + +import com.magmaguy.elitemobs.config.customevents.CustomEventsConfigFields; +import com.magmaguy.elitemobs.events.CustomEvent; + +import java.util.Arrays; + +public class WeaponsGoblinEvent extends CustomEventsConfigFields { + public WeaponsGoblinEvent() { + super("weapons_goblin", true); + setEventType(CustomEvent.EventType.TIMED); + setBossFilenames(Arrays.asList("weapons_goblin.yml")); + setLocalCooldown(120D); + setGlobalCooldown(25D); + setWeight(100D); + setCustomSpawn("normal_surface_spawn.yml"); + setEventDuration(30); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/ZombieTotemEvent.java b/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/ZombieTotemEvent.java new file mode 100644 index 000000000..16d79609d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customevents/premade/ZombieTotemEvent.java @@ -0,0 +1,20 @@ +package com.magmaguy.elitemobs.config.customevents.premade; + +import com.magmaguy.elitemobs.config.customevents.CustomEventsConfigFields; +import com.magmaguy.elitemobs.events.CustomEvent; + +import java.util.Arrays; + +public class ZombieTotemEvent extends CustomEventsConfigFields { + public ZombieTotemEvent() { + super("zombie_totem", true); + setEventType(CustomEvent.EventType.TIMED); + setBossFilenames(Arrays.asList("totem_zombie_1.yml")); + setLocalCooldown(120D); + setGlobalCooldown(25D); + setWeight(100D); + setCustomSpawn("normal_surface_spawn.yml"); + setEventDuration(30); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/CustomItemsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/CustomItemsConfig.java new file mode 100644 index 000000000..15ce5ec19 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/CustomItemsConfig.java @@ -0,0 +1,22 @@ +package com.magmaguy.elitemobs.config.customitems; + +import com.magmaguy.elitemobs.config.CustomConfig; + +import java.util.HashMap; + +public class CustomItemsConfig extends CustomConfig { + + private static HashMap customItems = new HashMap<>(); + + public CustomItemsConfig() { + super("customitems", "com.magmaguy.elitemobs.config.customitems.premade", CustomItemsConfigFields.class); + customItems = new HashMap<>(); + for (String key : super.getCustomConfigFieldsHashMap().keySet()) + customItems.put(key, (CustomItemsConfigFields) super.getCustomConfigFieldsHashMap().get(key)); + } + + public static HashMap getCustomItems() { + return customItems; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/CustomItemsConfigFields.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/CustomItemsConfigFields.java new file mode 100644 index 000000000..ea9da5df2 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/CustomItemsConfigFields.java @@ -0,0 +1,83 @@ +package com.magmaguy.elitemobs.config.customitems; + +import com.magmaguy.elitemobs.config.CustomConfigFields; +import com.magmaguy.elitemobs.config.CustomConfigFieldsInterface; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import lombok.Getter; +import lombok.Setter; +import org.bukkit.Material; + +import java.util.ArrayList; +import java.util.List; + +public class CustomItemsConfigFields extends CustomConfigFields implements CustomConfigFieldsInterface { + + @Getter + @Setter + private Material material = Material.WOODEN_SWORD; + @Getter + @Setter + private String name = "Default name"; + @Getter + @Setter + private List lore = new ArrayList<>(); + @Getter + @Setter + private List enchantments = new ArrayList<>(); + @Getter + @Setter + private List potionEffects = new ArrayList<>(); + @Getter + @Setter + private String dropWeight = "dynamic"; + @Getter + @Setter + private CustomItem.Scalability scalability = CustomItem.Scalability.SCALABLE; + @Getter + @Setter + private CustomItem.ItemType itemType = CustomItem.ItemType.CUSTOM; + @Getter + @Setter + private Integer customModelID = -1; + @Getter + @Setter + //todo: implement + private List nbtTags = new ArrayList<>(); + @Getter + @Setter + private String permission = ""; + + public CustomItemsConfigFields(String fileName, + boolean isEnabled, + Material material, + String name, + List lore) { + super(fileName, isEnabled); + this.material = material; + this.name = name; + this.lore = lore; + } + + public CustomItemsConfigFields(String fileName, + boolean isEnabled) { + super(fileName, isEnabled); + } + + /** + * Generates config defaults to be used by CustomBossesConfig + */ + @Override + public void processConfigFields() { + this.isEnabled = processBoolean("isEnabled", isEnabled, true, true); + this.material = processEnum("material", material, Material.WOODEN_SWORD, Material.class, true); + this.name = processString("name", name, "Default name", true); + this.lore = processStringList("lore", lore, new ArrayList<>(), true); + this.enchantments = processStringList("enchantments", enchantments, new ArrayList<>(), false); + this.potionEffects = processStringList("potionEffects", potionEffects, new ArrayList<>(), false); + this.dropWeight = processString("dropWeight", dropWeight, "dynamic", false); + this.scalability = processEnum("scalability", scalability, CustomItem.Scalability.SCALABLE, CustomItem.Scalability.class, false); + this.itemType = processEnum("itemType", itemType, CustomItem.ItemType.CUSTOM, CustomItem.ItemType.class, false); + this.customModelID = processInt("customModelID", customModelID, -1, false); + this.permission = processString("permission", permission, "", false); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/BerserkerCharmConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/BerserkerCharmConfig.java new file mode 100644 index 000000000..30327f7ca --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/BerserkerCharmConfig.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import org.bukkit.Material; + +import java.util.Arrays; + +public class BerserkerCharmConfig extends CustomItemsConfigFields { + public BerserkerCharmConfig() { + super("berserker_charm", + true, + Material.TOTEM_OF_UNDYING, + "&bBerserker Charm", + Arrays.asList("&aLose yourself in the face of", "&aoverwhelming adversity in more", "&aways than one...")); + setEnchantments(Arrays.asList("VANISHING_CURSE,1")); + setPotionEffects(Arrays.asList("BLINDNESS,0,self,onHit", "FAST_DIGGING,0,self,onHit")); + setDropWeight("1"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/ChallengersBootsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/ChallengersBootsConfig.java new file mode 100644 index 000000000..034dbb151 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/ChallengersBootsConfig.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class ChallengersBootsConfig extends CustomItemsConfigFields { + public ChallengersBootsConfig() { + super("challengers_boots", true, Material.DIAMOND_BOOTS, "&cChallenger's Boots", Arrays.asList("&2Awarded to those who challenge the", "&2Wood League Arena!")); + setEnchantments(Arrays.asList("PROTECTION_ENVIRONMENTAL,40", "PROTECTION_EXPLOSIONS,20", "PROTECTION_PROJECTILE,20", "MENDING,1", "DURABILITY,5")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/ChallengersChestplateConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/ChallengersChestplateConfig.java new file mode 100644 index 000000000..08b8f2f2d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/ChallengersChestplateConfig.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class ChallengersChestplateConfig extends CustomItemsConfigFields { + public ChallengersChestplateConfig(){ + super("challengers_chestplate", true, Material.DIAMOND_CHESTPLATE, "&cChallenger's Chestplate", Arrays.asList("&2Awarded to those who challenge the", "&2Wood League Arena!")); + setEnchantments(Arrays.asList("PROTECTION_ENVIRONMENTAL,40", "PROTECTION_EXPLOSIONS,20", "PROTECTION_PROJECTILE,20", "MENDING,1", "DURABILITY,5")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/ChallengersHelmetConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/ChallengersHelmetConfig.java new file mode 100644 index 000000000..ca2caa7fa --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/ChallengersHelmetConfig.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class ChallengersHelmetConfig extends CustomItemsConfigFields { + public ChallengersHelmetConfig(){ + super("challengers_helmet", true, Material.DIAMOND_HELMET, "&cChallenger's Helmet", Arrays.asList("&2Awarded to those who challenge the", "&2Wood League Arena!")); + setEnchantments(Arrays.asList("PROTECTION_ENVIRONMENTAL,40", "PROTECTION_EXPLOSIONS,20", "PROTECTION_PROJECTILE,20", "MENDING,1", "DURABILITY,5")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/ChallengersLeggingsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/ChallengersLeggingsConfig.java new file mode 100644 index 000000000..a9e9f341b --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/ChallengersLeggingsConfig.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class ChallengersLeggingsConfig extends CustomItemsConfigFields { + public ChallengersLeggingsConfig(){ + super("challengers_leggings", true, Material.DIAMOND_LEGGINGS, "&cChallenger's Leggings", Arrays.asList("&2Awarded to those who challenge the", "&2Wood League Arena!")); + setEnchantments(Arrays.asList("PROTECTION_ENVIRONMENTAL,40", "PROTECTION_EXPLOSIONS,20", "PROTECTION_PROJECTILE,20", "MENDING,1", "DURABILITY,5")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/ChallengersSwordConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/ChallengersSwordConfig.java new file mode 100644 index 000000000..6cbb38930 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/ChallengersSwordConfig.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class ChallengersSwordConfig extends CustomItemsConfigFields { + public ChallengersSwordConfig(){ + super("challengers_sword", true, Material.DIAMOND_SWORD, "&cChallenger's Sword", Arrays.asList("&2Awarded to those who challenge the", "&2Wood League Arena!")); + setEnchantments(Arrays.asList("DAMAGE_ALL,40", "KNOCKBACK,2", "MENDING,1", "LIGHTNING,3", "SWEEPING_EDGE,1", "DURABILITY,5")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/ChameleonCharmConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/ChameleonCharmConfig.java new file mode 100644 index 000000000..bec6d4a62 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/ChameleonCharmConfig.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import org.bukkit.Material; + +import java.util.Arrays; + +public class ChameleonCharmConfig extends CustomItemsConfigFields { + public ChameleonCharmConfig() { + super("chameleon_charm", + true, + Material.LEATHER, + "&bChameleon Charm", + Arrays.asList("&aThe colorful Chameleon can", "&ablend in just about anywhere,", "&aslowly creeping around...")); + setEnchantments(Arrays.asList("VANISHING_CURSE,1")); + setPotionEffects(Arrays.asList("INVISIBILITY,0,self,onHit", "SLOW,0,self,onHit", "BLINDNESS,0,self,onHit")); + setDropWeight("1"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/CheetahCharmConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/CheetahCharmConfig.java new file mode 100644 index 000000000..6f156173d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/CheetahCharmConfig.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import org.bukkit.Material; + +import java.util.Arrays; + +public class CheetahCharmConfig extends CustomItemsConfigFields { + public CheetahCharmConfig() { + super("cheetah_charm", + true, + Material.GOLDEN_BOOTS, + "&bCheetah Charm", + Arrays.asList("&aCheetahs can reach speeds of", "&a120 km/h... for about 60", "&aseconds. Make them count!")); + setEnchantments(Arrays.asList("VANISHING_CURSE,1")); + setPotionEffects(Arrays.asList("SPEED,2,self,continuous", "HUNGER,0,self,continuous")); + setDropWeight("1"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/DepthsSeekerConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/DepthsSeekerConfig.java new file mode 100644 index 000000000..3dff27bdb --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/DepthsSeekerConfig.java @@ -0,0 +1,20 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class DepthsSeekerConfig extends CustomItemsConfigFields { + public DepthsSeekerConfig() { + super("depths_seeker", + true, + Material.FISHING_ROD, + "&2Depths seeker", + Arrays.asList("&9Come from depths immeasurable", "&9and looted from monster most vile,", "&9there is no telling what horrors", "&9this fishing rod has seen.")); + setEnchantments(Arrays.asList("LURE,3", "LUCK,3", "DURABILITY,10", "FIRE_ASPECT,1", "VANISHING_CURSE,1")); + setPotionEffects(Arrays.asList("WATER_BREATHING,0,self,continuous", "LUCK,0,self,continuous")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/DwarvenGreedConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/DwarvenGreedConfig.java new file mode 100644 index 000000000..98b618338 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/DwarvenGreedConfig.java @@ -0,0 +1,20 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class DwarvenGreedConfig extends CustomItemsConfigFields { + public DwarvenGreedConfig() { + super("dwarven_greed", + true, + Material.WOODEN_PICKAXE, + "&4Dwarven Greed", + Arrays.asList("&cThose who delve too greedily", "&cand too deep may wake ancient", "&chorrors of shadow and flame", "&cbest left undisturbed.")); + setEnchantments(Arrays.asList("LOOT_BONUS_BLOCKS,4", "DURABILITY,6", "DIG_SPEED,6", "VANISHING_CURSE,1")); + setPotionEffects(Arrays.asList("FAST_DIGGING,1,self,continuous", "NIGHT_VISION,0,self,continuous")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/ElephantCharmConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/ElephantCharmConfig.java new file mode 100644 index 000000000..2f2dd3e05 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/ElephantCharmConfig.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import org.bukkit.Material; + +import java.util.Arrays; + +public class ElephantCharmConfig extends CustomItemsConfigFields { + public ElephantCharmConfig() { + super("elephant_charm", + true, + Material.ANVIL, + "&bElephant Charm", + Arrays.asList("&aGain the power of an elephant", "&astampede, for the cost of the", "&aspeed of an elephant stampede!")); + setEnchantments(Arrays.asList("VANISHING_CURSE,1")); + setPotionEffects(Arrays.asList("INCREASE_DAMAGE,1,self,onHit", "SLOW,3,self,onHit")); + setDropWeight("1"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/FireflyCharmConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/FireflyCharmConfig.java new file mode 100644 index 000000000..b7a43f4ea --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/FireflyCharmConfig.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import org.bukkit.Material; + +import java.util.Arrays; + +public class FireflyCharmConfig extends CustomItemsConfigFields { + public FireflyCharmConfig() { + super("firefly_charm", + true, + Material.GLASS_BOTTLE, + "&bFirefly Charm", + Arrays.asList("&aLight up the night!")); + setEnchantments(Arrays.asList("VANISHING_CURSE,1")); + setPotionEffects(Arrays.asList("NIGHT_VISION,0,self,continuous", "GLOWING,0,target,onHit")); + setDropWeight("1"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/FishyCharmConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/FishyCharmConfig.java new file mode 100644 index 000000000..a1826317f --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/FishyCharmConfig.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import org.bukkit.Material; + +import java.util.Arrays; + +public class FishyCharmConfig extends CustomItemsConfigFields { + public FishyCharmConfig() { + super("fishy_charm", + true, + Material.COD, + "&bFishy Charm", + Arrays.asList("&aThere's just something not", "&aquite right with this one...")); + setEnchantments(Arrays.asList("VANISHING_CURSE,1")); + setPotionEffects(Arrays.asList("WATER_BREATHING,0,self,continuous")); + setDropWeight("1"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GoblinBallistaItem.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GoblinBallistaItem.java new file mode 100644 index 000000000..8b02832c9 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GoblinBallistaItem.java @@ -0,0 +1,20 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class GoblinBallistaItem extends CustomItemsConfigFields { + public GoblinBallistaItem() { + super("goblin_ballista", + true, + Material.CROSSBOW, + "&8Goblin Ballista", + Arrays.asList("&8A treasure among goblins!")); + setEnchantments(Arrays.asList("ARROW_DAMAGE,1", "DURABILITY,1", "QUICK_CHARGE,3", "MULTISHOT,1")); + setPotionEffects(Arrays.asList("HEAL,0,self,onHit")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GoblinBootsItem.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GoblinBootsItem.java new file mode 100644 index 000000000..746837fee --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GoblinBootsItem.java @@ -0,0 +1,23 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import com.magmaguy.elitemobs.utils.VersionChecker; +import org.bukkit.Material; + +import java.util.Arrays; + +public class GoblinBootsItem extends CustomItemsConfigFields { + public GoblinBootsItem() { + super("goblin_boots", + true, + Material.GOLDEN_BOOTS, + "&8Goblin Boots", + Arrays.asList("&8A treasure among goblins!")); + if (!VersionChecker.serverVersionOlderThan(16, 0)) + setMaterial(Material.NETHERITE_BOOTS); + setEnchantments(Arrays.asList("PROTECTION_ENVIRONMENTAL,1", "PROTECTION_EXPLOSIONS,1", "PROTECTION_PROJECTILE,1", "DURABILITY,1")); + setPotionEffects(Arrays.asList("SPEED,0,self,continuous")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GoblinChestplateItem.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GoblinChestplateItem.java new file mode 100644 index 000000000..cb0fe86f2 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GoblinChestplateItem.java @@ -0,0 +1,23 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import com.magmaguy.elitemobs.utils.VersionChecker; +import org.bukkit.Material; + +import java.util.Arrays; + +public class GoblinChestplateItem extends CustomItemsConfigFields { + public GoblinChestplateItem() { + super("goblin_chestplate", + true, + Material.GOLDEN_CHESTPLATE, + "&8Goblin Chestplate", + Arrays.asList("&8A treasure among goblins!")); + if (!VersionChecker.serverVersionOlderThan(16, 0)) + setMaterial(Material.NETHERITE_CHESTPLATE); + setEnchantments(Arrays.asList("PROTECTION_ENVIRONMENTAL,1", "PROTECTION_EXPLOSIONS,1", "PROTECTION_PROJECTILE,1", "DURABILITY,1")); + setPotionEffects(Arrays.asList("SATURATION,0,self,continuous")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GoblinCleaverItem.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GoblinCleaverItem.java new file mode 100644 index 000000000..9c30ee824 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GoblinCleaverItem.java @@ -0,0 +1,23 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import com.magmaguy.elitemobs.utils.VersionChecker; +import org.bukkit.Material; + +import java.util.Arrays; + +public class GoblinCleaverItem extends CustomItemsConfigFields { + public GoblinCleaverItem() { + super("goblin_cleaver", + true, + Material.GOLDEN_AXE, + "&8Goblin Cleaver", + Arrays.asList("&8A treasure among goblins!")); + if (!VersionChecker.serverVersionOlderThan(16, 0)) + setMaterial(Material.NETHERITE_AXE); + setEnchantments(Arrays.asList("DAMAGE_ALL,1", "DAMAGE_UNDEAD,1", "DURABILITY,1", "KNOCKBACK,1", "LOOT_BONUS_MOBS,5")); + setPotionEffects(Arrays.asList("POISON,0,target,onHit")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GoblinHelmetItem.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GoblinHelmetItem.java new file mode 100644 index 000000000..4d2f17e7e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GoblinHelmetItem.java @@ -0,0 +1,23 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import com.magmaguy.elitemobs.utils.VersionChecker; +import org.bukkit.Material; + +import java.util.Arrays; + +public class GoblinHelmetItem extends CustomItemsConfigFields { + public GoblinHelmetItem() { + super("goblin_helmet", + true, + Material.GOLDEN_HELMET, + "&8Goblin Helmet", + Arrays.asList("&8A treasure among goblins!")); + if (!VersionChecker.serverVersionOlderThan(16, 0)) + setMaterial(Material.NETHERITE_HELMET); + setEnchantments(Arrays.asList("PROTECTION_ENVIRONMENTAL,1", "PROTECTION_EXPLOSIONS,1", "PROTECTION_PROJECTILE,1", "DURABILITY,1")); + setPotionEffects(Arrays.asList("NIGHT_VISION,0,self,continuous")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GoblinLeggingsItem.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GoblinLeggingsItem.java new file mode 100644 index 000000000..495c85ee0 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GoblinLeggingsItem.java @@ -0,0 +1,23 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import com.magmaguy.elitemobs.utils.VersionChecker; +import org.bukkit.Material; + +import java.util.Arrays; + +public class GoblinLeggingsItem extends CustomItemsConfigFields { + public GoblinLeggingsItem() { + super("goblin_leggings", + true, + Material.GOLDEN_LEGGINGS, + "&8Goblin Leggings", + Arrays.asList("&8A treasure among goblins!")); + if (!VersionChecker.serverVersionOlderThan(16, 0)) + setMaterial(Material.NETHERITE_LEGGINGS); + setEnchantments(Arrays.asList("PROTECTION_ENVIRONMENTAL,1", "PROTECTION_EXPLOSIONS,1", "PROTECTION_PROJECTILE,1", "DURABILITY,1")); + setPotionEffects(Arrays.asList("JUMP,0,self,continuous")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GoblinPokerItem.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GoblinPokerItem.java new file mode 100644 index 000000000..d7977748c --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GoblinPokerItem.java @@ -0,0 +1,20 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class GoblinPokerItem extends CustomItemsConfigFields { + public GoblinPokerItem() { + super("goblin_poker", + true, + Material.TRIDENT, + "&8Goblin Poker", + Arrays.asList("&8A treasure among goblins!")); + setEnchantments(Arrays.asList("DAMAGE_ALL,1", "DAMAGE_UNDEAD,1", "DURABILITY,1", "KNOCKBACK,1", "LOOT_BONUS_MOBS,5")); + setPotionEffects(Arrays.asList("WITHER,0,target,onHit")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GoblinShooterItem.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GoblinShooterItem.java new file mode 100644 index 000000000..68fb2979d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GoblinShooterItem.java @@ -0,0 +1,20 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class GoblinShooterItem extends CustomItemsConfigFields { + public GoblinShooterItem() { + super("goblin_shooter", + true, + Material.BOW, + "&8Goblin Shooter", + Arrays.asList("&8A treasure among goblins!")); + setEnchantments(Arrays.asList("ARROW_DAMAGE,1", "DURABILITY,1", "ARROW_INFINITE,1", "ARROW_FIRE,1")); + setPotionEffects(Arrays.asList("SPEED,2,self,onHit")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GoblinSlasherItem.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GoblinSlasherItem.java new file mode 100644 index 000000000..d1dd84dbb --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GoblinSlasherItem.java @@ -0,0 +1,23 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import com.magmaguy.elitemobs.utils.VersionChecker; +import org.bukkit.Material; + +import java.util.Arrays; + +public class GoblinSlasherItem extends CustomItemsConfigFields { + public GoblinSlasherItem() { + super("goblin_slasher", + true, + Material.GOLDEN_SWORD, + "&8Goblin Slasher", + Arrays.asList("&8A treasure among goblins!")); + if (!VersionChecker.serverVersionOlderThan(16, 0)) + setMaterial(Material.NETHERITE_SWORD); + setEnchantments(Arrays.asList("DAMAGE_ALL,1", "DAMAGE_UNDEAD,1", "DURABILITY,1", "KNOCKBACK,1", "LOOT_BONUS_MOBS,5")); + setPotionEffects(Arrays.asList("FAST_DIGGING,0,self,onHit")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GrapplingArrowConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GrapplingArrowConfig.java new file mode 100644 index 000000000..193334cf3 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GrapplingArrowConfig.java @@ -0,0 +1,20 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class GrapplingArrowConfig extends CustomItemsConfigFields { + public GrapplingArrowConfig() { + super("grappling_arrow", + true, + Material.SPECTRAL_ARROW, + "&6Grappling Arrow", + Arrays.asList("&eFire at a TARGET BLOCK to grapple!")); + setEnchantments(Arrays.asList("GRAPPLING_HOOK,1")); + setScalability(CustomItem.Scalability.FIXED); + setDropWeight("1"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GruntsBootsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GruntsBootsConfig.java new file mode 100644 index 000000000..4e23b629d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GruntsBootsConfig.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class GruntsBootsConfig extends CustomItemsConfigFields { + public GruntsBootsConfig(){ + super("grunts_boots", true, Material.IRON_BOOTS, "&fGrunt's Boots", Arrays.asList("&2Awarded to those who challenge the", "&2Wood League Arena!")); + setEnchantments(Arrays.asList("PROTECTION_ENVIRONMENTAL,20", "PROTECTION_PROJECTILE,10", "DURABILITY,5")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GruntsChestplateConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GruntsChestplateConfig.java new file mode 100644 index 000000000..de4248457 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GruntsChestplateConfig.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class GruntsChestplateConfig extends CustomItemsConfigFields { + public GruntsChestplateConfig(){ + super("grunts_chestplate", true, Material.IRON_CHESTPLATE, "&fGrunt's Chestplate", Arrays.asList("&2Awarded to those who challenge the", "&2Wood League Arena!")); + setEnchantments(Arrays.asList("PROTECTION_ENVIRONMENTAL,20", "PROTECTION_PROJECTILE,10", "DURABILITY,5")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GruntsHelmetConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GruntsHelmetConfig.java new file mode 100644 index 000000000..23dd6d9dc --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GruntsHelmetConfig.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class GruntsHelmetConfig extends CustomItemsConfigFields { + public GruntsHelmetConfig(){ + super("grunts_helmet", true, Material.IRON_HELMET, "&fGrunt's Helmet", Arrays.asList("&2Awarded to those who challenge the", "&2Wood League Arena!")); + setEnchantments(Arrays.asList("PROTECTION_ENVIRONMENTAL,20", "PROTECTION_PROJECTILE,10", "DURABILITY,5")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GruntsLeggingsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GruntsLeggingsConfig.java new file mode 100644 index 000000000..9099ca486 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GruntsLeggingsConfig.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class GruntsLeggingsConfig extends CustomItemsConfigFields { + public GruntsLeggingsConfig(){ + super("grunts_leggings", true, Material.IRON_LEGGINGS, "&fGrunt's Leggings", Arrays.asList("&2Awarded to those who challenge the", "&2Wood League Arena!")); + setEnchantments(Arrays.asList("PROTECTION_ENVIRONMENTAL,20", "PROTECTION_PROJECTILE,10", "DURABILITY,5")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GruntsSwordConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GruntsSwordConfig.java new file mode 100644 index 000000000..62336fc58 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/GruntsSwordConfig.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class GruntsSwordConfig extends CustomItemsConfigFields { + public GruntsSwordConfig(){ + super("grunts_sword", true, Material.IRON_SWORD, "&fGrunt's Sword", Arrays.asList("&2Awarded to those who challenge the", "&2Wood League Arena!")); + setEnchantments(Arrays.asList("DAMAGE_ALL,20", "KNOCKBACK,2", "SWEEPING_EDGE,1", "DURABILITY,5")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/InvictusBootsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/InvictusBootsConfig.java new file mode 100644 index 000000000..d588d2ace --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/InvictusBootsConfig.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import com.magmaguy.elitemobs.utils.VersionChecker; +import org.bukkit.Material; + +import java.util.Arrays; + +public class InvictusBootsConfig extends CustomItemsConfigFields { + public InvictusBootsConfig(){ + super("invictus_boots", true, Material.DIAMOND_BOOTS, "&4Invictus Boots", Arrays.asList("&2Awarded to the champions of the", "&2Wood League Arena!")); + if (!VersionChecker.serverVersionOlderThan(16, 0)) + setMaterial(Material.NETHERITE_BOOTS); + setEnchantments(Arrays.asList("PROTECTION_ENVIRONMENTAL,50", "PROTECTION_EXPLOSIONS,25", "PROTECTION_PROJECTILE,25", "MENDING,1", "DURABILITY,5")); + setPotionEffects(Arrays.asList("SPEED,0,self,continuous")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/InvictusChestplateConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/InvictusChestplateConfig.java new file mode 100644 index 000000000..4b749c662 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/InvictusChestplateConfig.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import com.magmaguy.elitemobs.utils.VersionChecker; +import org.bukkit.Material; + +import java.util.Arrays; + +public class InvictusChestplateConfig extends CustomItemsConfigFields { + public InvictusChestplateConfig(){ + super("invictus_chestplate", true, Material.DIAMOND_CHESTPLATE, "&4Invictus Chestplate", Arrays.asList("&2Awarded to the champions of the", "&2Wood League Arena!")); + if (!VersionChecker.serverVersionOlderThan(16, 0)) + setMaterial(Material.NETHERITE_CHESTPLATE); + setEnchantments(Arrays.asList("PROTECTION_ENVIRONMENTAL,50", "PROTECTION_EXPLOSIONS,25", "PROTECTION_PROJECTILE,25", "MENDING,1", "DURABILITY,5")); + setPotionEffects(Arrays.asList("HEAL,0,self,onHit")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/InvictusHelmetConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/InvictusHelmetConfig.java new file mode 100644 index 000000000..9e040f302 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/InvictusHelmetConfig.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import com.magmaguy.elitemobs.utils.VersionChecker; +import org.bukkit.Material; + +import java.util.Arrays; + +public class InvictusHelmetConfig extends CustomItemsConfigFields { + public InvictusHelmetConfig() { + super("invictus_helmet", true, Material.DIAMOND_HELMET, "&4Invictus Helmet", Arrays.asList("&2Awarded to the champions of the", "&2Wood League Arena!")); + if (!VersionChecker.serverVersionOlderThan(16, 0)) + setMaterial(Material.NETHERITE_HELMET); + setEnchantments(Arrays.asList("PROTECTION_ENVIRONMENTAL,50", "PROTECTION_EXPLOSIONS,25", "PROTECTION_PROJECTILE,25", "MENDING,1", "DURABILITY,5")); + setPotionEffects(Arrays.asList("NIGHT_VISION,0,self,continuous")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/InvictusLeggingsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/InvictusLeggingsConfig.java new file mode 100644 index 000000000..d5d385359 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/InvictusLeggingsConfig.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import com.magmaguy.elitemobs.utils.VersionChecker; +import org.bukkit.Material; + +import java.util.Arrays; + +public class InvictusLeggingsConfig extends CustomItemsConfigFields { + public InvictusLeggingsConfig(){ + super("invictus_leggings", true, Material.DIAMOND_LEGGINGS, "&4Invictus Leggings", Arrays.asList("&2Awarded to the champions of the", "&2Wood League Arena!")); + if (!VersionChecker.serverVersionOlderThan(16, 0)) + setMaterial(Material.NETHERITE_LEGGINGS); + setEnchantments(Arrays.asList("PROTECTION_ENVIRONMENTAL,50", "PROTECTION_EXPLOSIONS,25", "PROTECTION_PROJECTILE,25", "MENDING,1", "DURABILITY,5")); + setPotionEffects(Arrays.asList("JUMP,0,self,continuous")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/InvictusPickaxeConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/InvictusPickaxeConfig.java new file mode 100644 index 000000000..630ce0720 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/InvictusPickaxeConfig.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import com.magmaguy.elitemobs.utils.VersionChecker; +import org.bukkit.Material; + +import java.util.Arrays; + +public class InvictusPickaxeConfig extends CustomItemsConfigFields { + public InvictusPickaxeConfig(){ + super("invictus_pickaxe", true, Material.DIAMOND_PICKAXE, "&4Invictus Pickaxe", Arrays.asList("&2Awarded to the champions of the", "&2Wood League Arena!")); + if (!VersionChecker.serverVersionOlderThan(16, 0)) + setMaterial(Material.NETHERITE_PICKAXE); + setEnchantments(Arrays.asList("DIG_SPEED,6", "DRILLING,3", "DURABILITY,5")); + setPotionEffects(Arrays.asList("FAST_DIGGING,0,self,continuous")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/InvictusShovelConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/InvictusShovelConfig.java new file mode 100644 index 000000000..ebdbd70ee --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/InvictusShovelConfig.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import com.magmaguy.elitemobs.utils.VersionChecker; +import org.bukkit.Material; + +import java.util.Arrays; + +public class InvictusShovelConfig extends CustomItemsConfigFields { + public InvictusShovelConfig(){ + super("invictus_shovel", true, Material.DIAMOND_SHOVEL, "&4Invictus Shovel", Arrays.asList("&2Awarded to the champions of the", "&2Wood League Arena!")); + if (!VersionChecker.serverVersionOlderThan(16, 0)) + setMaterial(Material.NETHERITE_SHOVEL); + setEnchantments(Arrays.asList("DIG_SPEED,6", "DRILLING,3", "DURABILITY,5")); + setPotionEffects(Arrays.asList("FAST_DIGGING,0,self,continuous")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/InvictusSwordConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/InvictusSwordConfig.java new file mode 100644 index 000000000..332298e2e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/InvictusSwordConfig.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import com.magmaguy.elitemobs.utils.VersionChecker; +import org.bukkit.Material; + +import java.util.Arrays; + +public class InvictusSwordConfig extends CustomItemsConfigFields { + public InvictusSwordConfig() { + super("invictus_sword", true, Material.DIAMOND_SWORD, "&4Invictus Sword", Arrays.asList("&2Awarded to the champions of the", "&2Wood League Arena!")); + if (!VersionChecker.serverVersionOlderThan(16, 0)) + setMaterial(Material.NETHERITE_SWORD); + setEnchantments(Arrays.asList("DAMAGE_ALL,50", "KNOCKBACK,2", "MENDING,1", "LIGHTNING,3", "SWEEPING_EDGE,1", "DURABILITY,5")); + setPotionEffects(Arrays.asList("WITHER,0,target,onHit")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/LuckyCharmsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/LuckyCharmsConfig.java new file mode 100644 index 000000000..95eca3c17 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/LuckyCharmsConfig.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import org.bukkit.Material; + +import java.util.Arrays; + +public class LuckyCharmsConfig extends CustomItemsConfigFields { + public LuckyCharmsConfig() { + super("lucky_charms", + true, + Material.COOKIE, + "&bLucky Charms", + Arrays.asList("&aPart of a complete breakfast!", "&cNote: Absolutely not a part of", "&ca complete breakfast.")); + setEnchantments(Arrays.asList("VANISHING_CURSE,1")); + setPotionEffects(Arrays.asList("LUCK,0,self,continuous")); + setDropWeight("1"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/MagmaguysToothpickConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/MagmaguysToothpickConfig.java new file mode 100644 index 000000000..6b5509905 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/MagmaguysToothpickConfig.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import org.bukkit.Material; + +import java.util.Arrays; + +public class MagmaguysToothpickConfig extends CustomItemsConfigFields { + public MagmaguysToothpickConfig() { + super("magmaguys_toothpick", + true, + Material.WOODEN_SWORD, + "&4Magmaguy&c's &2Toothpick", + Arrays.asList("&aIn nearly mint condition!")); + setEnchantments(Arrays.asList("VANISHING_CURSE,1")); + setCustomModelID(1); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/MeteorShowerScrollConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/MeteorShowerScrollConfig.java new file mode 100644 index 000000000..a6fac7383 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/MeteorShowerScrollConfig.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class MeteorShowerScrollConfig extends CustomItemsConfigFields { + public MeteorShowerScrollConfig() { + super("meteor_shower_scroll", + true, + Material.PAPER, + "&7Meteor Shower Scroll", + Arrays.asList("&4Call forth destruction.", "&4Single-use.")); + setEnchantments(Arrays.asList("METEOR_SHOWER,1")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/NovicesBootsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/NovicesBootsConfig.java new file mode 100644 index 000000000..4ec88baac --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/NovicesBootsConfig.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class NovicesBootsConfig extends CustomItemsConfigFields { + public NovicesBootsConfig(){ + super("novices_boots", true, Material.LEATHER_BOOTS, "&8Novice's Boots", Arrays.asList("&2Awarded to those who challenge the", "&2Wood League Arena!")); + setEnchantments(Arrays.asList("PROTECTION_ENVIRONMENTAL,10", "DURABILITY,5")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/NovicesChestplateConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/NovicesChestplateConfig.java new file mode 100644 index 000000000..8693ad772 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/NovicesChestplateConfig.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class NovicesChestplateConfig extends CustomItemsConfigFields { + public NovicesChestplateConfig(){ + super("novices_chestplate", true, Material.LEATHER_CHESTPLATE, "&8Novice's Chestplate", Arrays.asList("&2Awarded to those who challenge the", "&2Wood League Arena!")); + setEnchantments(Arrays.asList("PROTECTION_ENVIRONMENTAL,10", "DURABILITY,5")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/NovicesHelmetConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/NovicesHelmetConfig.java new file mode 100644 index 000000000..d42b919c8 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/NovicesHelmetConfig.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class NovicesHelmetConfig extends CustomItemsConfigFields { + public NovicesHelmetConfig(){ + super("novices_helmet", true, Material.LEATHER_HELMET, "&8Novice's Helmet", Arrays.asList("&2Awarded to those who challenge the", "&2Wood League Arena!")); + setEnchantments(Arrays.asList("PROTECTION_ENVIRONMENTAL,10", "DURABILITY,5")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/NovicesLeggingsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/NovicesLeggingsConfig.java new file mode 100644 index 000000000..07dc93d21 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/NovicesLeggingsConfig.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class NovicesLeggingsConfig extends CustomItemsConfigFields { + public NovicesLeggingsConfig(){ + super("novices_leggings", true, Material.LEATHER_LEGGINGS, "&8Novice's Leggings", Arrays.asList("&2Awarded to those who challenge the", "&2Wood League Arena!")); + setEnchantments(Arrays.asList("PROTECTION_ENVIRONMENTAL,10", "DURABILITY,5")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/NovicesSwordConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/NovicesSwordConfig.java new file mode 100644 index 000000000..29166ce41 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/NovicesSwordConfig.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class NovicesSwordConfig extends CustomItemsConfigFields { + public NovicesSwordConfig(){ + super("novices_sword", true, Material.STONE_SWORD, "&8Novice's Sword", Arrays.asList("&2Awarded to those who challenge the", "&2Wood League Arena!")); + setEnchantments(Arrays.asList("DAMAGE_ALL,10", "SWEEPING_EDGE,1", "DURABILITY,5")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/OwlCharmConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/OwlCharmConfig.java new file mode 100644 index 000000000..8aaca1d0d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/OwlCharmConfig.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import org.bukkit.Material; + +import java.util.Arrays; + +public class OwlCharmConfig extends CustomItemsConfigFields { + public OwlCharmConfig() { + super("owl_charm", + true, + Material.ELYTRA, + "&bOwl Charm", + Arrays.asList("&aBecome the ultimate nocturnal", "&apredator!")); + setEnchantments(Arrays.asList("VANISHING_CURSE,1")); + setPotionEffects(Arrays.asList("GLOWING,0,target,onHit", "JUMP,2,self,continuous", "NIGHT_VISION,0,self,continuous", "WEAKNESS,0,self,continuous")); + setDropWeight("1"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/RabbitCharmConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/RabbitCharmConfig.java new file mode 100644 index 000000000..c79315e79 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/RabbitCharmConfig.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import org.bukkit.Material; + +import java.util.Arrays; + +public class RabbitCharmConfig extends CustomItemsConfigFields { + public RabbitCharmConfig() { + super("rabbit_charm", + true, + Material.RABBIT_FOOT, + "&bRabbit Charm", + Arrays.asList("&aWith this charm, just about", "&aany destination is only a hop,", "&askip and a jump away!")); + setEnchantments(Arrays.asList("VANISHING_CURSE,1")); + setPotionEffects(Arrays.asList("JUMP,2,self,continuous")); + setDropWeight("1"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/RodOfTheDepthsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/RodOfTheDepthsConfig.java new file mode 100644 index 000000000..7b3aef81a --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/RodOfTheDepthsConfig.java @@ -0,0 +1,20 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class RodOfTheDepthsConfig extends CustomItemsConfigFields { + public RodOfTheDepthsConfig() { + super("rod_of_the_depths", + true, + Material.FISHING_ROD, + "&3Rod of the Depths", + Arrays.asList("&3You want to hear about where", "&3I got this from? Sit down lad,", "&3I've got a tale for ye...")); + setEnchantments(Arrays.asList("LURE,3", "LUCK,1", "DURABILITY,6", "VANISHING_CURSE,1")); + setPotionEffects(Arrays.asList("INVISIBILITY,0,self,onHit", "SLOW,0,self,onHit", "BLINDNESS,0,self,onHit")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/SalamanderCharmConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/SalamanderCharmConfig.java new file mode 100644 index 000000000..6d91893ed --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/SalamanderCharmConfig.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import org.bukkit.Material; + +import java.util.Arrays; + +public class SalamanderCharmConfig extends CustomItemsConfigFields { + public SalamanderCharmConfig() { + super("salamander_charm", + true, + Material.LEATHER, + "&bSalamander Charm", + Arrays.asList("&aAlmost as hot as MagmaGuy's", "&anew mixtape!")); + setEnchantments(Arrays.asList("VANISHING_CURSE,1")); + setPotionEffects(Arrays.asList("FIRE_RESISTANCE,0,self,continuous")); + setDropWeight("1"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/ScorpionCharm.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/ScorpionCharm.java new file mode 100644 index 000000000..11f621cb1 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/ScorpionCharm.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import org.bukkit.Material; + +import java.util.Arrays; + +public class ScorpionCharm extends CustomItemsConfigFields { + public ScorpionCharm() { + super("scorpion_charm", + true, + Material.POISONOUS_POTATO, + "&bScorpion Charm", + Arrays.asList("&aFloat like a butterfly,", "&asting like a bee,", "&apoison like a potato!")); + setEnchantments(Arrays.asList("VANISHING_CURSE,1")); + setPotionEffects(Arrays.asList("POISON,0,target,onHit")); + setDropWeight("1"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/ShulkerCharmConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/ShulkerCharmConfig.java new file mode 100644 index 000000000..167176526 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/ShulkerCharmConfig.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import org.bukkit.Material; + +import java.util.Arrays; + +public class ShulkerCharmConfig extends CustomItemsConfigFields { + public ShulkerCharmConfig() { + super("shulker_charm", + true, + Material.FEATHER, + "&bShulker Charm", + Arrays.asList("&aI believe I can fly", "&aI believe I can touch the sky", "&aAnd you're coming with me!")); + setEnchantments(Arrays.asList("VANISHING_CURSE,1")); + setPotionEffects(Arrays.asList("LEVITATION,0,self,onHit", "LEVITATION,1,target,onHit")); + setDropWeight("1"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/SlowpokeCharmConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/SlowpokeCharmConfig.java new file mode 100644 index 000000000..bcc6ca997 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/SlowpokeCharmConfig.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import org.bukkit.Material; + +import java.util.Arrays; + +public class SlowpokeCharmConfig extends CustomItemsConfigFields { + public SlowpokeCharmConfig() { + super("slowpoke_charm", + true, + Material.CARROT_ON_A_STICK, + "&bSlowpoke Charm", + Arrays.asList("&aLet's just hope it doesn't hit", "&aitself in its confusion...")); + setEnchantments(Arrays.asList("VANISHING_CURSE,1")); + setPotionEffects(Arrays.asList("SLOW,0,self,onHit", "CONFUSION,0,target,onHit")); + setDropWeight("1"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/SummonMerchantScrollConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/SummonMerchantScrollConfig.java new file mode 100644 index 000000000..2313aebd7 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/SummonMerchantScrollConfig.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import org.bukkit.Material; + +import java.util.Arrays; + +public class SummonMerchantScrollConfig extends CustomItemsConfigFields { + public SummonMerchantScrollConfig() { + super("summon_merchant_scroll", + true, + Material.PAPER, + "&6Summon Merchant Scroll", + Arrays.asList("&aNeed to sell an item?", "&aRight-click to activate", "&aor yell &9Jeeves!")); + setEnchantments(Arrays.asList("SUMMON_MERCHANT,1")); + setDropWeight("5"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/SummonWolfScrollConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/SummonWolfScrollConfig.java new file mode 100644 index 000000000..4609d2651 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/SummonWolfScrollConfig.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class SummonWolfScrollConfig extends CustomItemsConfigFields { + public SummonWolfScrollConfig() { + super("summon_wolf_scroll", + true, + Material.PAPER, + "&6Summon Wolf Scroll", + Arrays.asList("&aSummons a good boy", "&ato help you bite Elites!", "&aMake sure you pet it!")); + setEnchantments(Arrays.asList("SUMMON_WOLF,1")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/TheFellerConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/TheFellerConfig.java new file mode 100644 index 000000000..14fbb4d6c --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/TheFellerConfig.java @@ -0,0 +1,20 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class TheFellerConfig extends CustomItemsConfigFields { + public TheFellerConfig() { + super("the_feller", + true, + Material.DIAMOND_AXE, + "&2The Feller", + Arrays.asList("&aEven in your sleep,", "&ayou can feel this axe''s", "&asaplust")); + setEnchantments(Arrays.asList("LOOT_BONUS_BLOCKS,4", "SILK_TOUCH,1", "DURABILITY,6", "DIG_SPEED,6", "VANISHING_CURSE,1")); + setPotionEffects(Arrays.asList("FAST_DIGGING,1,self,continuous", "NIGHT_VISION,0,self,continuous")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/TheStingerConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/TheStingerConfig.java new file mode 100644 index 000000000..b1ab531f6 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/TheStingerConfig.java @@ -0,0 +1,20 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class TheStingerConfig extends CustomItemsConfigFields { + public TheStingerConfig() { + super("the_stinger", + true, + Material.GOLDEN_SWORD, + "&eThe Stinger", + Arrays.asList("&aFloat like a butterfly,", "&asting like a bee!")); + setEnchantments(Arrays.asList("DAMAGE_ALL,1", "DURABILITY,1", "VANISHING_CURSE,1")); + setPotionEffects(Arrays.asList("POISON,0,target,onHit")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/UnbindScrollConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/UnbindScrollConfig.java new file mode 100644 index 000000000..3ec3db0ef --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/UnbindScrollConfig.java @@ -0,0 +1,21 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class UnbindScrollConfig extends CustomItemsConfigFields { + public UnbindScrollConfig() { + super("unbind_scroll", + true, + Material.PAPER, + "&5Unbind Scroll", + Arrays.asList("&5Allows users to unbind one", + "&5soulbound item at an anvil!", + "&5Use wisely!")); + setEnchantments(Arrays.asList("UNBIND,1")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/VampiricCharmConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/VampiricCharmConfig.java new file mode 100644 index 000000000..0320928ba --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/VampiricCharmConfig.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import org.bukkit.Material; + +import java.util.Arrays; + +public class VampiricCharmConfig extends CustomItemsConfigFields { + public VampiricCharmConfig() { + super("vampiric_charm", + true, + Material.STICK, + "&bVampiric Charm", + Arrays.asList("&aNo one can remember where this", "&acame from, and no one can,", "&aforget how dangerous it is...")); + setEnchantments(Arrays.asList("VANISHING_CURSE,1")); + setPotionEffects(Arrays.asList("HEAL,0,self,onHit", "BLINDNESS,0,self,onHit", "SLOW,0,self,onHit")); + setDropWeight("1"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/VeteransBootsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/VeteransBootsConfig.java new file mode 100644 index 000000000..eeed84b63 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/VeteransBootsConfig.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class VeteransBootsConfig extends CustomItemsConfigFields { + public VeteransBootsConfig(){ + super("veterans_boots", true, Material.GOLDEN_BOOTS, "&6Veteran's Boots", Arrays.asList("&2Awarded to those who challenge the", "&2Wood League Arena!")); + setEnchantments(Arrays.asList("PROTECTION_ENVIRONMENTAL,30", "PROTECTION_PROJECTILE,15", "MENDING,1", "DURABILITY,5")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/VeteransChestplateConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/VeteransChestplateConfig.java new file mode 100644 index 000000000..345d78589 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/VeteransChestplateConfig.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class VeteransChestplateConfig extends CustomItemsConfigFields { + public VeteransChestplateConfig(){ + super("veterans_chestplate", true, Material.GOLDEN_CHESTPLATE, "&6Veteran's Chestplate", Arrays.asList("&2Awarded to those who challenge the", "&2Wood League Arena!")); + setEnchantments(Arrays.asList("PROTECTION_ENVIRONMENTAL,30", "PROTECTION_PROJECTILE,15", "MENDING,1", "DURABILITY,5")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/VeteransHelmetConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/VeteransHelmetConfig.java new file mode 100644 index 000000000..743a22d08 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/VeteransHelmetConfig.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class VeteransHelmetConfig extends CustomItemsConfigFields { + public VeteransHelmetConfig(){ + super("veterans_helmet", true, Material.GOLDEN_HELMET, "&6Veteran's Helmet", Arrays.asList("&2Awarded to those who challenge the", "&2Wood League Arena!")); + setEnchantments(Arrays.asList("PROTECTION_ENVIRONMENTAL,30", "PROTECTION_PROJECTILE,15", "MENDING,1", "DURABILITY,5")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/VeteransLeggingsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/VeteransLeggingsConfig.java new file mode 100644 index 000000000..3e71f9fd2 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/VeteransLeggingsConfig.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class VeteransLeggingsConfig extends CustomItemsConfigFields { + public VeteransLeggingsConfig(){ + super("veterans_leggings", true, Material.GOLDEN_LEGGINGS, "&6Veteran's Leggings", Arrays.asList("&2Awarded to those who challenge the", "&2Wood League Arena!")); + setEnchantments(Arrays.asList("PROTECTION_ENVIRONMENTAL,30", "PROTECTION_PROJECTILE,15", "MENDING,1", "DURABILITY,5")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/VeteransSwordConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/VeteransSwordConfig.java new file mode 100644 index 000000000..4ecc6045d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/VeteransSwordConfig.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class VeteransSwordConfig extends CustomItemsConfigFields { + public VeteransSwordConfig(){ + super("veterans_sword", true, Material.GOLDEN_SWORD, "&6Veteran's Sword", Arrays.asList("&2Awarded to those who challenge the", "&2Wood League Arena!")); + setEnchantments(Arrays.asList("DAMAGE_ALL,30", "KNOCKBACK,2", "MENDING,1", "SWEEPING_EDGE,1", "DURABILITY,5")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/WerewolfBoneItem.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/WerewolfBoneItem.java new file mode 100644 index 000000000..f6d9bff4e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/WerewolfBoneItem.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class WerewolfBoneItem extends CustomItemsConfigFields { + public WerewolfBoneItem() { + super("werewolf_bone", + true, + Material.BONE, + "&6Werewolf Bone", + Arrays.asList("&aHaving killed the alpha,", "&athis temporarily makes you!", "&athe wolves' new leader")); + setEnchantments(Arrays.asList("SUMMON_WOLF,1")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/WolfsbaneItem.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/WolfsbaneItem.java new file mode 100644 index 000000000..93e85d278 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/WolfsbaneItem.java @@ -0,0 +1,20 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class WolfsbaneItem extends CustomItemsConfigFields { + public WolfsbaneItem() { + super("wolfsbane", + true, + Material.IRON_SWORD, + "&7Wolfsbane", + Arrays.asList("&aMade from the remains of", "&aan alpha werewolf, all", "&awolves cower at the sight of it.")); + setEnchantments(Arrays.asList("DAMAGE_ALL,1", "FIRE_ASPECT,4", "DURABILITY,5", "LOOT_BONUS_MOBS,5")); + setPotionEffects(Arrays.asList("FAST_DIGGING,2,self,onHit", "NIGHT_VISION,0,self,continuous")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/ZombieKingsAxeConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/ZombieKingsAxeConfig.java new file mode 100644 index 000000000..3ded99b92 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customitems/premade/ZombieKingsAxeConfig.java @@ -0,0 +1,21 @@ +package com.magmaguy.elitemobs.config.customitems.premade; + +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Material; + +import java.util.Arrays; + +public class ZombieKingsAxeConfig extends CustomItemsConfigFields { + public ZombieKingsAxeConfig() { + super("zombie_kings_axe", + true, + Material.GOLDEN_AXE, + "&4Zombie King's Axe", + Arrays.asList("The axe of the one Zombies", "call their king.", "The bloodlust is palpable.")); + setEnchantments(Arrays.asList("DAMAGE_ALL,10", "DAMAGE_UNDEAD,5", "DIG_SPEED,5", "DURABILITY,5", "KNOCKBACK,3", + "FIRE_ASPECT,4", "LOOT_BONUS_MOBS,5", "WATER_WORKER,5", "FLAMETHROWER,1")); + setPotionEffects(Arrays.asList("FAST_DIGGING,0,self,onHit", "NIGHT_VISION,0,self,continuous", "WITHER,0,target,onHit")); + setItemType(CustomItem.ItemType.UNIQUE); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customquests/CustomQuestsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customquests/CustomQuestsConfig.java new file mode 100644 index 000000000..81494039b --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customquests/CustomQuestsConfig.java @@ -0,0 +1,20 @@ +package com.magmaguy.elitemobs.config.customquests; + +import com.magmaguy.elitemobs.config.CustomConfig; + +import java.util.HashMap; + +public class CustomQuestsConfig extends CustomConfig { + private static HashMap customQuests = new HashMap<>(); + + public CustomQuestsConfig() { + super("customquests", "com.magmaguy.elitemobs.config.customquests.premade", CustomQuestsConfigFields.class); + customQuests = new HashMap<>(); + for (String key : super.getCustomConfigFieldsHashMap().keySet()) + customQuests.put(key, (CustomQuestsConfigFields) super.getCustomConfigFieldsHashMap().get(key)); + } + + public static HashMap getCustomQuests() { + return customQuests; + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customquests/CustomQuestsConfigFields.java b/src/main/java/com/magmaguy/elitemobs/config/customquests/CustomQuestsConfigFields.java new file mode 100644 index 000000000..883d0cf1d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customquests/CustomQuestsConfigFields.java @@ -0,0 +1,107 @@ +package com.magmaguy.elitemobs.config.customquests; + +import com.magmaguy.elitemobs.config.CustomConfigFields; +import com.magmaguy.elitemobs.config.CustomConfigFieldsInterface; +import lombok.Getter; +import lombok.Setter; + +import java.util.ArrayList; +import java.util.List; + +public class CustomQuestsConfigFields extends CustomConfigFields implements CustomConfigFieldsInterface { + + @Getter + @Setter + List temporaryPermissions = new ArrayList<>(); + @Getter + @Setter + List questAcceptDialog = new ArrayList<>(); + @Getter + @Setter + private int questLevel = 0; + @Getter + @Setter + private List customObjectivesList = new ArrayList<>(); + @Getter + @Setter + private List customRewardsList = new ArrayList<>(); + @Getter + @Setter + //Required permission to accept quest + private String questAcceptPermission = ""; + @Getter + //Permission which locks players out of a quest + private String questLockoutPermission = ""; + @Getter + @Setter + private int questLockoutMinutes = -1; + @Getter + @Setter + private String questName = ""; + @Getter + @Setter + private List questLore = new ArrayList<>(); + @Getter + @Setter + private List questCompleteDialog = new ArrayList<>(); + @Getter + @Setter + //placeholders: $player, $getX, $getY, $getZ + private List questCompleteCommands = new ArrayList<>(); + @Getter + @Setter + private String turnInNPC = ""; + @Getter + @Setter + private boolean trackable = true; + + public CustomQuestsConfigFields(String filename, + boolean isEnabled, + List customQuestObjective, + List customQuestReward, + int questLevel, + String questName, + List questLore) { + super(filename, isEnabled); + this.customObjectivesList = customQuestObjective; + this.customRewardsList = customQuestReward; + this.questLevel = questLevel; + this.questName = questName; + this.questLore = questLore; + } + + /** + * Used by plugin-generated files (defaults) + * + * @param filename + * @param isEnabled + */ + public CustomQuestsConfigFields(String filename, + boolean isEnabled) { + super(filename, isEnabled); + } + + public void setQuestLockoutPermission() { + this.questLockoutPermission = "elitequest." + getFilename(); + } + + @Override + public void processConfigFields() { + this.isEnabled = processBoolean("isEnabled", isEnabled, true, true); + this.customObjectivesList = processStringList("customObjectives", customObjectivesList, new ArrayList<>(), true); + this.customRewardsList = processStringList("customRewards", customRewardsList, new ArrayList<>(), true); + this.questAcceptPermission = processString("questAcceptPermission", questAcceptPermission, null, false); + this.questLockoutPermission = processString("questLockoutPermission", questLockoutPermission, null, false); + this.questLockoutMinutes = processInt("questLockoutMinutes", questLockoutMinutes, -1, false); + this.questName = processString("name", questName, filename, true); + this.questLore = processStringList("questLore", questLore, new ArrayList<>(), false); + this.temporaryPermissions = processStringList("temporaryPermissions", temporaryPermissions, new ArrayList<>(), false); + this.questAcceptDialog = processStringList("questAcceptDialog", questAcceptDialog, new ArrayList<>(), false); + this.questCompleteDialog = processStringList("questCompleteMessage", questCompleteDialog, new ArrayList<>(), false); + this.questCompleteCommands = processStringList("questCompleteCommands", questCompleteCommands, new ArrayList<>(), false); + this.turnInNPC = processString("turnInNPC", turnInNPC, "", false); + this.trackable = processBoolean("trackable", trackable, true, false); + } + + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customquests/premade/TestQuestConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customquests/premade/TestQuestConfig.java new file mode 100644 index 000000000..6c0c60a8a --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customquests/premade/TestQuestConfig.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.customquests.premade; + +import com.magmaguy.elitemobs.config.customquests.CustomQuestsConfigFields; + +import java.util.Arrays; + +public class TestQuestConfig extends CustomQuestsConfigFields { + public TestQuestConfig() { + super("test_quest", + true, + Arrays.asList("KILL_CUSTOM:filename=test_boss.yml:amount=1"), + Arrays.asList("filename=magmaguys_toothpick.yml:amount=1:chance=1"), + 0, + "Kill the Test Boss", + Arrays.asList("&cEnd the test boss' reign of terror!")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customquests/premade/WelcomeQuest0Config.java b/src/main/java/com/magmaguy/elitemobs/config/customquests/premade/WelcomeQuest0Config.java new file mode 100644 index 000000000..98cb44f63 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customquests/premade/WelcomeQuest0Config.java @@ -0,0 +1,28 @@ +package com.magmaguy.elitemobs.config.customquests.premade; + +import com.magmaguy.elitemobs.config.customquests.CustomQuestsConfigFields; + +import java.util.Arrays; + +public class WelcomeQuest0Config extends CustomQuestsConfigFields { + public WelcomeQuest0Config() { + super("ag_welcome_quest_0.yml", + true, + Arrays.asList( + "DIALOG:" + + "filename=guide_1.yml:" + + "npcName=Odigos:" + + "location=at the Adventurer's Guild:" + + "dialog=&8[&aCasus&8]&f Welcome to the Adventurer's Guild Hub, the hub for all things EliteMobs! \nYou can always get back here using &2/ag&f! \nTalk to me again for a quest!" + ), + Arrays.asList("currencyAmount=50:amount=1:chance=1"), + 1, + "&2Finding the AG!", + Arrays.asList("Discover the Adventurer's Guild Hub using the command &2/ag &0or &2/adventurersguild !") + ); + setQuestLockoutPermission(); + setTurnInNPC("guide_1.yml"); + setQuestAcceptDialog(Arrays.asList("&8[Odigos]&f Alright, make sure you use &2/ag &f or &2/adventurersguild&f to head off to the Adventurer's Guild Hub!", + "Make sure you talk to Casus when you're there!")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customquests/premade/WelcomeQuest1Config.java b/src/main/java/com/magmaguy/elitemobs/config/customquests/premade/WelcomeQuest1Config.java new file mode 100644 index 000000000..2e9de5589 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customquests/premade/WelcomeQuest1Config.java @@ -0,0 +1,37 @@ +package com.magmaguy.elitemobs.config.customquests.premade; + +import com.magmaguy.elitemobs.config.customquests.CustomQuestsConfigFields; + +import java.util.Arrays; +import java.util.Collections; + +public class WelcomeQuest1Config extends CustomQuestsConfigFields { + public WelcomeQuest1Config() { + super("ag_welcome_quest_1.yml", + true, + Arrays.asList( + "DIALOG:filename=back_teleporter.yml:npcName=Hermes:location=by the gate:dialog=&8[&aHermes&8]&f I take you back to where you were before! Just talk to me again!", + "DIALOG:filename=barkeep.yml:npcName=Bartley:location=in the main building:dialog=&8[&aBartley&8]&f Need a stiff drink? My drinks pack an extra punch!", + "DIALOG:filename=blacksmith.yml:npcName=Greg:location=in the main building:dialog=&8[&aGreg&8]&f Want to buy or sell something? I've got a little of everything!", + "DIALOG:filename=combat_instructor.yml:npcName=Charles:location=next to the main building:dialog=&8[&aCharles&8]&f Want to learn about fighting elites? Just talk to me!", + "DIALOG:filename=enhancer_config.yml:npcName=Tim:location=under the main building:dialog=&8[&aTim&8]&f Want to upgrade your Elite Items? Just get an upgrade orb from Sam over there!", + "DIALOG:filename=guild_attendant.yml:npcName=Gillian:location=in the main building:dialog=&8[&aGillian&8]&f Do you seek power? Do you desire to reach new heights? Talk to me to unlock new guild ranks, and reach levels of power you never thought to be possible!", + "DIALOG:filename=quest_giver.yml:npcName=Qel'Thuzad:location=in the main building:dialog=&8[&aQel'Thuzad&8]&f These Elite monsters, where do they keep coming from?" + System.lineSeparator() + "Ah, never mind that for now, we are always in need of more people to assist us in slaying quests!" + System.lineSeparator() + "Just talk to me to get one!", + "DIALOG:filename=refiner_config.yml:npcName=Ralph:location=under the main building:dialog=&8[&aRalph&8]&f Get more out of your scrap by upgrading it! Just talk to me at any time.", + "DIALOG:filename=repairman_config.yml:npcName=Reggie:location=under the main building:dialog=&8[&aReggie&8]&f Need your Elite items repaired? Just bring me some scrap, and I'll make them as good as new!" + System.lineSeparator() + "Remember, the higher the level of your scrap, the better I can repair you Elite item!", + "DIALOG:filename=scrapper_config.yml:npcName=Kelly:location=under the main building:dialog=&8[&aKelly&8]&f Got extra Elite items? Don't know what to do with them? Give them to me, and I'll turn them into scrap! " + System.lineSeparator() + " You can use scrap to do lots of things, like repairing or upgrading Elite items!", + "DIALOG:filename=smelter.yml:npcName=Sam:location=under the main building:dialog=&8[&aSam&8]&f Got extra scrap? I can refine that into Upgrade Orbs, which you can give to Tim to upgrade your Elite items with!", + "DIALOG:filename=special_blacksmith.yml:npcName=Grog:location=under the main building:dialog=&8[&aGrog&8]&f Want to buy special items? I've got just the thing!", + "DIALOG:filename=unbinder.yml:npcName=Ulfric:location=under the main building:dialog=&8[&aUlfric&8]&f If you bring me a very special and rare item, I can unbind your Elite items." + System.lineSeparator() + " You don't yet look prepared to take this challenge on, but you can make killing the Binder of Worlds your ultimate goal, if you dare." + ), + Arrays.asList( + "filename=magmaguys_toothpick.yml:amount=1:chance=1", + "currencyAmount=750:amount=1:chance=1" + ), + 1, + "&2Welcome to the AG!", + Collections.singletonList("&aMeet the Adventurer's Guild NPCs!") + ); + setQuestLockoutPermission(); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customquests/premade/XmasQuest0Config.java b/src/main/java/com/magmaguy/elitemobs/config/customquests/premade/XmasQuest0Config.java new file mode 100644 index 000000000..f69eb2c46 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customquests/premade/XmasQuest0Config.java @@ -0,0 +1,35 @@ +package com.magmaguy.elitemobs.config.customquests.premade; + +import com.magmaguy.elitemobs.config.customquests.CustomQuestsConfigFields; + +import java.util.Arrays; + +public class XmasQuest0Config extends CustomQuestsConfigFields { + public XmasQuest0Config() { + super("xmas_quest_0", + true, + Arrays.asList("FETCH_ITEM:filename=xmas_lost_present.yml:amount=10:itemName=Lost Present"), + Arrays.asList( + "filename=xmas_treat.yml:amount=10:chance=.3", + "filename=xmas_treat_v2.yml:amount=1:chance=.3", + "filename=xmas_and_gold.yml:amount=1:chance=.2", + "filename=xmas_and_goooooold.yml:amount=1:chance=.2", + "filename=xmas_silver.yml:amount=1:chance=.2", + "filename=xmas_siiiiilver.yml:amount=1:chance=.2", + "filename=xmas_peppermint.yml:amount=1:chance=.1", + "filename=xmas_cornelius_pick.yml:amount=1:chance=.1", + "filename=xmas_substitute_elf_practice.yml:amount=1:chance=.1", + "currencyAmount=300:amount=1:chance=.3", + "currencyAmount=300:amount=1:chance=.3", + "currencyAmount=300:amount=1:chance=.3" + ), + 10, + "&2Find the lost gifts!", + Arrays.asList("I seem to have lost some Christmas gifts along the way, would you help a poor old man find them again?", + "I will let you open one of them in return!")); + super.setQuestAcceptDialog(Arrays.asList("&8[&cSaint Nick&8]&f Thank you! I will be waiting here for you!")); + super.setQuestCompleteDialog(Arrays.asList("&8[&cSaint Nick&8]&f Thank you for your help! " + + "There are still some lost gifts out there, talk to me again if you want to help out more!")); + super.setTemporaryPermissions(Arrays.asList("elitequest.xmas_quest.yml")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customspawns/CustomSpawnConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customspawns/CustomSpawnConfig.java new file mode 100644 index 000000000..75312b5b5 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customspawns/CustomSpawnConfig.java @@ -0,0 +1,27 @@ +package com.magmaguy.elitemobs.config.customspawns; + +import com.magmaguy.elitemobs.config.CustomConfig; + +import java.util.HashMap; + +public class CustomSpawnConfig extends CustomConfig { + + private static HashMap customSpawns = new HashMap<>(); + + public CustomSpawnConfig() { + super("customspawns", "com.magmaguy.elitemobs.config.customspawns.premade", CustomSpawnConfigFields.class); + customSpawns = new HashMap<>(); + for (String key : super.getCustomConfigFieldsHashMap().keySet()) + if (super.getCustomConfigFieldsHashMap().get(key).isEnabled()) + customSpawns.put(key, (CustomSpawnConfigFields) super.getCustomConfigFieldsHashMap().get(key)); + } + + public static HashMap getCustomSpawns() { + return customSpawns; + } + + public static CustomSpawnConfigFields getCustomEvent(String fileName) { + return customSpawns.get(fileName); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customspawns/CustomSpawnConfigFields.java b/src/main/java/com/magmaguy/elitemobs/config/customspawns/CustomSpawnConfigFields.java new file mode 100644 index 000000000..ac263aacd --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customspawns/CustomSpawnConfigFields.java @@ -0,0 +1,73 @@ +package com.magmaguy.elitemobs.config.customspawns; + +import com.magmaguy.elitemobs.config.CustomConfigFields; +import com.magmaguy.elitemobs.config.CustomConfigFieldsInterface; +import com.magmaguy.elitemobs.events.MoonPhaseDetector; +import lombok.Getter; +import lombok.Setter; +import org.bukkit.World; +import org.bukkit.block.Biome; + +import java.util.ArrayList; +import java.util.List; + +public class CustomSpawnConfigFields extends CustomConfigFields implements CustomConfigFieldsInterface { + + @Getter + @Setter + int lowestYLevel = 0; + @Getter + @Setter + int highestYLevel = 320; + @Getter + @Setter + List validWorlds = new ArrayList<>(); + @Getter + @Setter + List validWorldEnvironments = new ArrayList<>(); + @Getter + @Setter + List validBiomes = new ArrayList<>(); + @Getter + @Setter + private long earliestTime = 0; + @Getter + @Setter + private long latestTime = 24000; + @Getter + @Setter + private MoonPhaseDetector.MoonPhase moonPhase = null; + @Getter + @Setter + private boolean bypassWorldGuard = false; + @Getter + @Setter + private boolean canSpawnInLight = false; + @Getter + @Setter + private boolean isSurfaceSpawn = false; + @Getter + @Setter + private boolean isUndergroundSpawn = false; + + public CustomSpawnConfigFields(String filename, boolean isEnabled) { + super(filename, isEnabled); + } + + @Override + public void processConfigFields() { + this.isEnabled = processBoolean("isEnabled", isEnabled, true, true); + this.lowestYLevel = processInt("lowestYLevel", lowestYLevel, 0, false); + this.highestYLevel = processInt("highestYLevel", highestYLevel, 320, false); + this.validWorlds = processWorldList("validWorlds", validWorlds, new ArrayList<>(), false); + this.validWorldEnvironments = processEnumList("validWorldEnvironments", validWorldEnvironments, new ArrayList<>(), World.Environment.class, false); + this.validBiomes = processEnumList("validBiomes", validBiomes, new ArrayList<>(), Biome.class, false); + this.earliestTime = processLong("earliestTime", earliestTime, 0, false); + this.latestTime = processLong("latestTime", latestTime, 24000, false); + this.moonPhase = processEnum("moonPhase", moonPhase, null, MoonPhaseDetector.MoonPhase.class, false); + this.bypassWorldGuard = processBoolean("bypassWorldGuard", bypassWorldGuard, false, false); + this.canSpawnInLight = processBoolean("canSpawnInLight", canSpawnInLight, false, false); + this.isSurfaceSpawn = processBoolean("isSurfaceSpawn", isSurfaceSpawn, false, false); + this.isUndergroundSpawn = processBoolean("isUndergroundSpawn", isUndergroundSpawn, false, false); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customspawns/premade/DeadMoonSpawn.java b/src/main/java/com/magmaguy/elitemobs/config/customspawns/premade/DeadMoonSpawn.java new file mode 100644 index 000000000..bba7d0f51 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customspawns/premade/DeadMoonSpawn.java @@ -0,0 +1,23 @@ +package com.magmaguy.elitemobs.config.customspawns.premade; + +import com.magmaguy.elitemobs.config.customspawns.CustomSpawnConfigFields; +import com.magmaguy.elitemobs.events.MoonPhaseDetector; +import org.bukkit.World; + +import java.util.ArrayList; +import java.util.Arrays; + +public class DeadMoonSpawn extends CustomSpawnConfigFields { + public DeadMoonSpawn() { + super("dead_moon_spawn", true); + setSurfaceSpawn(true); + try { + setValidWorldEnvironments(new ArrayList<>(Arrays.asList(World.Environment.NORMAL, World.Environment.CUSTOM))); + } catch (NoSuchFieldError err) { + //So this happens when CUSTOM doesn't exist, which it should but in some bugged releases it doesn't. + setValidWorldEnvironments(new ArrayList<>(Arrays.asList(World.Environment.NORMAL))); + } + setEarliestTime(12000); + setMoonPhase(MoonPhaseDetector.MoonPhase.NEW_MOON); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customspawns/premade/FullMoonSpawn.java b/src/main/java/com/magmaguy/elitemobs/config/customspawns/premade/FullMoonSpawn.java new file mode 100644 index 000000000..86a94ae92 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customspawns/premade/FullMoonSpawn.java @@ -0,0 +1,23 @@ +package com.magmaguy.elitemobs.config.customspawns.premade; + +import com.magmaguy.elitemobs.config.customspawns.CustomSpawnConfigFields; +import com.magmaguy.elitemobs.events.MoonPhaseDetector; +import org.bukkit.World; + +import java.util.ArrayList; +import java.util.Arrays; + +public class FullMoonSpawn extends CustomSpawnConfigFields { + public FullMoonSpawn() { + super("full_moon_spawn", true); + setSurfaceSpawn(true); + try { + setValidWorldEnvironments(new ArrayList<>(Arrays.asList(World.Environment.NORMAL, World.Environment.CUSTOM))); + } catch (NoSuchFieldError ex) { + //So this happens when CUSTOM doesn't exist, which it should but in some bugged releases it doesn't. + setValidWorldEnvironments(new ArrayList<>(Arrays.asList(World.Environment.NORMAL))); + } + setEarliestTime(12000); + setMoonPhase(MoonPhaseDetector.MoonPhase.FULL_MOON); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customspawns/premade/NighttimeSurfaceSpawn.java b/src/main/java/com/magmaguy/elitemobs/config/customspawns/premade/NighttimeSurfaceSpawn.java new file mode 100644 index 000000000..a322ce931 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customspawns/premade/NighttimeSurfaceSpawn.java @@ -0,0 +1,23 @@ +package com.magmaguy.elitemobs.config.customspawns.premade; + +import com.magmaguy.elitemobs.config.customspawns.CustomSpawnConfigFields; +import org.bukkit.World; + +import java.util.ArrayList; +import java.util.Arrays; + +public class NighttimeSurfaceSpawn extends CustomSpawnConfigFields { + public NighttimeSurfaceSpawn() { + super("nighttime_surface_spawn", + true); + setSurfaceSpawn(true); + try { + setValidWorldEnvironments(new ArrayList<>(Arrays.asList(World.Environment.NORMAL, World.Environment.CUSTOM))); + } catch (NoSuchFieldError ex) { + //So this happens when CUSTOM doesn't exist, which it should but in some bugged releases it doesn't. + setValidWorldEnvironments(new ArrayList<>(Arrays.asList(World.Environment.NORMAL))); + } + setEarliestTime(12000); + setBypassWorldGuard(false); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customspawns/premade/NormalSurfaceSpawn.java b/src/main/java/com/magmaguy/elitemobs/config/customspawns/premade/NormalSurfaceSpawn.java new file mode 100644 index 000000000..edf40f214 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customspawns/premade/NormalSurfaceSpawn.java @@ -0,0 +1,22 @@ +package com.magmaguy.elitemobs.config.customspawns.premade; + +import com.magmaguy.elitemobs.config.customspawns.CustomSpawnConfigFields; +import org.bukkit.World; + +import java.util.ArrayList; +import java.util.Arrays; + +public class NormalSurfaceSpawn extends CustomSpawnConfigFields { + public NormalSurfaceSpawn() { + super("normal_surface_spawn", + true); + setSurfaceSpawn(true); + try { + setValidWorldEnvironments(new ArrayList<>(Arrays.asList(World.Environment.NORMAL, World.Environment.CUSTOM))); + } catch (NoSuchFieldError ex) { + //So this happens when CUSTOM doesn't exist, which it should but in some bugged releases it doesn't. + setValidWorldEnvironments(new ArrayList<>(Arrays.asList(World.Environment.NORMAL))); + } + setBypassWorldGuard(false); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customtreasurechests/CustomTreasureChestConfigFields.java b/src/main/java/com/magmaguy/elitemobs/config/customtreasurechests/CustomTreasureChestConfigFields.java new file mode 100644 index 000000000..6836b4028 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customtreasurechests/CustomTreasureChestConfigFields.java @@ -0,0 +1,194 @@ +package com.magmaguy.elitemobs.config.customtreasurechests; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.CustomConfigFields; +import com.magmaguy.elitemobs.items.customloottable.CustomLootTable; +import com.magmaguy.elitemobs.treasurechest.TreasureChest; +import com.magmaguy.elitemobs.utils.ConfigurationLocation; +import com.magmaguy.elitemobs.utils.InfoMessage; +import com.magmaguy.elitemobs.utils.WarningMessage; +import lombok.Getter; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +import java.util.ArrayList; +import java.util.List; + +public class CustomTreasureChestConfigFields extends CustomConfigFields { + + @Getter + private Material chestMaterial = Material.CHEST; + @Getter + private BlockFace facing = BlockFace.NORTH; + @Getter + private int chestTier = 0; + @Getter + private TreasureChest.DropStyle dropStyle = TreasureChest.DropStyle.SINGLE; + @Getter + private int restockTimer = 0; + @Getter + private List lootList = new ArrayList<>(); + @Getter + private double mimicChance = 0; + @Getter + private List mimicCustomBossesList = new ArrayList<>(); + @Getter + private List restockTimers = new ArrayList<>(); + @Getter + private List effects = new ArrayList<>(); + @Getter + private String worldName; + @Getter + private Location location; + @Getter + private long restockTime = 0L; + @Getter + private List locations = new ArrayList<>(); + @Getter + private CustomLootTable customLootTable = null; + + + public CustomTreasureChestConfigFields(String filename, boolean isEnabled) { + super(filename, isEnabled); + } + + /** + * Called to write defaults for a new Custom Boss Mob Entity + */ + public CustomTreasureChestConfigFields(String fileName, + boolean isEnabled, + Material chestMaterial, + BlockFace facing, + int chestTier, + Location location, + TreasureChest.DropStyle dropStyle, + int restockTimer, + List lootList, + double mimicChance, + List mimicCustomBossesList, + long restockTime, + List restockTimers, + List effects) { + + super(fileName, isEnabled); + this.chestMaterial = chestMaterial; + this.facing = facing; + this.chestTier = chestTier; + this.location = location; + this.dropStyle = dropStyle; + this.restockTimer = restockTimer; + this.lootList = lootList; + this.mimicChance = mimicChance; + this.mimicCustomBossesList = mimicCustomBossesList; + this.restockTime = restockTime; + this.restockTimers = restockTimers; + this.effects = effects; + } + + @Override + public void processConfigFields() { + this.isEnabled = processBoolean("isEnabled", isEnabled, false, false); + this.chestMaterial = processEnum("chestType", chestMaterial, Material.CHEST, Material.class, true); + this.facing = processEnum("facing", facing, BlockFace.NORTH, BlockFace.class, true); + this.chestTier = processInt("chestTier", chestTier, 0, true); + this.worldName = processString("location", worldName, null, false); + if (worldName != null) + worldName = worldName.split(",")[0]; + this.dropStyle = processEnum("dropStyle", dropStyle, TreasureChest.DropStyle.SINGLE, TreasureChest.DropStyle.class, true); + this.restockTimer = processInt("restockTimer", restockTimer, 0, true); + this.lootList = processStringList("lootList", lootList, new ArrayList<>(), true); + this.customLootTable = new CustomLootTable(this); + this.mimicChance = processDouble("mimicChance", mimicChance, 0, true); + this.mimicCustomBossesList = processStringList("mimicCustomBossesList", mimicCustomBossesList, new ArrayList<>(), true); + this.restockTime = processLong("restockTime", restockTime, 0, false); + this.restockTimers = processStringList("restockTimers", restockTimers, new ArrayList<>(), false); + this.effects = processStringList("effects", effects, new ArrayList<>(), false); + this.locations = processStringList("locations", locations, new ArrayList<>(), false); + this.location = processLocation("location", location, null, false); + if (location == null && locations.isEmpty()) + new InfoMessage("Custom Treasure Chest in file " + filename + " does not have a defined location(s)! It will not spawn."); + else + new TreasureChest(this, location, restockTime); + for (String string : locations) { + String[] strings = string.split(":"); + Location location = ConfigurationLocation.serialize(strings[0]); + if (location == null) { + new WarningMessage("Bad location entry in locations for " + filename + " . Entry: " + strings[0]); + continue; + } + long timestamp = 0; + if (strings.length > 1) { + try { + timestamp = Long.parseLong(strings[1]); + } catch (Exception exception) { + new WarningMessage("Bad unix timestamp in locations for " + filename + " . Entry: " + strings[0]); + } + } + new TreasureChest(this, location, timestamp); + } + } + + /** + * For the new format of Treasure chests, which have multiple locations per file + * @param chestInstanceLocation + * @param unixTimeStamp + * @return + */ + public TreasureChest updateTreasureChest(Location chestInstanceLocation, long unixTimeStamp) { + int index = -1; + String deserializedLocation = ConfigurationLocation.deserialize(chestInstanceLocation.getBlock().getLocation()); + for (String string : locations) + if (string.split(":")[0].equals(deserializedLocation)) { + index = locations.indexOf(string); + break; + } + String serializedUpdatedLocation = deserializedLocation + ":" + unixTimeStamp; + TreasureChest treasureChest = null; + if (index != -1) { + //case for existing treasure chest getting a cooldown + locations.set(index, serializedUpdatedLocation); + } else { + //case for a new treasure chest + locations.add(serializedUpdatedLocation); + treasureChest = new TreasureChest(this, chestInstanceLocation, unixTimeStamp); + } + fileConfiguration.set("locations", locations); + ConfigurationEngine.fileSaverCustomValues(fileConfiguration, file); + return treasureChest; + } + + public void removeTreasureChest(Location chestInstanceLocation) { + if (locations.isEmpty()) return; + int index = -1; + String deserializedLocation = ConfigurationLocation.deserialize(chestInstanceLocation.getBlock().getLocation()); + for (String string : locations) + if (string.split(":")[0].equals(deserializedLocation)) { + index = locations.indexOf(string); + break; + } + if (index < 0) + return; + String location = locations.get(index); + locations.remove(location); + fileConfiguration.set("locations", locations); + ConfigurationEngine.fileSaverCustomValues(fileConfiguration, file); + } + + public void setRestockTime(Location location, long newRestockTime) { + if (!locations.isEmpty()) { + updateTreasureChest(location, newRestockTime); + return; + } + + this.restockTime = newRestockTime; + this.fileConfiguration.set("restockTime", newRestockTime); + try { + fileConfiguration.save(file); + } catch (Exception ex) { + Bukkit.getLogger().warning("[EliteMobs] Attempted to update restock time for a custom treasure chest and failed, did you delete it during runtime?"); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customtreasurechests/CustomTreasureChestsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customtreasurechests/CustomTreasureChestsConfig.java new file mode 100644 index 000000000..c2216156d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customtreasurechests/CustomTreasureChestsConfig.java @@ -0,0 +1,52 @@ +package com.magmaguy.elitemobs.config.customtreasurechests; + +import com.magmaguy.elitemobs.config.CustomConfig; +import com.magmaguy.elitemobs.treasurechest.TreasureChest; +import com.magmaguy.elitemobs.utils.WarningMessage; +import lombok.Getter; +import org.bukkit.Location; +import org.bukkit.entity.Player; + +import java.util.HashMap; + +public class CustomTreasureChestsConfig extends CustomConfig { + + @Getter + private static HashMap customTreasureChestConfigFields = new HashMap<>(); + + public CustomTreasureChestsConfig() { + super("customtreasurechests", "com.magmaguy.elitemobs.config.customtreasurechests.premade", CustomTreasureChestConfigFields.class); + customTreasureChestConfigFields = new HashMap<>(); + for (String key : super.getCustomConfigFieldsHashMap().keySet()) + if (super.getCustomConfigFieldsHashMap().get(key).isEnabled()) + customTreasureChestConfigFields.put(key, (CustomTreasureChestConfigFields) super.getCustomConfigFieldsHashMap().get(key)); + } + + public static void addTreasureChestEntry(Player player, String customChestFileName) { + CustomTreasureChestConfigFields customTreasureChestConfigFields = getCustomTreasureChestConfigFields().get(customChestFileName); + if (customTreasureChestConfigFields == null) { + player.sendMessage("[EM] Invalid Treasure Chest file name!"); + return; + } + addTreasureChestEntry(new Location(player.getWorld(), player.getLocation().getX(), player.getLocation().getY(), player.getLocation().getZ()), customChestFileName); + } + + public static TreasureChest addTreasureChestEntry(Location location, String customChestFileName) { + CustomTreasureChestConfigFields customTreasureChestConfigFields = getCustomTreasureChestConfigFields().get(customChestFileName); + if (location == null) { + new WarningMessage("Failed to commit a location for a treasure chest!"); + return null; + } + return customTreasureChestConfigFields.updateTreasureChest(location, 0); + } + + public static void removeTreasureChestEntry(Location location, String customChestFileName) { + CustomTreasureChestConfigFields customTreasureChestConfigFields = getCustomTreasureChestConfigFields().get(customChestFileName); + if (location == null || customTreasureChestConfigFields == null) { + new WarningMessage("Failed to remove a location for a treasure chest!"); + return; + } + customTreasureChestConfigFields.removeTreasureChest(location); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/customtreasurechests/premade/TestCustomTreasureChestConfig.java b/src/main/java/com/magmaguy/elitemobs/config/customtreasurechests/premade/TestCustomTreasureChestConfig.java new file mode 100644 index 000000000..cfbffe21c --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/customtreasurechests/premade/TestCustomTreasureChestConfig.java @@ -0,0 +1,29 @@ +package com.magmaguy.elitemobs.config.customtreasurechests.premade; + +import com.magmaguy.elitemobs.config.customtreasurechests.CustomTreasureChestConfigFields; +import com.magmaguy.elitemobs.treasurechest.TreasureChest; +import org.bukkit.Material; +import org.bukkit.block.BlockFace; + +import java.util.Arrays; + +public class TestCustomTreasureChestConfig extends CustomTreasureChestConfigFields { + + public TestCustomTreasureChestConfig() { + super("test_custom_treasure_config", + true, + Material.CHEST, + BlockFace.NORTH, + 0, + null, + TreasureChest.DropStyle.SINGLE, + 1, + Arrays.asList("magmaguys_toothpick.yml:1"), + 0.5, + Arrays.asList("test_boss.yml:1"), + 0, + null, + Arrays.asList("BARRIER")); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/DungeonPackagerConfig.java b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/DungeonPackagerConfig.java new file mode 100644 index 000000000..f5998bee5 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/DungeonPackagerConfig.java @@ -0,0 +1,23 @@ +package com.magmaguy.elitemobs.config.dungeonpackager; + +import com.magmaguy.elitemobs.config.CustomConfig; +import com.magmaguy.elitemobs.dungeons.Minidungeon; +import lombok.Getter; + +import java.util.HashMap; +import java.util.Map; + +public class DungeonPackagerConfig extends CustomConfig { + + @Getter + private static Map dungeonPackages = new HashMap<>(); + + public DungeonPackagerConfig() { + super("dungeonpackages", "com.magmaguy.elitemobs.config.dungeonpackager.premade", DungeonPackagerConfigFields.class); + dungeonPackages = new HashMap<>(); + for (String key : super.getCustomConfigFieldsHashMap().keySet()) + dungeonPackages.put(key, (DungeonPackagerConfigFields) super.getCustomConfigFieldsHashMap().get(key)); + dungeonPackages.values().forEach(Minidungeon::new); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/DungeonPackagerConfigFields.java b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/DungeonPackagerConfigFields.java new file mode 100644 index 000000000..4d075b204 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/DungeonPackagerConfigFields.java @@ -0,0 +1,252 @@ +package com.magmaguy.elitemobs.config.dungeonpackager; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.CustomConfigFields; +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import com.magmaguy.elitemobs.config.customtreasurechests.CustomTreasureChestConfigFields; +import com.magmaguy.elitemobs.utils.ConfigurationLocation; +import com.magmaguy.elitemobs.utils.DebugBlockLocation; +import com.magmaguy.elitemobs.utils.WarningMessage; +import lombok.Getter; +import lombok.Setter; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.List; + +public class DungeonPackagerConfigFields extends CustomConfigFields { + + @Getter + private String name; + @Getter + private DungeonLocationType dungeonLocationType = DungeonLocationType.WORLD; + @Getter + private List customInfo = new ArrayList<>(); + @Getter + private List relativeBossLocations = new ArrayList<>(); + @Getter + private List relativeTreasureChestLocations = new ArrayList<>(); + @Getter + private String downloadLink = ""; + @Getter + private DungeonSizeCategory dungeonSizeCategory = DungeonSizeCategory.LAIR; + @Getter + private String worldName; + @Getter + @Setter + private String wormholeWorldName; + @Getter + private String schematicName = ""; + @Getter + private World.Environment environment = World.Environment.NORMAL; + @Getter + private boolean protect = true; + @Getter + private Location anchorPoint; + @Getter + private double rotation; + @Getter + private Vector corner1 = new Vector(0, 0, 0), corner2 = new Vector(0, 0, 0); + @Getter + private Vector teleportPoint = new Vector(0, 0, 0); + @Getter + private Vector wormholeTeleportPoint = new Vector(0, 0, 0); + @Getter + private double teleportPointPitch = 0d; + @Getter + private double wormholeTeleportPointPitch = 0d; + @Getter + private double teleportPointYaw = 0d; + @Getter + private double wormholeTeleportPointYaw = 0d; + @Getter + private int dungeonVersion = 0; + @Getter + private String playerInfo = ""; + @Getter + private String regionEnterMessage = ""; + @Getter + private String regionLeaveMessage = ""; + @Getter + @Setter + private List worldGuardFlags = new ArrayList<>(); + @Getter + @Setter + private boolean hasCustomModels = false; + @Getter + private boolean defaultDungeon = false; + + + public DungeonPackagerConfigFields(String fileName, boolean isEnabled) { + super(fileName, isEnabled); + } + + public DungeonPackagerConfigFields(String fileName, + boolean isEnabled, + String name, + DungeonLocationType dungeonLocationType, + List customInfo, + List relativeBossLocations, + List relativeTreasureChestLocations, + String downloadLink, + DungeonSizeCategory dungeonSizeCategory, + String worldName, + String schematicName, + World.Environment environment, + Boolean protect, + Vector corner1, + Vector corner2, + Vector teleportPoint, + double teleportPointPitch, + double teleportPointYaw, + int dungeonVersion, + String playerInfo, + String regionEnterMessage, + String regionLeaveMessage) { + super(fileName, isEnabled); + this.name = name; + this.dungeonLocationType = dungeonLocationType; + this.customInfo = customInfo; + this.relativeBossLocations = new ArrayList<>(relativeBossLocations); + this.relativeTreasureChestLocations = new ArrayList<>(relativeTreasureChestLocations); + this.downloadLink = downloadLink; + this.dungeonSizeCategory = dungeonSizeCategory; + this.worldName = worldName; + this.schematicName = schematicName; + this.environment = environment; + this.protect = protect; + this.corner1 = corner1; + this.corner2 = corner2; + this.teleportPoint = teleportPoint; + this.teleportPointPitch = teleportPointPitch; + this.teleportPointYaw = teleportPointYaw; + this.dungeonVersion = dungeonVersion; + this.playerInfo = playerInfo; + this.regionEnterMessage = regionEnterMessage; + this.regionLeaveMessage = regionLeaveMessage; + defaultDungeon = true; + } + + @Override + public void processConfigFields() { + this.isEnabled = processBoolean("isEnabled", isEnabled, false, true); + this.name = processString("name", name, "name", true); + this.dungeonLocationType = processEnum("dungeonLocationType", dungeonLocationType, null, DungeonLocationType.class, true); + if (dungeonLocationType == null) { + new WarningMessage("File " + filename + " does not have a valid dungeonLocationType!"); + this.fileConfiguration = null; + return; + } + this.customInfo = processStringList("customInfo", customInfo, customInfo, true); + this.relativeBossLocations = processStringList("relativeBossLocations", relativeBossLocations, new ArrayList<>(), false); + this.relativeTreasureChestLocations = processStringList("relativeTreasureChestLocations", relativeTreasureChestLocations, new ArrayList<>(), false); + this.downloadLink = processString("downloadLink", downloadLink, "", false); + this.dungeonSizeCategory = processEnum("dungeonSizeCategory", dungeonSizeCategory, null, DungeonSizeCategory.class, false); + if (dungeonSizeCategory == null) { + new WarningMessage("File " + filename + " does not have a valid dungeonSizeCategory!"); + this.fileConfiguration = null; + return; + } + this.worldName = processString("worldName", worldName, "", false); + this.wormholeWorldName = processString("wormholeWorldName", wormholeWorldName, "", false); + this.schematicName = processString("schematicName", schematicName, "", false); + this.environment = processEnum("environment", environment, null, World.Environment.class, false); + this.protect = processBoolean("protect", protect, true, true); + this.anchorPoint = processLocation("anchorPoint", anchorPoint, null, false); + this.rotation = processDouble("rotation", rotation, 0, false); + this.corner1 = processVector("corner1", corner1, null, false); + this.corner2 = processVector("corner2", corner2, null, false); + this.teleportPoint = processVector("teleportPoint", teleportPoint, null, false); + this.teleportPointPitch = processDouble("teleportPointPitch", teleportPointPitch, 0d, false); + this.teleportPointYaw = processDouble("teleportPointYaw", teleportPointYaw, 0d, false); + this.dungeonVersion = processInt("dungeonVersion", dungeonVersion, 0, false); + this.playerInfo = processString("playerInfo", playerInfo, "", false); + this.regionEnterMessage = processString("regionEnterMessage", regionEnterMessage, "", false); + this.regionLeaveMessage = processString("regionLeaveMessage", regionLeaveMessage, "", false); + this.hasCustomModels = processBoolean("hasCustomModels", hasCustomModels, false, false); + } + + @Override + public void setEnabled(boolean isEnabled) { + this.isEnabled = isEnabled; + ConfigurationEngine.writeValue(isEnabled, file, fileConfiguration, "isEnabled"); + } + + public void setEnabled(boolean isEnabled, Location anchorPoint) { + setEnabled(isEnabled); + if (isEnabled) + setAnchorPoint(anchorPoint); + else + removeAnchorPoint(); + } + + public boolean addRelativeBossLocation(CustomBossesConfigFields customBossesConfigFields, Location relativeLocation) { + String configurationLocation = customBossesConfigFields.getFilename() + ":" + relativeLocation.getX() + "," + relativeLocation.getY() + "," + relativeLocation.getZ(); + relativeBossLocations.add(configurationLocation); + return ConfigurationEngine.writeValue(relativeBossLocations, file, fileConfiguration, "relativeBossLocations"); + } + + public void removeRelativeBossLocation(CustomBossesConfigFields customBossesConfigFields, Vector relativeLocation) { + String configurationLocation = customBossesConfigFields.getFilename() + ":" + relativeLocation.getX() + "," + relativeLocation.getY() + "," + relativeLocation.getZ(); + relativeBossLocations.remove(configurationLocation); + ConfigurationEngine.writeValue(relativeBossLocations, file, fileConfiguration, "relativeBossLocations"); + } + + public boolean addRelativeTreasureChests(CustomTreasureChestConfigFields treasureChestConfigFields, Location relativeLocation) { + String configurationLocation = treasureChestConfigFields.getFilename() + ":" + relativeLocation.getX() + "," + relativeLocation.getY() + "," + relativeLocation.getZ(); + relativeTreasureChestLocations.add(configurationLocation); + return ConfigurationEngine.writeValue(relativeTreasureChestLocations, file, fileConfiguration, "relativeTreasureChestLocations"); + } + + private void setAnchorPoint(Location location) { + Location roundedLocation = location.clone(); + roundedLocation.setX(roundedLocation.getBlockX() + 0.5); + roundedLocation.setY(roundedLocation.getBlockY() + 0.5); + roundedLocation.setZ(roundedLocation.getBlockZ() + 0.5); + float roundedYaw = roundedLocation.getYaw(); + while (roundedYaw < -225F) { + roundedYaw += 360F; + } + while (roundedYaw > 225F) { + roundedYaw -= 360F; + } + if (roundedYaw <= 45F && roundedYaw >= -45F) + roundedYaw = 0F; + else if (roundedYaw >= 45F && roundedYaw <= 135F) + roundedYaw = 90F; + else if (roundedYaw <= -45F && roundedYaw >= -135F) + roundedYaw = -90F; + else if (roundedYaw >= 135F || roundedYaw <= -135F) + roundedYaw = 180F; + roundedLocation.setYaw(roundedYaw); + this.anchorPoint = roundedLocation; + setRotation(roundedYaw); + ConfigurationEngine.writeValue(ConfigurationLocation.deserialize(roundedLocation), file, fileConfiguration, "anchorPoint"); + new DebugBlockLocation(roundedLocation); + } + + private void removeAnchorPoint() { + ConfigurationEngine.removeValue(file, fileConfiguration, "anchorPoint"); + this.anchorPoint = null; + } + + public void setRotation(float roundedRotation) { + this.rotation = roundedRotation; + ConfigurationEngine.writeValue(rotation, file, fileConfiguration, "rotation"); + } + + public enum DungeonLocationType { + WORLD, + SCHEMATIC + } + + public enum DungeonSizeCategory { + LAIR, + MINIDUNGEON, + DUNGEON, + RAID, + ADVENTURE + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/AirShipMinidungeon.java b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/AirShipMinidungeon.java new file mode 100644 index 000000000..b4a4b47e0 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/AirShipMinidungeon.java @@ -0,0 +1,108 @@ +package com.magmaguy.elitemobs.config.dungeonpackager.premade; + +import com.magmaguy.elitemobs.config.dungeonpackager.DungeonPackagerConfigFields; +import com.magmaguy.elitemobs.utils.DiscordLinks; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.Arrays; + +public class AirShipMinidungeon extends DungeonPackagerConfigFields { + public AirShipMinidungeon() { + super( + "airship_minidungeon", + false, + "&6The Airship", + DungeonLocationType.SCHEMATIC, + Arrays.asList("&fAn awesome airship full of undead pirates!", + "&6Credits: MagmaGuy, 69OzCanOfBepis", + "&6and Realm of Lotheridon"), + Arrays.asList( + "airship_tier_75_boss.yml:0.0,31.5,112.0", + "airship_tier_65_silverfish.yml:-8.0,21.5,102.0", + "airship_tier_65_silverfish.yml:-10.0,21.5,97.0", + "airship_tier_65_silverfish.yml:-13.0,21.5,93.0", + "airship_tier_65_silverfish.yml:-14.0,7.5,98.0", + "airship_tier_65_silverfish.yml:-13.0,9.5,86.0", + "airship_tier_65_silverfish.yml:-12.0,9.5,76.0", + "airship_tier_65_silverfish.yml:-11.0,9.5,62.0", + "airship_tier_65_silverfish.yml:-9.0,9.5,53.0", + "airship_tier_65_silverfish.yml:0.0,2.5,31.0", + "airship_tier_65_silverfish.yml:0.0,2.5,46.0", + "airship_tier_65_silverfish.yml:0.0,1.5,61.0", + "airship_tier_65_silverfish.yml:0.0,1.5,78.0", + "airship_tier_65_silverfish.yml:0.0,1.5,91.0", + "airship_tier_65_silverfish.yml:0.0,2.5,105.0", + "airship_tier_70_miniboss.yml:0.0,6.5,102.0", + "airship_tier_70_miniboss_2.yml:0.0,6.5,38.0", + "airship_tier_65_silverfish.yml:15.0,7.5,96.0", + "airship_tier_65_silverfish.yml:13.0,10.5,83.0", + "airship_tier_65_silverfish.yml:12.0,10.5,74.0", + "airship_tier_65_silverfish.yml:11.0,9.5,62.0", + "airship_tier_65_silverfish.yml:9.0,10.5,52.0", + "airship_tier_65_silverfish.yml:8.0,10.5,40.0", + "airship_tier_65_silverfish.yml:13.0,21.5,93.0", + "airship_tier_65_silverfish.yml:10.0,21.5,97.0", + "airship_tier_65_silverfish.yml:8.0,21.5,104.0", + "airship_tier_45_knockback.yml:7.0,16.5,42.0", + "airship_tier_45_knockback.yml:-8.0,16.5,42.0", + "airship_tier_45_witherblind.yml:-3.0,16.5,42.0", + "airship_tier_45_witherblind.yml:3.0,16.5,42.0", + "airship_tier_45_witherblind.yml:-6.0,14.5,59.0", + "airship_tier_45_knockback.yml:-6.0,14.5,53.0", + "airship_tier_45_knockback.yml:7.0,14.5,59.0", + "airship_tier_45_knockback.yml:2.0,14.5,75.0", + "airship_tier_45_witherblind.yml:-3.0,14.5,74.0", + "airship_tier_50_scourge.yml:2.0,14.5,89.0", + "airship_tier_50_scourge.yml:-2.0,14.5,89.0", + "airship_tier_60_mess_hall_mate.yml:8.0,14.5,89.0", + "airship_tier_60_mess_hall_mate.yml:10.0,14.5,90.0", + "airship_tier_60_mess_hall_mate.yml:8.0,14.5,97.0", + "airship_tier_60_mess_hall_mate.yml:-8.0,14.5,84.0", + "airship_tier_60_mess_hall_mate.yml:-9.0,14.5,87.0", + "airship_tier_60_mess_hall_mate.yml:-9.0,14.5,101.0", + "airship_tier_50_scourge.yml:0.0,14.5,98.0", + "airship_tier_65_bodyguard.yml:3.0,14.5,109.0", + "airship_tier_50_powder_monkeys.yml:10.0,5.5,88.0", + "airship_tier_50_powder_monkeys.yml:4.0,5.5,85.0", + "airship_tier_50_powder_monkeys.yml:6.0,5.5,77.0", + "airship_tier_50_powder_monkeys.yml:3.0,5.5,72.0", + "airship_tier_65_boatswain_boss.yml:3.0,5.5,74.0", + "airship_tier_65_boatswain_boss.yml:3.0,5.5,54.0", + "airship_tier_50_powder_monkeys.yml:0.0,5.5,59.0", + "airship_tier_50_powder_monkeys.yml:-4.0,5.5,53.0", + "airship_tier_50_powder_monkeys.yml:-4.0,5.5,67.0", + "airship_tier_50_powder_monkeys.yml:-6.0,5.5,73.0", + "airship_tier_50_powder_monkeys.yml:-5.0,5.5,85.0", + "airship_tier_50_powder_monkeys.yml:-9.0,5.5,86.0", + "airship_tier_65_boatswain_boss.yml:-7.0,5.5,80.0", + "airship_tier_70_miniboss_wayfinder.yml:-2.0,21.5,115.0", + "airship_tier_65_bodyguard.yml:-3.0,21.5,109.0", + "airship_tier_65_bodyguard.yml:3.0,21.5,109.0", + "airship_tier_45_witherblind.yml:8.0,21.5,82.0", + "airship_tier_45_witherblind.yml:-5.0,21.5,84.0", + "airship_tier_45_knockback.yml:11.0,26.5,96.0", + "airship_tier_45_knockback.yml:-11.0,26.5,96.0", + "airship_tier_45_knockback.yml:1.0,21.5,98.0", + "airship_tier_65_bodyguard.yml:-3.0,14.5,109.0"), + new ArrayList<>(), + DiscordLinks.premiumMinidungeons, + DungeonSizeCategory.MINIDUNGEON, + null, + "em_airship.schem", + null, + true, + new Vector(38, -2, 0), + new Vector(-40, 70, 146), + new Vector(12, 14, 56), + 0D, + 0D, + 0, + "Difficulty: &6Medium\n" + + "$bossCount bosses, from level $lowestTier to $highestTier\n" + + "&6An awesome airship full of undead pirates\n" + + "&6for experienced players!", + "&8[EM] &cEntering hostile air zone!", + "&8[EM] &cLeaving hostile air zone!"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/BinderOfWorldsLair.java b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/BinderOfWorldsLair.java new file mode 100644 index 000000000..2b695fdfb --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/BinderOfWorldsLair.java @@ -0,0 +1,39 @@ +package com.magmaguy.elitemobs.config.dungeonpackager.premade; + +import com.magmaguy.elitemobs.config.dungeonpackager.DungeonPackagerConfigFields; +import com.magmaguy.elitemobs.utils.DiscordLinks; +import org.bukkit.World; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.Arrays; + +public class BinderOfWorldsLair extends DungeonPackagerConfigFields { + public BinderOfWorldsLair() { + super("binder_of_worlds_lair", + false, + "&5Binder Of Worlds", + DungeonLocationType.WORLD, + Arrays.asList("&5The ultimate challenge. Be prepared!", + "&6Credits: MagmaGuy & 69OzCanOfBepis"), + new ArrayList<>(), + new ArrayList<>(), + DiscordLinks.premiumMinidungeons, + DungeonSizeCategory.LAIR, + "em_binder_of_worlds", + null, + World.Environment.THE_END, + true, + null, + null, + new Vector(0, 0, 0), + 0D, + 0D, + 0, + "Difficulty: &6Nightmare\n" + + "$bossCount level $highestTier final boss!\n" + + "&5This is the hardest fight in EliteMobs!", + "&8[EM] &5Reality unravels around you. You face the final challenge. &4You are not prepared!", + "&8[EM] &5You have left the unravelling. Did you find what you sought? Was it worth it?"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/CatacombsLair.java b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/CatacombsLair.java new file mode 100644 index 000000000..ce54344cb --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/CatacombsLair.java @@ -0,0 +1,42 @@ +package com.magmaguy.elitemobs.config.dungeonpackager.premade; + +import com.magmaguy.elitemobs.config.dungeonpackager.DungeonPackagerConfigFields; +import com.magmaguy.elitemobs.utils.DiscordLinks; +import org.bukkit.util.Vector; + +import java.util.Arrays; +import java.util.Collections; + +public class CatacombsLair extends DungeonPackagerConfigFields { + public CatacombsLair() { + super("catacombs_lair", + false, + "&8The Catacombs", + DungeonLocationType.SCHEMATIC, + Arrays.asList("&fThe best starter dungeon for players!", + "&6Credits: Realm of Lotheridon"), + Arrays.asList( + "catacombs_tier_5_evoker_guard_2.yml:2.5,0.5,13.5", + "catacombs_tier_5_illusioner_guard_1.yml:-2.5,2.5,16.5", + "catacombs_tier_15_boss.yml:0.5,-7.5,45.5", + "catacombs_tier_10_miniboss.yml:-8.5,-15.5,36.5"), + Collections.singletonList("catacombs_tier_15_treasure_chest.yml:-1,-14,15"), + DiscordLinks.premiumMinidungeons, + DungeonSizeCategory.LAIR, + null, + "em_catacombs.schem", + null, + true, + new Vector(13, -16, 0), + new Vector(-18, 17, 52), + new Vector(0, 0, 0), + 0, + 0, + 0, + "Difficulty: &cHard\n" + + "$bossCount bosses, from tier $lowestTier to $highestTier\n" + + "&2The best Lair challenge for groups of beginners!", + "&8[EM] &8Now entering the Catacombs. Be careful with what dwells below...", + "&8[EM] &8You have left the Catacombs. Was it worth it?"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/ColosseumLair.java b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/ColosseumLair.java new file mode 100644 index 000000000..6f5198d8c --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/ColosseumLair.java @@ -0,0 +1,49 @@ +package com.magmaguy.elitemobs.config.dungeonpackager.premade; + +import com.magmaguy.elitemobs.config.dungeonpackager.DungeonPackagerConfigFields; +import com.magmaguy.elitemobs.utils.DiscordLinks; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.Arrays; + +public class ColosseumLair extends DungeonPackagerConfigFields { + public ColosseumLair() { + super("colosseum_lair", + false, + "&6The Colosseum", + DungeonLocationType.SCHEMATIC, + Arrays.asList("&fFeaturing the first true World boss, first", + "&fmulti-phased battle, first mounted boss,", + "&ffirst disguised boss... a truly epic fight!", + "&6Credits: MagmaGuy & Maldini"), + Arrays.asList("colosseum_tier_70_boss_p1.yml:-0.5,-1.5,47.5", + "colosseum_tier_70_gladiator.yml:5.5,-7.5,22.5", + "colosseum_tier_70_gladiator.yml:1.5,-7.5,22.5", + "colosseum_tier_70_gladiator.yml:0.5,-7.5,30.5", + "colosseum_tier_70_gladiator.yml:-5.5,-7.5,41.5", + "colosseum_tier_70_gladiator.yml:1.5,-7.5,41.5", + "colosseum_tier_70_gladiator.yml:-11.5,-7.5,41.5", + "colosseum_tier_70_gladiator.yml:-14.5,-7.5,23.5", + "colosseum_tier_70_gladiator.yml:-30.5,-7.5,31.5", + "colosseum_tier_70_gladiator.yml:-30.5,-7.5,31.5"), + new ArrayList<>(), + DiscordLinks.premiumMinidungeons, + DungeonSizeCategory.LAIR, + null, + "em_colosseum.schem", + null, + true, + new Vector(40, -14, 0), + new Vector(-41, 31, 88), + new Vector(0, 0, 0), + 0, + 0, + 0, + "Difficulty: &cHard\n" + + "$bossCount bosses, from level $lowestTier to $highestTier\n" + + "&cA true challenge for big groups of players!", + "&8[EM] &6Champions and challengers prepare! &eProve your worth against the most mighty of foes!", + "&8[EM] &6Farewell traveller! &eReturn soon to show your might once more!"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/DarkCathedralLair.java b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/DarkCathedralLair.java new file mode 100644 index 000000000..70b6b04f6 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/DarkCathedralLair.java @@ -0,0 +1,39 @@ +package com.magmaguy.elitemobs.config.dungeonpackager.premade; + +import com.magmaguy.elitemobs.config.dungeonpackager.DungeonPackagerConfigFields; +import com.magmaguy.elitemobs.utils.DiscordLinks; +import org.bukkit.util.Vector; + +import java.util.Arrays; + +public class DarkCathedralLair extends DungeonPackagerConfigFields { + public DarkCathedralLair() { + super("dark_cathedral_lair", + false, + "&8The Dark Cathedral", + DungeonLocationType.SCHEMATIC, + Arrays.asList("&fThe first ever EliteMobs Lair!", + "&fA classic that all servers need!", + "&6Credits: MagmaGuy & 69OzCanOfBepis"), + Arrays.asList("dark_cathedral_tier_75_boss.yml:0.5,0.5,24.5"), + Arrays.asList(""), + DiscordLinks.freeMinidungeons, + DungeonSizeCategory.LAIR, + null, + "em_dark_cathedral.schem", + null, + true, + new Vector(17, -27, 0), + new Vector(-19, 54, 32), + new Vector(0, 0, 0), + 0, + 0, + 0, + "Difficulty: &cHard\n" + + "$bossCount level $highestTier Big Boss!\n" + + "&cThe original minidungeon, a challenge for\n" + + "&ca group of players or for veterans!", + "&8[EM] &8Welcome to the Dark Cathedral. &4Death awaits inside...", + "&8[EM] &8Now leaving the Dark Cathedral. &4It awaits your return..."); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/DarkSpireMinidungeon.java b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/DarkSpireMinidungeon.java new file mode 100644 index 000000000..8d331a019 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/DarkSpireMinidungeon.java @@ -0,0 +1,39 @@ +package com.magmaguy.elitemobs.config.dungeonpackager.premade; + +import com.magmaguy.elitemobs.config.dungeonpackager.DungeonPackagerConfigFields; +import com.magmaguy.elitemobs.utils.DiscordLinks; +import org.bukkit.World; +import org.bukkit.util.Vector; + +import java.util.Arrays; + +public class DarkSpireMinidungeon extends DungeonPackagerConfigFields { + public DarkSpireMinidungeon() { + super("dark_spire_minidungeon", + false, + "&8The Dark Spire", + DungeonLocationType.WORLD, + Arrays.asList("&fThe first ever high level content!", + "&fMade for those who want a real challenge!", + "&6Credits: 69OzCanOfBepis"), + Arrays.asList(""), + Arrays.asList(""), + DiscordLinks.premiumMinidungeons, + DungeonSizeCategory.MINIDUNGEON, + "em_dark_spire", + null, + World.Environment.NETHER, + true, + null, + null, + new Vector(0, 0, 0), + 150D, + 0D, + 0, + "Difficulty: &6Medium\n" + + "$bossCount bosses, from level $lowestTier to $highestTier\n" + + "&cA vast challenge for advanced players!", + "&8[EM] &1An invasion is in progress. &9Stop the insurrection!", + "&8[EM] &1You managed to hold them back. &9For now..."); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/FireworksLair.java b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/FireworksLair.java new file mode 100644 index 000000000..3a82f0858 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/FireworksLair.java @@ -0,0 +1,38 @@ +package com.magmaguy.elitemobs.config.dungeonpackager.premade; + +import com.magmaguy.elitemobs.config.dungeonpackager.DungeonPackagerConfigFields; +import com.magmaguy.elitemobs.utils.DiscordLinks; +import org.bukkit.World; +import org.bukkit.util.Vector; + +import java.util.Arrays; + +public class FireworksLair extends DungeonPackagerConfigFields { + public FireworksLair() { + super("fireworks_lair", + false, + "&aFireworks", + DungeonLocationType.WORLD, + Arrays.asList("&fThe 2021 4th of July map!", + "&6Credits: MagmaGuy"), + Arrays.asList(""), + Arrays.asList(""), + DiscordLinks.freeMinidungeons, + DungeonSizeCategory.LAIR, + "em_fireworks", + null, + World.Environment.NORMAL, + true, + null, + null, + new Vector(0, 0, 0), + -130D, + 0D, + 0, + "Difficulty: &cHard\n" + + "$bossCount level $lowestTier Big Boss!\n" + + "&6An encounter full of explosions!", + "&8[EM] &eWelcome to the fireworks show!", + "&8[EM] &eYou've left the party!"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/HallosseumLair.java b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/HallosseumLair.java new file mode 100644 index 000000000..b388aec4d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/HallosseumLair.java @@ -0,0 +1,38 @@ +package com.magmaguy.elitemobs.config.dungeonpackager.premade; + +import com.magmaguy.elitemobs.config.dungeonpackager.DungeonPackagerConfigFields; +import com.magmaguy.elitemobs.utils.DiscordLinks; +import org.bukkit.World; +import org.bukkit.util.Vector; + +import java.util.Arrays; + +public class HallosseumLair extends DungeonPackagerConfigFields { + public HallosseumLair() { + super("hallosseum_lair", + false, + "&cHallosseum", + DungeonLocationType.WORLD, + Arrays.asList("&fThe 2020 spooky halloween encounter!", + "&6Credits: MagmaGuy & 69OzCanOfBepis"), + Arrays.asList(""), + Arrays.asList(""), + DiscordLinks.freeMinidungeons, + DungeonSizeCategory.LAIR, + "em_hallosseum", + null, + World.Environment.NETHER, + true, + null, + null, + new Vector(0, 0, 0), + -130D, + 0D, + 0, + "Difficulty: &chard\n" + + "$bossCount level $lowestTier Big Boss!\n" + + "&6A fun Halloween challenge!", + "&8[EM] &4Trick or treat! &8Your soul is mine!", + "&8[EM] &4You've escaped with your soul intact."); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/InvasionMinidungeon.java b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/InvasionMinidungeon.java new file mode 100644 index 000000000..c2e4368d8 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/InvasionMinidungeon.java @@ -0,0 +1,39 @@ +package com.magmaguy.elitemobs.config.dungeonpackager.premade; + +import com.magmaguy.elitemobs.config.dungeonpackager.DungeonPackagerConfigFields; +import com.magmaguy.elitemobs.utils.DiscordLinks; +import org.bukkit.World; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.Arrays; + +public class InvasionMinidungeon extends DungeonPackagerConfigFields { + public InvasionMinidungeon() { + super("invasion_minidungeon", + false, + "&2The Invasion", + DungeonLocationType.WORLD, + Arrays.asList("&fThe Halloween Minidungeon!", + "&6Credits: MagmaGuy & 69OzCanOfBepis"), + new ArrayList<>(), + new ArrayList<>(), + DiscordLinks.freeMinidungeons, + DungeonSizeCategory.MINIDUNGEON, + "em_invasion", + null, + World.Environment.NORMAL, + true, + null, + null, + new Vector(0, 0, 0), + 0D, + 0D, + 0, + "Difficulty: &6Medium\n" + + "$bossCount aliens, from level $lowestTier to $highestTier\n" + + "&6Don't get abducted!", + "&8[EM] &7Alien invasion in progress! Defeat the Mothership!", + "&8[EM] &7You have escaped the alien abductions! No one will ever believe you."); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/NorthPoleMinidungeon.java b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/NorthPoleMinidungeon.java new file mode 100644 index 000000000..583962977 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/NorthPoleMinidungeon.java @@ -0,0 +1,39 @@ +package com.magmaguy.elitemobs.config.dungeonpackager.premade; + +import com.magmaguy.elitemobs.config.dungeonpackager.DungeonPackagerConfigFields; +import com.magmaguy.elitemobs.utils.DiscordLinks; +import org.bukkit.World; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.Arrays; + +public class NorthPoleMinidungeon extends DungeonPackagerConfigFields { + public NorthPoleMinidungeon() { + super("north_pole_minidungeon", + false, + "&9The North Pole", + DungeonLocationType.WORLD, + Arrays.asList("&fThe Christmas minidungeon!", + "&6Credits: MagmaGuy & 69OzCanOfBepis"), + new ArrayList<>(), + new ArrayList<>(), + DiscordLinks.freeMinidungeons, + DungeonSizeCategory.MINIDUNGEON, + "em_north_pole", + null, + World.Environment.NORMAL, + true, + null, + null, + new Vector(0, 0, 0), + 0D, + 0D, + 0, + "Difficulty: &6Medium\n" + + "$bossCount bosses, from level $lowestTier to $highestTier\n" + + "&6Christmas in a snow globe!", + "&8[EM] &7You have reached the North Pole! &fHave you been naughty this year?", + "&8[EM] &7Come back and visit. &fThere are plenty of sweets and treats for next time!"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/OasisAdventure.java b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/OasisAdventure.java new file mode 100644 index 000000000..c7a9fe00d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/OasisAdventure.java @@ -0,0 +1,39 @@ +package com.magmaguy.elitemobs.config.dungeonpackager.premade; + +import com.magmaguy.elitemobs.config.dungeonpackager.DungeonPackagerConfigFields; +import com.magmaguy.elitemobs.utils.DiscordLinks; +import org.bukkit.World; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.Arrays; + +public class OasisAdventure extends DungeonPackagerConfigFields { + public OasisAdventure() { + super("oasis_adventure", + false, + "&6The Oasis", + DungeonLocationType.WORLD, + Arrays.asList("&fA massive adventure for beginners!", + "&6Credits: 69OzCanOfBepis"), + new ArrayList<>(), + new ArrayList<>(), + DiscordLinks.premiumMinidungeons, + DungeonSizeCategory.ADVENTURE, + "em_oasis", + null, + World.Environment.NORMAL, + true, + new Vector(0, 0, 0), + new Vector(0, 0, 0), + new Vector(0, 0, 0), + 0D, + 0D, + 2, + "Difficulty: &2Solo-able\n" + + "$bossCount bosses, from level $lowestTier to $highestTier\n" + + "&6A big adventure for people who know the ropes!", + "&8[EM] &6You have arrived at the Oasis!", + "&8[EM] &6You have left the Oasis!"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/PirateShipMinidungeon.java b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/PirateShipMinidungeon.java new file mode 100644 index 000000000..cc04f9e60 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/PirateShipMinidungeon.java @@ -0,0 +1,68 @@ +package com.magmaguy.elitemobs.config.dungeonpackager.premade; + +import com.magmaguy.elitemobs.config.dungeonpackager.DungeonPackagerConfigFields; +import com.magmaguy.elitemobs.utils.DiscordLinks; +import org.bukkit.util.Vector; + +import java.util.Arrays; + +public class PirateShipMinidungeon extends DungeonPackagerConfigFields { + public PirateShipMinidungeon() { + super("pirate_ship_minidungeon", + false, + "&6The Pirate Ship", + DungeonLocationType.SCHEMATIC, + Arrays.asList("&fA fun, challenging minidungeon full of", + "&fbosses made for players starting to get good,", + "&fat EliteMobs!", + "&6Credits: MagmaGuy & Realm of Lotheridon"), + Arrays.asList( + "pirate_ship_tier_10.yml:-2.5,3.5,46.5", + "pirate_ship_tier_10.yml:2.5,3.5,46.5", + "pirate_ship_tier_15.yml:0.5,8.5,22.5", + "pirate_ship_tier_15.yml:-0.5,8.5,22.5", + "pirate_ship_tier_15.yml:0.5,8.5,22.5", + "pirate_ship_tier_20_melee_1.yml:0.5,3.5,67.5", + "pirate_ship_tier_20_melee_1.yml:-0.5,3.5,67.5", + "pirate_ship_tier_20_melee_2.yml:9.5,5.5,76.5", + "pirate_ship_tier_20_melee_2.yml:9.5,5.5,77.5", + "pirate_ship_tier_20_melee_2.yml:8.5,3.5,77.5", + "pirate_ship_tier_20_miniboss.yml:-9.5,3.5,76.5", + "pirate_ship_tier_20_ranged.yml:-1.5,8.5,67.5", + "pirate_ship_tier_20_ranged.yml:-1.5,8.5,67.5", + "pirate_ship_tier_25_miniboss_1.yml:-0.5,3.5,25.5", + "pirate_ship_tier_30_melee.yml:-0.5,-2.5,40.5", + "pirate_ship_tier_30_melee.yml:0.5,-2.5,43.5", + "pirate_ship_tier_30_melee.yml:0.5,-2.5,46.5", + "pirate_ship_tier_30_ranged.yml:-0.5,-2.5,45.5", + "pirate_ship_tier_30_ranged.yml:0.5,-2.5,47.5", + "pirate_ship_tier_30_ranged.yml:0.5,-2.5,50.5", + "pirate_ship_tier_30_miniboss_1.yml:-0.5,-2.5,31.5", + "pirate_ship_tier_35.yml:-0.5,13.5,84.5", + "pirate_ship_tier_35.yml:0.5,13.5,84.5", + "pirate_ship_tier_35.yml:-0.5,13.5,84.5", + "pirate_ship_tier_35_miniboss_1.yml:-1.5,8.5,84.5", + "pirate_ship_tier_35_miniboss_2.yml:-1.5,8.5,84.5", + "pirate_ship_tier_40_miniboss_1.yml:11.5,10.5,78.5", + "pirate_ship_tier_45_boss.yml:-13.5,10.5,79.5"), + Arrays.asList(), + DiscordLinks.premiumMinidungeons, + DungeonSizeCategory.MINIDUNGEON, + null, + "em_pirate_ship.schem", + null, + true, + new Vector(16, -6, -1), + new Vector(-20, 58, 90), + new Vector(-17, 1, 49), + 0, + 0, + 0, + "Difficulty: &6Medium\n" + + "$bossCount bosses, from level $lowestTier to $highestTier\n" + + "&6One of the best hunting grounds for" + + "&6aspiring adventurers!", + "&8[EM] &3Now boarding the Pirate Ship! &bPillage and plunder to yer' hearts content!", + "&8[EM] &3Player overboard! &bReturn when you've earned your sea-legs ye' landlubber!"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/PrimisAdventure.java b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/PrimisAdventure.java new file mode 100644 index 000000000..8c1263b9d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/PrimisAdventure.java @@ -0,0 +1,41 @@ +package com.magmaguy.elitemobs.config.dungeonpackager.premade; + +import com.magmaguy.elitemobs.config.dungeonpackager.DungeonPackagerConfigFields; +import com.magmaguy.elitemobs.utils.DiscordLinks; +import org.bukkit.World; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.Arrays; + +public class PrimisAdventure extends DungeonPackagerConfigFields { + public PrimisAdventure() { + super("primis_adventure", + false, + "&7Primis", + DungeonPackagerConfigFields.DungeonLocationType.WORLD, + Arrays.asList("&fA tutorial adventure for new players!", + "&6Credits: 69OzCanOfBepis, MagmaGuy"), + new ArrayList<>(), + new ArrayList<>(), + DiscordLinks.premiumMinidungeons, + DungeonPackagerConfigFields.DungeonSizeCategory.ADVENTURE, + "em_primis", + null, + World.Environment.NORMAL, + true, + new Vector(0, 0, 0), + new Vector(0, 0, 0), + new Vector(0, 0, 0), + 66D, + 0D, + 0, + "Difficulty: &2Easy\n" + + "$bossCount bosses, from level $lowestTier to $highestTier\n" + + "&6A tutorial adventure for new players!", + "&8[EM] &6Primis awaits, strike the earth!", + "&8[EM] &6You have left Primis!"); + setWormholeWorldName("em_primis_wormhole"); + setHasCustomModels(true); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/RuinsLair.java b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/RuinsLair.java new file mode 100644 index 000000000..1263be9af --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/RuinsLair.java @@ -0,0 +1,39 @@ +package com.magmaguy.elitemobs.config.dungeonpackager.premade; + +import com.magmaguy.elitemobs.config.dungeonpackager.DungeonPackagerConfigFields; +import com.magmaguy.elitemobs.utils.DiscordLinks; +import org.bukkit.util.Vector; + +import java.util.Arrays; + +public class RuinsLair extends DungeonPackagerConfigFields { + public RuinsLair() { + super("the_ruins", + false, + "&6The Ruins", + DungeonLocationType.SCHEMATIC, + Arrays.asList("&fA fight against a myth from", + "&fNorse mythology, be prepared for a smiting!", + "&6Credits: 69OzCanOfBepis, MagmaGuy"), + Arrays.asList( + "ruins_boss_p1.yml:0,0,0"), + Arrays.asList(), + DiscordLinks.premiumMinidungeons, + DungeonSizeCategory.LAIR, + null, + "em_the_ruins.schem", + null, + true, + new Vector(18, -6, -19), + new Vector(-21, 10, 20), + new Vector(-1, -4, 18), + 0, + 0, + 0, + "Difficulty: &cHard\n" + + "$bossCount level $lowestTier Big Boss!\n" + + "&cA tough fight against a Norse god!", + "&8[EM] &3Those who challenge the myths must be prepared for their downfall!", + "&8[EM] &3You now know what it takes to make a legend!"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/SewersMinidungeon.java b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/SewersMinidungeon.java new file mode 100644 index 000000000..401999479 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/SewersMinidungeon.java @@ -0,0 +1,39 @@ +package com.magmaguy.elitemobs.config.dungeonpackager.premade; + +import com.magmaguy.elitemobs.config.dungeonpackager.DungeonPackagerConfigFields; +import com.magmaguy.elitemobs.utils.DiscordLinks; +import org.bukkit.World; +import org.bukkit.util.Vector; + +import java.util.Arrays; + +public class SewersMinidungeon extends DungeonPackagerConfigFields { + public SewersMinidungeon() { + super("sewers_minidungeon", + false, + "&8The Sewers", + DungeonLocationType.WORLD, + Arrays.asList("&fThe biggest minidungeon ever made!", + "&6Credits: MagmaGuy & 69OzCanOfBepis"), + Arrays.asList(""), + Arrays.asList(""), + DiscordLinks.freeMinidungeons, + DungeonSizeCategory.MINIDUNGEON, + "em_sewer_maze", + null, + World.Environment.NORMAL, + true, + null, + null, + new Vector(0, 0, 0), + 90D, + 0D, + 0, + "Difficulty: &6Medium\n" + + "$bossCount bosses, from level $lowestTier to $highestTier\n" + + "&6A complex dungeon maze with a challenging sections!", + "&8[EM] &5This place looks abandoned... &dYet something lurks in these sewers!", + + "&8[EM] &5You managed to stay above water. &dMaybe next time you'll drown."); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/VampireManorMinidungeon.java b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/VampireManorMinidungeon.java new file mode 100644 index 000000000..3b1082739 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/dungeonpackager/premade/VampireManorMinidungeon.java @@ -0,0 +1,168 @@ +package com.magmaguy.elitemobs.config.dungeonpackager.premade; + +import com.magmaguy.elitemobs.config.dungeonpackager.DungeonPackagerConfigFields; +import com.magmaguy.elitemobs.utils.DiscordLinks; +import org.bukkit.util.Vector; + +import java.util.Arrays; + +public class VampireManorMinidungeon extends DungeonPackagerConfigFields { + public VampireManorMinidungeon() { + super("vampire_manor", + false, + "&cThe Vampire Manor", + DungeonLocationType.SCHEMATIC, + Arrays.asList("&fPrepare to spill blood!", + "&6Credits: MagmaGuy, 69OzCanOfBepis"), + Arrays.asList( + "vampire_grunt.yml:5.0,0.0,20.0", + "vampire_grunt.yml:-5.0,0.0,20.0", + "vampire_brute.yml:17.0,0.0,29.0", + "vampire_brute.yml:17.0,0.0,19.0", + "vampire_brute.yml:35.0,0.0,61.0", + "vampire_grunt.yml:35.0,0.0,70.0", + "vampire_grunt.yml:30.0,0.0,68.0", + "vampire_brute.yml:16.0,14.0,77.0", + "vampire_brute.yml:0.0,14.0,79.0", + "vampire_brute.yml:-16.0,14.0,77.0", + "vampire_brute.yml:-31.0,12.0,72.0", + "vampire_grunt.yml:-31.0,12.0,83.0", + "vampire_grunt.yml:30.0,12.0,81.0", + "vampire_brute.yml:31.0,12.0,72.0", + "vampire_necromancer.yml:-26.0,0.0,43.0", + "vampire_necromancer.yml:-28.0,0.0,47.0", + "vampire_necromancer.yml:-23.0,12.0,39.0", + "vampire_necromancer.yml:-30.0,12.0,39.0", + "vampire_grunt.yml:-32.0,0.0,22.0", + "vampire_grunt.yml:-27.0,0.0,15.0", + "vampire_grunt.yml:-26.0,0.0,29.0", + "vampire_grunt.yml:-18.0,12.0,21.0", + "vampire_grunt.yml:-35.0,12.0,21.0", + "vampire_grunt.yml:4.0,-11.0,57.0", + "vampire_grunt.yml:12.0,-11.0,66.0", + "vampire_fledgling.yml:5.0,-10.0,54.0", + "vampire_fledgling.yml:14.0,-12.0,70.0", + "vampire_fledgling.yml:6.0,-11.0,65.0", + "vampire_fledgling.yml:6.0,-13.0,87.0", + "vampire_fledgling.yml:-7.0,-12.0,89.0", + "vampire_fledgling.yml:-20.0,-10.0,81.0", + "vampire_necromancer.yml:-46.0,-9.0,24.0", + "vampire_necromancer.yml:-40.0,-9.0,18.0", + "vampire_necromancer.yml:-33.0,-9.0,24.0", + "vampire_grunt.yml:-35.0,-9.0,28.0", + "vampire_grunt.yml:-44.0,-9.0,28.0", + "vampire_grunt.yml:-45.0,-9.0,18.0", + "vampire_grunt.yml:-34.0,-9.0,17.0", + "vampire_grunt.yml:-14.0,0.0,62.0", + "vampire_grunt.yml:0.0,0.0,62.0", + "vampire_grunt.yml:13.0,0.0,62.0", + "vampire_brute.yml:0.0,2.0,78.0", + "vampire_brute.yml:-16.0,2.0,78.0", + "vampire_brute.yml:16.0,2.0,78.0", + "vampire_grunt.yml:35.0,0.0,33.0", + "vampire_grunt.yml:35.0,0.0,22.0", + "vampire_grunt.yml:31.0,0.0,13.0", + "vampire_grunt.yml:30.0,0.0,46.0", + "vampire_grunt.yml:25.0,0.0,36.0", + "vampire_necromancer.yml:30.0,1.0,30.0", + "vampire_grunt.yml:24.0,12.0,54.0", + "vampire_grunt.yml:17.0,12.0,42.0", + "vampire_grunt.yml:17.0,12.0,28.0", + "vampire_grunt.yml:-11.0,6.0,31.0", + "vampire_grunt.yml:10.0,6.0,31.0", + "vampire_grunt.yml:-30.0,0.0,67.0", + "vampire_grunt.yml:-33.0,0.0,76.0", + "vampire_grunt.yml:30.0,-11.0,33.0", + "vampire_grunt.yml:24.0,-11.0,33.0", + "vampire_necromancer.yml:19.0,-13.0,22.0", + "vampire_necromancer.yml:36.0,-13.0,23.0", + "vampire_grunt.yml:31.0,-11.0,13.0", + "vampire_grunt.yml:23.0,-11.0,14.0", + "vampire_necromancer.yml:2.0,-15.0,23.0", + "vampire_necromancer.yml:-26.0,-10.0,54.0", + "vampire_necromancer.yml:-9.0,46.0,48.0", + "vampire_brute.yml:-10.0,46.0,62.0", + "vampire_brute.yml:-9.0,46.0,33.0", + "vampire_brute.yml:13.0,61.0,48.0", + "vampire_brute.yml:0.0,61.0,60.0", + "vampire_necromancer_dining_hall.yml:17.0,12.0,17.0", + "vampire_necromancer_left_bedroom.yml:32.0,13.0,65.0", + "vampire_necromancer_right_bedroom.yml:-32.0,13.0,65.0", + "vampire_necromancer_supply_room.yml:-27.0,0.0,82.0", + "vampire_necromancer_gargoyle_rush.yml:-40.0,-9.0,57.0", + "vampire_brute_gargoyle_rush_right.yml:-38.0,-9.0,57.0", + "vampire_brute_gargoyle_rush_left.yml:-42.0,-9.0,57.0", + "vampire_grunt_gargoyle_rush_right.yml:-36.0,-9.0,57.0", + "vampire_grunt_gargoyle_rush_left.yml:-44.0,-9.0,57.0", + "vampire_king.yml:-13.0,30.0,48.0", + "vampire_wraith.yml:-47.0,-20.0,52.0", + "vampire_brute.yml:-18.0,12.0,16.0", + "vampire_necromancer_supreme_coffin_breaker.yml:2.0,-15.0,23.0", + "vampire_necromancer_supreme_gargoyle_overlord.yml:58.0,-15.0,23.0", + "vampire_fledgling_gargoyle_overlord.yml:58.0,-15.0,16.0", + "vampire_fledgling_gargoyle_overlord.yml:52.0,-15.0,16.0", + "vampire_fledgling_gargoyle_overlord.yml:48.0,-15.0,20.0", + "vampire_fledgling_gargoyle_overlord.yml:48.0,-15.0,26.0", + "vampire_fledgling_gargoyle_overlord.yml:52.0,-15.0,30.0", + "vampire_fledgling_gargoyle_overlord.yml:58.0,-15.0,30.0", + "vampire_fledgling_gargoyle_overlord.yml:48.0,-15.0,20.0", + "vampire_zombie.yml:-7.0,-25.0,65.0", + "vampire_zombie.yml:-19.0,-25.0,68.0", + "vampire_zombie.yml:-14.0,-25.0,51.0", + "vampire_zombie.yml:-2.0,-24.0,78.0", + "vampire_zombie.yml:-4.0,-26.0,43.0", + "vampire_zombie.yml:7.0,-24.0,78.0", + "vampire_zombie.yml:-30.0,-18.0,44.0", + "vampire_zombie.yml:-31.0,-18.0,34.0", + "vampire_zombie.yml:-26.0,-18.0,57.0", + "vampire_necromancer_entrance.yml:0.0,8.0,32.0", + "vampire_necromancer_foresight_pool.yml:-19.0,0.0,22.0", + "vampire_necromancer_roof.yml:-12.0,61.0,48.0", + "vampire_brute.yml:0.0,61.0,35.0", + "vampire_brute.yml:17.0,26.0,9.0", + "vampire_brute.yml:-17.0,26.0,9.0", + "vampire_brute.yml:-39.0,26.0,31.0", + "vampire_brute.yml:-39.0,26.0,65.0", + "vampire_brute.yml:-17.0,26.0,87.0", + "vampire_brute.yml:17.0,26.0,87.0", + "vampire_brute.yml:39.0,26.0,65.0", + "vampire_brute.yml:39.0,26.0,31.0", + "vampire_necromancer_roof_north.yml:0.0,26.0,8.0", + "vampire_necromancer_roof_east.yml:40.0,26.0,48.0", + "vampire_necromancer_roof_south.yml:0.0,26.0,88.0", + "vampire_necromancer_roof_west.yml:-40.0,26.0,48.0"), + Arrays.asList( + "vampire_manor_south.yml:16.5,11.5,13.5", + "vampire_manor_west.yml:-17.5,11.5,20.5", + "vampire_manor_east.yml:-28.5,-0.5,44.5", + "vampire_manor_north.yml:26.5,11.5,83.5", + "vampire_manor_north.yml:-27.5,11.5,83.5", + "vampire_manor_north.yml:-0.5,25.5,93.5", + "vampire_manor_north.yml:-0.5,60.5,37.5", + "vampire_manor_south.yml:-0.5,25.5,1.5", + "vampire_manor_south.yml:-0.5,60.5,57.5", + "vampire_manor_east.yml:-46.5,25.5,47.5", + "vampire_manor_west.yml:-10.5,60.5,47.5", + "vampire_manor_west.yml:45.5,25.5,47.5", + "vampire_manor_east.yml:-54.5,-19.5,54.5", + "vampire_manor_south.yml:-3.5,-25.5,37.5"), + DiscordLinks.premiumMinidungeons, + DungeonSizeCategory.MINIDUNGEON, + null, + "em_vampire_manor.schem", + null, + true, + new Vector(67, -28, 0), + new Vector(-57, 112, 97), + new Vector(0, 0, 0), + 0D, + 0D, + 0, + "Difficulty: &6Medium\n" + + "$bossCount bosses, from level $lowestTier to $highestTier\n" + + "&6A deadly manor full of blood thristy creatures!\n" + + "&6Are you ready to face that which haunts the night?", + "&8[EM] &cTrespassing on dangerous grounds!!", + "&8[EM] &cNow leaving haunted land!"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/EnchantmentsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/EnchantmentsConfig.java new file mode 100644 index 000000000..27450f9f9 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/EnchantmentsConfig.java @@ -0,0 +1,26 @@ +package com.magmaguy.elitemobs.config.enchantments; + +import com.magmaguy.elitemobs.config.CustomConfig; +import org.bukkit.enchantments.Enchantment; + +import java.util.HashMap; + +public class EnchantmentsConfig extends CustomConfig { + + private static HashMap enchantments = new HashMap(); + + public EnchantmentsConfig() { + super("enchantments", "com.magmaguy.elitemobs.config.enchantments.premade", EnchantmentsConfigFields.class); + enchantments = new HashMap<>(); + for (String key : super.getCustomConfigFieldsHashMap().keySet()) + enchantments.put(key, (EnchantmentsConfigFields) super.getCustomConfigFieldsHashMap().get(key)); + } + + public static EnchantmentsConfigFields getEnchantment(String string) { + return enchantments.get(string); + } + + public static EnchantmentsConfigFields getEnchantment(Enchantment enchantment) { + return getEnchantment(enchantment.getName().toLowerCase() + ".yml"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/EnchantmentsConfigFields.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/EnchantmentsConfigFields.java new file mode 100644 index 000000000..a1afe2460 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/EnchantmentsConfigFields.java @@ -0,0 +1,47 @@ +package com.magmaguy.elitemobs.config.enchantments; + +import com.magmaguy.elitemobs.config.CustomConfigFields; +import lombok.Getter; +import org.bukkit.enchantments.Enchantment; + +public class EnchantmentsConfigFields extends CustomConfigFields { + @Getter + private String name = "name"; + @Getter + private int maxLevel = 5; + @Getter + private double value = 1; + @Getter + private Enchantment enchantment = Enchantment.DAMAGE_ALL; + + public EnchantmentsConfigFields(String filename, + boolean isEnabled, + String name, + int maxLevel, + double value) { + super(filename, isEnabled); + this.isEnabled = isEnabled; + this.name = name; + this.maxLevel = maxLevel; + this.value = value; + } + + @Override + public void processConfigFields() { + this.isEnabled = processBoolean("isEnabled", isEnabled, true, true); + this.name = processString("name", name, "name", true); + this.maxLevel = processInt("maxLevel", maxLevel, 1, true); + String cleanName = this.filename.replace(".yml", "").toUpperCase(); + try { + this.enchantment = Enchantment.getByName(cleanName); + } catch (Exception ex) { + this.enchantment = null; + } + this.value = processDouble("value", value, 1, true); + processAdditionalFields(); + } + + public void processAdditionalFields() { + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ArrowDamageConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ArrowDamageConfig.java new file mode 100644 index 000000000..e5a617b95 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ArrowDamageConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class ArrowDamageConfig extends EnchantmentsConfigFields { + public ArrowDamageConfig() { + super("arrow_damage", + true, + "Power", + 200, + 13); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ArrowFireConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ArrowFireConfig.java new file mode 100644 index 000000000..4a43c73fa --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ArrowFireConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class ArrowFireConfig extends EnchantmentsConfigFields { + public ArrowFireConfig() { + super("arrow_fire", + true, + "Flame", + 1, + 6); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ArrowInfiniteConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ArrowInfiniteConfig.java new file mode 100644 index 000000000..fa6744076 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ArrowInfiniteConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class ArrowInfiniteConfig extends EnchantmentsConfigFields { + public ArrowInfiniteConfig() { + super("arrow_infinite", + true, + "Infinity", + 1, + 6); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ArrowKnockbackConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ArrowKnockbackConfig.java new file mode 100644 index 000000000..55543ad77 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ArrowKnockbackConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class ArrowKnockbackConfig extends EnchantmentsConfigFields { + public ArrowKnockbackConfig() { + super("arrow_knockback", + true, + "Punch", + 2, + 6); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/BindingCurseConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/BindingCurseConfig.java new file mode 100644 index 000000000..58e1eb6a2 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/BindingCurseConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class BindingCurseConfig extends EnchantmentsConfigFields { + public BindingCurseConfig() { + super("binding_curse", + true, + "Curse of Binding", + 1, + -6); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ChannelingConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ChannelingConfig.java new file mode 100644 index 000000000..121a06131 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ChannelingConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class ChannelingConfig extends EnchantmentsConfigFields { + public ChannelingConfig() { + super("channeling", + true, + "Channeling", + 1, + 6); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/CriticalStrikesConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/CriticalStrikesConfig.java new file mode 100644 index 000000000..c9e760c1c --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/CriticalStrikesConfig.java @@ -0,0 +1,26 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; +import lombok.Getter; + +public class CriticalStrikesConfig extends EnchantmentsConfigFields { + @Getter + private static String criticalHitPopup; + @Getter + private static String criticalHitColor; + + public CriticalStrikesConfig() { + super("critical_strikes", + true, + "Critical Strikes", + 2, + 13); + } + + @Override + public void processAdditionalFields() { + criticalHitPopup = ConfigurationEngine.setString(super.fileConfiguration, "criticalHitPopup", "&5Critical Hit!"); + criticalHitColor = ConfigurationEngine.setString(super.fileConfiguration, "criticalHitColor", "&5"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/DamageAllConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/DamageAllConfig.java new file mode 100644 index 000000000..8f72684d0 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/DamageAllConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class DamageAllConfig extends EnchantmentsConfigFields { + public DamageAllConfig() { + super("damage_all", + true, + "Sharpness", + 200, + 13); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/DamageArthropodsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/DamageArthropodsConfig.java new file mode 100644 index 000000000..6b31ed032 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/DamageArthropodsConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class DamageArthropodsConfig extends EnchantmentsConfigFields { + public DamageArthropodsConfig() { + super("damage_arthropods", + true, + "Bane of Arthropods", + 100, + 6); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/DamageUndeadConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/DamageUndeadConfig.java new file mode 100644 index 000000000..df2ff697b --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/DamageUndeadConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class DamageUndeadConfig extends EnchantmentsConfigFields { + public DamageUndeadConfig() { + super("damage_undead", + true, + "Smite", + 100, + 6); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/DepthStriderConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/DepthStriderConfig.java new file mode 100644 index 000000000..4063168e6 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/DepthStriderConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class DepthStriderConfig extends EnchantmentsConfigFields { + public DepthStriderConfig() { + super("depth_strider", + true, + "Depth Strider", + 3, + 6); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/DigSpeedConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/DigSpeedConfig.java new file mode 100644 index 000000000..75b37a6a1 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/DigSpeedConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class DigSpeedConfig extends EnchantmentsConfigFields { + public DigSpeedConfig() { + super("dig_speed", + true, + "Efficiency", + 5, + 13); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/DrillingConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/DrillingConfig.java new file mode 100644 index 000000000..c2cc6a82f --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/DrillingConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class DrillingConfig extends EnchantmentsConfigFields { + public DrillingConfig() { + super("drilling", + true, + "Drilling", + 4, + 15); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/DurabilityConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/DurabilityConfig.java new file mode 100644 index 000000000..96bac7b07 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/DurabilityConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class DurabilityConfig extends EnchantmentsConfigFields { + public DurabilityConfig() { + super("durability", + true, + "Unbreaking", + 3, + 13); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/EarthquakeConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/EarthquakeConfig.java new file mode 100644 index 000000000..9d523abf6 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/EarthquakeConfig.java @@ -0,0 +1,27 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; +import lombok.Getter; + +public class EarthquakeConfig extends EnchantmentsConfigFields { + @Getter + private static String earthquakeActivationMessage; + @Getter + private static String earthquakeAvailableMessage; + + public EarthquakeConfig() { + super("earthquake", + true, + "Earthquake", + 5, + 50); + } + + @Override + public void processAdditionalFields() { + earthquakeActivationMessage = ConfigurationEngine.setString(fileConfiguration, "earthquakeActivationMessage", "&8[EliteMobs] &aEarthquake triggered! &c2 min cooldown!"); + earthquakeAvailableMessage = ConfigurationEngine.setString(fileConfiguration, "earthquakeAvailableMessage", "&8[EliteMobs] &2Earthquake cooldown over!"); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/FireAspectConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/FireAspectConfig.java new file mode 100644 index 000000000..cb3a2f769 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/FireAspectConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class FireAspectConfig extends EnchantmentsConfigFields { + public FireAspectConfig() { + super("fire_aspect", + true, + "Fire Aspect", + 2, + 6); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/FlamethrowerConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/FlamethrowerConfig.java new file mode 100644 index 000000000..c42164626 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/FlamethrowerConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class FlamethrowerConfig extends EnchantmentsConfigFields { + public FlamethrowerConfig() { + super("flamethrower", + true, + "Flamethrower", + 1, + 20); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/FrostWalkerConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/FrostWalkerConfig.java new file mode 100644 index 000000000..00c517460 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/FrostWalkerConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class FrostWalkerConfig extends EnchantmentsConfigFields { + public FrostWalkerConfig() { + super("frost_walker", + true, + "Frost Walker", + 2, + 6); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/GrapplingHookConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/GrapplingHookConfig.java new file mode 100644 index 000000000..0d3b28d80 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/GrapplingHookConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class GrapplingHookConfig extends EnchantmentsConfigFields { + public GrapplingHookConfig() { + super("grappling_hook", + true, + "Grappling Hook", + 1, + 10); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/HunterConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/HunterConfig.java new file mode 100644 index 000000000..b68e4845c --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/HunterConfig.java @@ -0,0 +1,21 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class HunterConfig extends EnchantmentsConfigFields { + public static double hunterSpawnBonus; + + public HunterConfig() { + super("hunter", + true, + "Hunter", + 3, + 10); + } + + @Override + public void processAdditionalFields() { + hunterSpawnBonus = ConfigurationEngine.setDouble(super.fileConfiguration, "hunterSpawnBonus", 0.05); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/IceBreakerConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/IceBreakerConfig.java new file mode 100644 index 000000000..9a1da3bc8 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/IceBreakerConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class IceBreakerConfig extends EnchantmentsConfigFields { + public IceBreakerConfig() { + super("ice_breaker", + true, + "Ice Breaker", + 2, + 10); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ImpalingConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ImpalingConfig.java new file mode 100644 index 000000000..ef7eb8f97 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ImpalingConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class ImpalingConfig extends EnchantmentsConfigFields { + public ImpalingConfig() { + super("impaling", + true, + "Impaling", + 5, + 6); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/KnockbackConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/KnockbackConfig.java new file mode 100644 index 000000000..22fc8c32e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/KnockbackConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class KnockbackConfig extends EnchantmentsConfigFields { + public KnockbackConfig() { + super("knockback", + true, + "Knockback", + 2, + 6); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/LightningConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/LightningConfig.java new file mode 100644 index 000000000..a03c72ea9 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/LightningConfig.java @@ -0,0 +1,21 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class LightningConfig extends EnchantmentsConfigFields { + public static int minimumCooldown; + + public LightningConfig() { + super("lightning", + true, + "Lightning", + 5, + 15); + } + + @Override + public void processAdditionalFields() { + minimumCooldown = ConfigurationEngine.setInt(super.fileConfiguration, "minimumCooldownSeconds", 60 * 2); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/LootBonusBlocksConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/LootBonusBlocksConfig.java new file mode 100644 index 000000000..727504ae4 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/LootBonusBlocksConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class LootBonusBlocksConfig extends EnchantmentsConfigFields { + public LootBonusBlocksConfig() { + super("loot_bonus_blocks", + true, + "Fortune", + 3, + 13); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/LootBonusMobsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/LootBonusMobsConfig.java new file mode 100644 index 000000000..7244d288a --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/LootBonusMobsConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class LootBonusMobsConfig extends EnchantmentsConfigFields { + public LootBonusMobsConfig() { + super("loot_bonus_mobs", + true, + "Looting", + 3, + 6); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/LoyaltyConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/LoyaltyConfig.java new file mode 100644 index 000000000..314a5c0b5 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/LoyaltyConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class LoyaltyConfig extends EnchantmentsConfigFields { + public LoyaltyConfig() { + super("loyalty", + true, + "Loyalty", + 3, + 6); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/LuckConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/LuckConfig.java new file mode 100644 index 000000000..80b33bfa5 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/LuckConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class LuckConfig extends EnchantmentsConfigFields { + public LuckConfig() { + super("luck", + true, + "Luck of the Sea", + 3, + 6); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/LureConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/LureConfig.java new file mode 100644 index 000000000..26f2821ca --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/LureConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class LureConfig extends EnchantmentsConfigFields { + public LureConfig() { + super("lure", + true, + "Lure", + 3, + 6); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/MendingConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/MendingConfig.java new file mode 100644 index 000000000..8510b17b0 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/MendingConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class MendingConfig extends EnchantmentsConfigFields { + public MendingConfig() { + super("mending", + false, + "Mending", + 1, + 13); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/MeteorShowerConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/MeteorShowerConfig.java new file mode 100644 index 000000000..463ca0b13 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/MeteorShowerConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class MeteorShowerConfig extends EnchantmentsConfigFields { + public MeteorShowerConfig() { + super("meteor_shower", + true, + "Meteor Shower", + 1, + 130); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/MultishotConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/MultishotConfig.java new file mode 100644 index 000000000..71dc6cd14 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/MultishotConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class MultishotConfig extends EnchantmentsConfigFields { + public MultishotConfig() { + super("multishot", + true, + "Multishot", + 1, + 6); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/OxygenConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/OxygenConfig.java new file mode 100644 index 000000000..930d79e39 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/OxygenConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class OxygenConfig extends EnchantmentsConfigFields { + public OxygenConfig() { + super("oxygen", + true, + "Respiration", + 3, + 6); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/PiercingConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/PiercingConfig.java new file mode 100644 index 000000000..200fed0e8 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/PiercingConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class PiercingConfig extends EnchantmentsConfigFields { + public PiercingConfig() { + super("piercing", + true, + "Piercing", + 4, + 6); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/PlasmaBootsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/PlasmaBootsConfig.java new file mode 100644 index 000000000..89279e814 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/PlasmaBootsConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class PlasmaBootsConfig extends EnchantmentsConfigFields { + public PlasmaBootsConfig() { + super("plasma_boots", + true, + "Plasma Boots", + 3, + 20); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ProtectionEnvironmentalConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ProtectionEnvironmentalConfig.java new file mode 100644 index 000000000..f3deace49 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ProtectionEnvironmentalConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class ProtectionEnvironmentalConfig extends EnchantmentsConfigFields { + public ProtectionEnvironmentalConfig() { + super("protection_environmental", + true, + "Protection", + 200, + 13); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ProtectionExplosionsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ProtectionExplosionsConfig.java new file mode 100644 index 000000000..e4e91a6fe --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ProtectionExplosionsConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class ProtectionExplosionsConfig extends EnchantmentsConfigFields { + public ProtectionExplosionsConfig() { + super("protection_explosions", + true, + "Blast Protection", + 100, + 6); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ProtectionFallConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ProtectionFallConfig.java new file mode 100644 index 000000000..3a3fca9f7 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ProtectionFallConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class ProtectionFallConfig extends EnchantmentsConfigFields { + public ProtectionFallConfig() { + super("protection_fall", + true, + "Feather Falling", + 4, + 6); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ProtectionFireConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ProtectionFireConfig.java new file mode 100644 index 000000000..0e3d24e48 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ProtectionFireConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class ProtectionFireConfig extends EnchantmentsConfigFields { + public ProtectionFireConfig() { + super("protection_fire", + true, + "Fire Protection", + 4, + 6); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ProtectionProjectileConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ProtectionProjectileConfig.java new file mode 100644 index 000000000..be6c469a0 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ProtectionProjectileConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class ProtectionProjectileConfig extends EnchantmentsConfigFields { + public ProtectionProjectileConfig() { + super("protection_projectile", + true, + "Projectile Protection", + 100, + 6); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/QuickChargeConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/QuickChargeConfig.java new file mode 100644 index 000000000..7886b47cc --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/QuickChargeConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class QuickChargeConfig extends EnchantmentsConfigFields { + public QuickChargeConfig() { + super("quick_charge", + true, + "Quick Charge", + 3, + 6); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/RiptideConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/RiptideConfig.java new file mode 100644 index 000000000..f78e93c5f --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/RiptideConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class RiptideConfig extends EnchantmentsConfigFields { + public RiptideConfig() { + super("riptide", + true, + "Riptide", + 3, + 6); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/SilkTouchConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/SilkTouchConfig.java new file mode 100644 index 000000000..7b2aaa9f2 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/SilkTouchConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class SilkTouchConfig extends EnchantmentsConfigFields { + public SilkTouchConfig() { + super("silk_touch", + true, + "Silk Touch", + 1, + 13); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/SoulbindConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/SoulbindConfig.java new file mode 100644 index 000000000..49cf55c3d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/SoulbindConfig.java @@ -0,0 +1,23 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class SoulbindConfig extends EnchantmentsConfigFields { + public static String loreStrings; + public static String hologramStrings; + + public SoulbindConfig() { + super("soulbind", + true, + "Soulbind", + 1, + 10); + } + + @Override + public void processAdditionalFields() { + loreStrings = ConfigurationEngine.setString(super.fileConfiguration, "loreStrings", "&7Soulbound to &f$player"); + hologramStrings = ConfigurationEngine.setString(super.fileConfiguration, "hologramString", "$player&f's"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/SummonMerchantConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/SummonMerchantConfig.java new file mode 100644 index 000000000..5c11955ce --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/SummonMerchantConfig.java @@ -0,0 +1,22 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class SummonMerchantConfig extends EnchantmentsConfigFields { + public static String message; + + public SummonMerchantConfig() { + super("summon_merchant", + true, + "Summon Merchant", + 1, + 10); + + } + + @Override + public void processAdditionalFields() { + message = ConfigurationEngine.setString(super.fileConfiguration, "message", "Jeeves!"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/SummonWolfConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/SummonWolfConfig.java new file mode 100644 index 000000000..a1605ea08 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/SummonWolfConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class SummonWolfConfig extends EnchantmentsConfigFields { + public SummonWolfConfig() { + super("summon_wolf", + true, + "Summon Wolf", + 1, + 20); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/SweepingEdgeConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/SweepingEdgeConfig.java new file mode 100644 index 000000000..e156385a6 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/SweepingEdgeConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class SweepingEdgeConfig extends EnchantmentsConfigFields { + public SweepingEdgeConfig() { + super("sweeping_edge", + true, + "Sweeping Edge", + 3, + 6); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ThornsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ThornsConfig.java new file mode 100644 index 000000000..fa95765a7 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/ThornsConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class ThornsConfig extends EnchantmentsConfigFields { + public ThornsConfig() { + super("thorns", + true, + "Thorns", + 100, + 6); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/UnbindConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/UnbindConfig.java new file mode 100644 index 000000000..334a7bafb --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/UnbindConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class UnbindConfig extends EnchantmentsConfigFields { + public UnbindConfig() { + super("unbind", + true, + "Unbind", + 1, + 10000); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/VanishingCurseConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/VanishingCurseConfig.java new file mode 100644 index 000000000..0629bc8bc --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/VanishingCurseConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class VanishingCurseConfig extends EnchantmentsConfigFields { + public VanishingCurseConfig() { + super("vanishing_curse", + true, + "Curse of Vanishing", + 1, + -1); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/WaterWorkerConfig.java b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/WaterWorkerConfig.java new file mode 100644 index 000000000..0395ddf59 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/enchantments/premade/WaterWorkerConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.enchantments.premade; + +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; + +public class WaterWorkerConfig extends EnchantmentsConfigFields { + public WaterWorkerConfig() { + super("water_worker", + true, + "Aqua Affinity", + 1, + 6); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/menus/MenusConfig.java b/src/main/java/com/magmaguy/elitemobs/config/menus/MenusConfig.java new file mode 100644 index 000000000..1e87eb5f5 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/menus/MenusConfig.java @@ -0,0 +1,22 @@ +package com.magmaguy.elitemobs.config.menus; + +import com.magmaguy.elitemobs.config.CustomConfig; + +import java.util.HashMap; + +public class MenusConfig extends CustomConfig { + + private static HashMap menusConfigFields = new HashMap<>(); + + public MenusConfig() { + super("menus", "com.magmaguy.elitemobs.config.menus.premade", MenusConfigFields.class); + menusConfigFields = new HashMap<>(); + for (String key : super.getCustomConfigFieldsHashMap().keySet()) + menusConfigFields.put(key, (MenusConfigFields) super.getCustomConfigFieldsHashMap().get(key)); + } + + public static HashMap getCustomQuests() { + return menusConfigFields; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/menus/MenusConfigFields.java b/src/main/java/com/magmaguy/elitemobs/config/menus/MenusConfigFields.java new file mode 100644 index 000000000..b39e8586d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/menus/MenusConfigFields.java @@ -0,0 +1,21 @@ +package com.magmaguy.elitemobs.config.menus; + +import com.magmaguy.elitemobs.config.CustomConfigFields; +import com.magmaguy.elitemobs.config.CustomConfigFieldsInterface; + +public class MenusConfigFields extends CustomConfigFields implements CustomConfigFieldsInterface { + + public MenusConfigFields(String fileName, boolean isEnabled) { + super(fileName, isEnabled); + } + + @Override + public void processConfigFields() { + this.isEnabled = processBoolean("isEnabled", isEnabled, true, true); + processAdditionalFields(); + } + + public void processAdditionalFields() { + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/menus/premade/ArenaMenuConfig.java b/src/main/java/com/magmaguy/elitemobs/config/menus/premade/ArenaMenuConfig.java new file mode 100644 index 000000000..def3b47e4 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/menus/premade/ArenaMenuConfig.java @@ -0,0 +1,41 @@ +package com.magmaguy.elitemobs.config.menus.premade; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.menus.MenusConfigFields; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import com.magmaguy.elitemobs.utils.VersionChecker; +import lombok.Getter; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class ArenaMenuConfig extends MenusConfigFields { + @Getter + private static ItemStack playerItem; + @Getter + private static int playerItemSlot; + @Getter + private static ItemStack spectatorItem; + @Getter + private static int spectatorItemSlot; + + public ArenaMenuConfig() { + super("arena_menu", true); + } + + @Override + public void processAdditionalFields() { + playerItem = ConfigurationEngine.setItemStack(fileConfiguration, "playerItem", + ItemStackGenerator.generateItemStack(Material.DIAMOND_SWORD, "&4Challenge the arena!", Arrays.asList("&2Fight in the arena!"))); + playerItemSlot = ConfigurationEngine.setInt(fileConfiguration, "playerItemSlot", 6); + if (!VersionChecker.serverVersionOlderThan(17, 0)) + spectatorItem = ConfigurationEngine.setItemStack(fileConfiguration, "spectatorItem", + ItemStackGenerator.generateItemStack(Material.SPYGLASS, "&aSpectate!", Arrays.asList("&2Spectate players in the arena!"))); + else + spectatorItem = ConfigurationEngine.setItemStack(fileConfiguration, "spectatorItem", + ItemStackGenerator.generateItemStack(Material.NOTE_BLOCK, "&aSpectate!", Arrays.asList("&2Spectate players in the arena!"))); + spectatorItemSlot = ConfigurationEngine.setInt(fileConfiguration, "spectatorItemSlot", 2); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/menus/premade/BuyOrSellMenuConfig.java b/src/main/java/com/magmaguy/elitemobs/config/menus/premade/BuyOrSellMenuConfig.java new file mode 100644 index 000000000..da6b2e7b5 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/menus/premade/BuyOrSellMenuConfig.java @@ -0,0 +1,52 @@ +package com.magmaguy.elitemobs.config.menus.premade; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.menus.MenusConfigFields; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import com.magmaguy.elitemobs.utils.ItemStackSerializer; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class BuyOrSellMenuConfig extends MenusConfigFields { + public static String SHOP_NAME; + public static ItemStack INFORMATION_ITEM; + public static int INFORMATION_SLOT; + public static ItemStack BUY_PROCEDURAL_ITEM; + public static ItemStack BUY_CUSTOM_ITEM; + public static int BUY_SLOT; + public static ItemStack SELL_ITEM; + public static int SELL_SLOT; + + public BuyOrSellMenuConfig() { + super("buy_or_sell_menu", true); + } + + @Override + public void processAdditionalFields() { + SHOP_NAME = ConfigurationEngine.setString(fileConfiguration, "Shop name", "[EM] Custom Item Shop"); + ItemStackSerializer.serialize( + "Information button", + ItemStackGenerator.generateSkullItemStack("magmaguy", + "&4&lEliteMobs &r&cby &4&lMagmaGuy", + Arrays.asList("&8Support the plugins you enjoy!", + "&aClick on the emerald to buy items!", + "&cClick on the redstone to sell items!")), + fileConfiguration); + INFORMATION_ITEM = ItemStackSerializer.deserialize("Information button", fileConfiguration); + INFORMATION_SLOT = ConfigurationEngine.setInt(fileConfiguration, "Information button slot", 4); + ItemStackSerializer.serialize("Buy procedurally generated items", + ItemStackGenerator.generateItemStack(Material.EMERALD, "Buy items"), fileConfiguration); + BUY_PROCEDURAL_ITEM = ItemStackSerializer.deserialize("Buy procedurally generated items", fileConfiguration); + ItemStackSerializer.serialize("Buy custom items", + ItemStackGenerator.generateItemStack(Material.EMERALD, "Buy custom items"), fileConfiguration); + BUY_CUSTOM_ITEM = ItemStackSerializer.deserialize("Buy custom items", fileConfiguration); + ItemStackSerializer.serialize("Sell items", + ItemStackGenerator.generateItemStack(Material.REDSTONE, "Sell items"), fileConfiguration); + SELL_ITEM = ItemStackSerializer.deserialize("Sell items", fileConfiguration); + BUY_SLOT = ConfigurationEngine.setInt(fileConfiguration, "Buy slot", 11); + SELL_SLOT = ConfigurationEngine.setInt(fileConfiguration, "Sell slot", 15); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/menus/premade/CustomQuestMenuConfig.java b/src/main/java/com/magmaguy/elitemobs/config/menus/premade/CustomQuestMenuConfig.java new file mode 100644 index 000000000..94ae62c73 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/menus/premade/CustomQuestMenuConfig.java @@ -0,0 +1,180 @@ +package com.magmaguy.elitemobs.config.menus.premade; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.EconomySettingsConfig; +import com.magmaguy.elitemobs.config.menus.MenusConfigFields; +import com.magmaguy.elitemobs.items.customloottable.*; +import com.magmaguy.elitemobs.quests.objectives.CustomFetchObjective; +import com.magmaguy.elitemobs.quests.objectives.CustomKillObjective; +import com.magmaguy.elitemobs.quests.objectives.DialogObjective; +import com.magmaguy.elitemobs.quests.objectives.Objective; +import com.magmaguy.elitemobs.quests.rewards.QuestReward; +import lombok.Getter; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; + +public class CustomQuestMenuConfig extends MenusConfigFields { + @Getter + private static String headerTextLines; + @Getter + private static String acceptTextLines; + @Getter + private static String acceptHoverLines; + @Getter + private static String acceptCommandLines; + @Getter + private static String acceptedTextLines; + @Getter + private static String acceptedHoverLines; + @Getter + private static String acceptedCommandLines; + @Getter + private static String trackTextLines; + @Getter + private static String trackHoverLines; + @Getter + private static String trackCommandLines; + @Getter + private static String untrackTextLines; + @Getter + private static String untrackHoverLines; + @Getter + private static String untrackCommandLines; + @Getter + private static String completedTextLines; + @Getter + private static String completedHoverLines; + @Getter + private static String completedCommandLines; + @Getter + private static String ongoingColorCode; + @Getter + private static String completedColorCode; + @Getter + private static String objectivesLine; + @Getter + private static String rewardsLine; + @Getter + private static String turnedInTextLines; + private static String turnedInHoverLines; + private static String killQuestDefaultSummaryLine; + private static String fetchQuestDefaultSummaryLine; + private static String dialogQuestDefaultSummaryLine; + private static String rewardsDefaultSummaryLine; + @Getter + private static boolean useQuestTracking; + + public CustomQuestMenuConfig() { + super("custom_quest_screen", true); + } + + public static String getObjectiveLine(Objective objective) { + if (objective == null) return ""; + String newString = ""; + if (objective instanceof CustomKillObjective) + newString = killQuestDefaultSummaryLine; + else if (objective instanceof DialogObjective) + newString = dialogQuestDefaultSummaryLine.replace("$location", ((DialogObjective) objective).getTargetLocation()); + else if (objective instanceof CustomFetchObjective) + newString = fetchQuestDefaultSummaryLine; + newString = newString.replace("$name", ChatColor.BLACK + ChatColor.stripColor(objective.getObjectiveName())); + newString = newString.replace("$current", objective.getCurrentAmount() + ""); + newString = newString.replace("$target", objective.getTargetAmount() + ""); + if (!objective.isObjectiveCompleted()) + return newString.replace("$color", ongoingColorCode); + else + return newString.replace("$color", completedColorCode); + } + + public static List getRewardsDefaultSummaryLine(QuestReward questReward) { + List textComponent = new ArrayList<>(); + if (questReward.getCustomLootTable() == null) return textComponent; + for (CustomLootEntry customLootEntry : questReward.getCustomLootTable().getEntries()) { + ItemStack itemStack = null; + if (customLootEntry instanceof EliteCustomLootEntry) + itemStack = ((EliteCustomLootEntry) customLootEntry).generateItemStack(questReward.getRewardLevel(), Bukkit.getPlayer(questReward.getPlayerUUID()), null); + else if (customLootEntry instanceof SpecialCustomLootEntry) + itemStack = ((SpecialCustomLootEntry) customLootEntry).generateItemStack(Bukkit.getPlayer(questReward.getPlayerUUID())); + else if (customLootEntry instanceof ItemStackCustomLootEntry) + itemStack = ((ItemStackCustomLootEntry) customLootEntry).generateItemStack(); + if (itemStack != null) { + textComponent.add(new TextComponent(rewardsDefaultSummaryLine + .replace("$amount", customLootEntry.getAmount() + "") + .replace("$rewardName", itemStack.getItemMeta().getDisplayName()) + .replace("$chance", (int) (customLootEntry.getChance() * 100) + ""))); + continue; + } + + if (customLootEntry instanceof VanillaCustomLootEntry) + itemStack = ((VanillaCustomLootEntry) customLootEntry).generateItemStack(); + if (itemStack != null) { + textComponent.add(new TextComponent(rewardsDefaultSummaryLine + .replace("$amount", customLootEntry.getAmount() + "") + .replace("$rewardName", itemStack.getType().toString().replace("_", " ")) + .replace("$chance", (int) (customLootEntry.getChance() * 100) + ""))); + continue; + } + + if (customLootEntry instanceof CurrencyCustomLootEntry) { + textComponent.add(new TextComponent(rewardsDefaultSummaryLine + .replace("$amount", customLootEntry.getAmount() + "") + .replace("$rewardName", ((CurrencyCustomLootEntry) customLootEntry).getCurrencyAmount() + " " + EconomySettingsConfig.getCurrencyName()) + .replace("$chance", (int) (customLootEntry.getChance() * 100) + ""))); + + } + } + return textComponent; + } + + + @Override + public void processAdditionalFields() { + //headerTextLines = ConfigurationEngine.setString(fileConfiguration, "headerTextLines", ChatColorConverter.convert("&0&m⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯\n&c&l$questName\n&0&m⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯")); + + headerTextLines = ConfigurationEngine.setString(fileConfiguration, "headerTextLines2", ChatColorConverter.convert("&a&l『&c&l$questName&a&l』\n")); + + acceptTextLines = ConfigurationEngine.setString(fileConfiguration, "acceptTextLines", "&a&l[Accept!]"); + acceptHoverLines = ConfigurationEngine.setString(fileConfiguration, "acceptHoverLines", "&aClick to \n&aaccept quest!"); + acceptCommandLines = ConfigurationEngine.setString(fileConfiguration, "acceptCommandLines", "/em quest accept $questID"); + + acceptedTextLines = ConfigurationEngine.setString(fileConfiguration, "acceptedTextLines", "&2&lAccepted! &4[Abandon]"); + acceptedHoverLines = ConfigurationEngine.setString(fileConfiguration, "acceptedHoverLines", "&aClick to abandon quest!"); + acceptedCommandLines = ConfigurationEngine.setString(fileConfiguration, "acceptedCommandLines3", "/em quest leave $questID"); + + useQuestTracking = ConfigurationEngine.setBoolean(fileConfiguration, "useQuestTracking", true); + + trackTextLines = ConfigurationEngine.setString(fileConfiguration, "trackTextLines", "&2&l[Track]"); + trackHoverLines = ConfigurationEngine.setString(fileConfiguration, "trackHoverLines", "&aClick to track quest!"); + trackCommandLines = ConfigurationEngine.setString(fileConfiguration, "trackCommandLines3", "/em quest track $questID"); + + untrackTextLines = ConfigurationEngine.setString(fileConfiguration, "untrackTextLines", "&4&l[Untrack]"); + untrackHoverLines = ConfigurationEngine.setString(fileConfiguration, "untrackHoverLines", "&cClick to untrack quest!"); + untrackCommandLines = ConfigurationEngine.setString(fileConfiguration, "untrackCommandLines", "/em quest track $questID"); + + completedTextLines = ConfigurationEngine.setString(fileConfiguration, "completedTextLines", "&2&l[Turn in!]"); + completedHoverLines = ConfigurationEngine.setString(fileConfiguration, "completedHoverLines", "&aClick to turn quest in!"); + completedCommandLines = ConfigurationEngine.setString(fileConfiguration, "completedCommandLines", "/em quest complete $questID"); + + turnedInTextLines = ConfigurationEngine.setString(fileConfiguration, "turnedInTextLines", "&8[Completed!]"); + turnedInHoverLines = ConfigurationEngine.setString(fileConfiguration, "turnedInHoverLines", "&8Already turned in!"); + + objectivesLine = ConfigurationEngine.setString(fileConfiguration, "objectivesLine", "&c&lObjectives:"); + killQuestDefaultSummaryLine = ConfigurationEngine.setString(fileConfiguration, "killQuestDefaultSummaryLine", "&c➤Kill $name:$color$current&0/$color$target"); + fetchQuestDefaultSummaryLine = ConfigurationEngine.setString(fileConfiguration, "fetchQuestDefaultSummaryLine", "&c➤Get $name:$color&$current&0/$color$target"); + dialogQuestDefaultSummaryLine = ConfigurationEngine.setString(fileConfiguration, "dialogQuestDefaultSummaryLine", "&c➤Go talk to $name $location"); + + rewardsLine = ConfigurationEngine.setString(fileConfiguration, "rewardsLine", "&2&lRewards:"); + rewardsDefaultSummaryLine = ConfigurationEngine.setString(fileConfiguration, "rewardsDefaultSummaryLine", "&2➤$amountx $rewardName &8($chance%)"); + + ongoingColorCode = ConfigurationEngine.setString(fileConfiguration, "ongoingQuestColorCode", "&c"); + completedColorCode = ConfigurationEngine.setString(fileConfiguration, "ongoingQuestColorCode", "&2"); + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/menus/premade/CustomShopMenuConfig.java b/src/main/java/com/magmaguy/elitemobs/config/menus/premade/CustomShopMenuConfig.java new file mode 100644 index 000000000..54af91536 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/menus/premade/CustomShopMenuConfig.java @@ -0,0 +1,41 @@ +package com.magmaguy.elitemobs.config.menus.premade; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.menus.MenusConfigFields; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import com.magmaguy.elitemobs.utils.ItemStackSerializer; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; +import java.util.List; + + +public class CustomShopMenuConfig extends MenusConfigFields { + public static String shopName; + public static ItemStack rerollItem; + public static int rerollSlot; + public static List storeSlots; + public static String messageFullInventory; + + public CustomShopMenuConfig() { + super("custom_shop_menu", true); + } + + @Override + public void processAdditionalFields() { + shopName = ConfigurationEngine.setString(fileConfiguration, "Shop name", "[EM] Buy or Sell"); + ItemStackSerializer.serialize("Reroll button", + ItemStackGenerator.generateSkullItemStack("magmaguy", + "&4&lEliteMobs &r&cby &4&lMagmaGuy", + Arrays.asList("&8Support the plugins you enjoy!")), + fileConfiguration); + rerollItem = ItemStackSerializer.deserialize("Reroll button", fileConfiguration); + rerollSlot = ConfigurationEngine.setInt(fileConfiguration, "Reroll button slot", 4); + storeSlots = ConfigurationEngine.setList(fileConfiguration, "Store item slots", Arrays.asList(9, 10, 11, 12, 13, 14, 15, 16, + 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, + 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53)); + messageFullInventory = ConfigurationEngine.setString(fileConfiguration, "Full inventory message", + "[EliteMobs] &4Your inventory is full! You can't buy items until you get some free space."); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/menus/premade/DynamicQuestMenuConfig.java b/src/main/java/com/magmaguy/elitemobs/config/menus/premade/DynamicQuestMenuConfig.java new file mode 100644 index 000000000..299070a36 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/menus/premade/DynamicQuestMenuConfig.java @@ -0,0 +1,149 @@ +package com.magmaguy.elitemobs.config.menus.premade; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.EconomySettingsConfig; +import com.magmaguy.elitemobs.config.menus.MenusConfigFields; +import com.magmaguy.elitemobs.items.customloottable.*; +import com.magmaguy.elitemobs.quests.objectives.Objective; +import com.magmaguy.elitemobs.quests.rewards.QuestReward; +import lombok.Getter; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; +import java.util.List; + +public class DynamicQuestMenuConfig extends MenusConfigFields { + @Getter + private static String questName; + @Getter + private static String headerTextLines; + @Getter + private static String defaultLoreTextLines; + @Getter + private static String acceptTextLines; + @Getter + private static String acceptHoverLines; + @Getter + private static String acceptCommandLines; + @Getter + private static String acceptedTextLines; + @Getter + private static String acceptedHoverLines; + @Getter + private static String acceptedCommandLines; + @Getter + private static String completedTextLines; + @Getter + private static String completedHoverLines; + @Getter + private static String completedCommandLines; + @Getter + private static String turnedInTextLines; + @Getter + private static String turnedInHoverLines; + @Getter + private static String ongoingColorCode; + @Getter + private static String completedColorCode; + @Getter + private static String objectivesLine; + @Getter + private static String rewardsLine; + + private static String killQuestDefaultSummaryLine; + private static String rewardsDefaultSummaryLine; + + public DynamicQuestMenuConfig() { + super("dynamic_quest_screen", true); + } + + public static String getKillQuestDefaultSummaryLine(Objective objective) { + String newString = killQuestDefaultSummaryLine; + newString = newString.replace("$name", ChatColor.BLACK + ChatColor.stripColor((objective).getObjectiveName())); + newString = newString.replace("$current", objective.getCurrentAmount() + ""); + newString = newString.replace("$target", objective.getTargetAmount() + ""); + if (!objective.isObjectiveCompleted()) + return newString.replace("$color", ongoingColorCode); + else + return newString.replace("$color", completedColorCode); + } + + public static List getRewardsDefaultSummaryLine(QuestReward questReward) { + List textComponent = new ArrayList<>(); + if (questReward.getCustomLootTable() == null) return textComponent; + for (CustomLootEntry customLootEntry : questReward.getCustomLootTable().getEntries()) { + ItemStack itemStack = null; + if (customLootEntry instanceof EliteCustomLootEntry) + itemStack = ((EliteCustomLootEntry) customLootEntry).generateItemStack(questReward.getRewardLevel(), Bukkit.getPlayer(questReward.getPlayerUUID()), null); + else if (customLootEntry instanceof SpecialCustomLootEntry) + itemStack = ((SpecialCustomLootEntry) customLootEntry).generateItemStack(Bukkit.getPlayer(questReward.getPlayerUUID())); + else if (customLootEntry instanceof ItemStackCustomLootEntry) + itemStack = ((ItemStackCustomLootEntry) customLootEntry).generateItemStack(); + if (itemStack != null) { + textComponent.add(new TextComponent(rewardsDefaultSummaryLine + .replace("$amount", customLootEntry.getAmount() + "") + .replace("$rewardName", itemStack.getItemMeta().getDisplayName()) + .replace("$chance", (int) (customLootEntry.getChance() * 100) + ""))); + continue; + } + + if (customLootEntry instanceof VanillaCustomLootEntry) + itemStack = ((VanillaCustomLootEntry) customLootEntry).generateItemStack(); + if (itemStack != null) { + textComponent.add(new TextComponent(rewardsDefaultSummaryLine + .replace("$amount", customLootEntry.getAmount() + "") + .replace("$rewardName", itemStack.getType().toString().replace("_", " ")) + .replace("$chance", (int) (customLootEntry.getChance() * 100) + ""))); + continue; + } + + if (customLootEntry instanceof CurrencyCustomLootEntry) { + textComponent.add(new TextComponent(rewardsDefaultSummaryLine + .replace("$amount", customLootEntry.getAmount() + "") + .replace("$rewardName", ((CurrencyCustomLootEntry) customLootEntry).getCurrencyAmount() + " " + EconomySettingsConfig.getCurrencyName()) + .replace("$chance", (int) (customLootEntry.getChance() * 100) + ""))); + + } + } + return textComponent; + } + + @Override + public void processAdditionalFields() { + questName = ConfigurationEngine.setString(fileConfiguration, "questName", "Slay $amount $name"); + + headerTextLines = ConfigurationEngine.setString(fileConfiguration, "headerTextLines2", + ChatColorConverter.convert("&c&lGuild request!\n&0&m⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯")); + + defaultLoreTextLines = ConfigurationEngine.setString(fileConfiguration, "defaultLoreTextLines", "&8Slay $amount $name!"); + + acceptTextLines = ConfigurationEngine.setString(fileConfiguration, "acceptTextLines", "&a&lAccept!"); + acceptHoverLines = ConfigurationEngine.setString(fileConfiguration, "acceptHoverLines", "&aClick to \n&aaccept quest!"); + acceptCommandLines = ConfigurationEngine.setString(fileConfiguration, "acceptCommandLines", "/em quest accept $questID"); + + acceptedTextLines = ConfigurationEngine.setString(fileConfiguration, "acceptedTextLines", "&2&lAccepted! &4[Abandon]"); + acceptedHoverLines = ConfigurationEngine.setString(fileConfiguration, "acceptedHoverLines", "&aClick to abandon quest!"); + acceptedCommandLines = ConfigurationEngine.setString(fileConfiguration, "acceptedCommandLines3", "/em quest leave $questID"); + + completedTextLines = ConfigurationEngine.setString(fileConfiguration, "completedTextLines", "&2&l[Turn in!]"); + completedHoverLines = ConfigurationEngine.setString(fileConfiguration, "completedHoverLines", "&aClick to turn quest in!"); + completedCommandLines = ConfigurationEngine.setString(fileConfiguration, "completedCommandLines", "/em quest complete $questID"); + + turnedInTextLines = ConfigurationEngine.setString(fileConfiguration, "turnedInTextLines", "&8[Completed!]"); + turnedInHoverLines = ConfigurationEngine.setString(fileConfiguration, "turnedInHoverLines", "&8Already turned in!"); + + objectivesLine = ConfigurationEngine.setString(fileConfiguration, "objectivesLine", "&c&lObjectives:"); + killQuestDefaultSummaryLine = ConfigurationEngine.setString(fileConfiguration, "killQuestDefaultSummaryLine", "&c➤Kill $name:$color$current&0/$color$target"); + + rewardsLine = ConfigurationEngine.setString(fileConfiguration, "rewardsLine", "&2&lRewards:"); + rewardsDefaultSummaryLine = ConfigurationEngine.setString(fileConfiguration, "rewardsDefaultSummaryLine", "&2➤$amountx $rewardName &8($chance%)"); + + ongoingColorCode = ConfigurationEngine.setString(fileConfiguration, "ongoingQuestColorCode", "&c"); + completedColorCode = ConfigurationEngine.setString(fileConfiguration, "ongoingQuestColorCode", "&2"); + + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/menus/premade/EnhancementMenuConfig.java b/src/main/java/com/magmaguy/elitemobs/config/menus/premade/EnhancementMenuConfig.java new file mode 100644 index 000000000..fc90ccfd2 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/menus/premade/EnhancementMenuConfig.java @@ -0,0 +1,82 @@ +package com.magmaguy.elitemobs.config.menus.premade; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.menus.MenusConfigFields; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import com.magmaguy.elitemobs.utils.ItemStackSerializer; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class EnhancementMenuConfig extends MenusConfigFields { + public static String shopName; + public static ItemStack infoButton; + public static ItemStack eliteItemInputInfoButton; + public static ItemStack eliteUpgradeOrbInputInfoButton; + public static ItemStack outputInfoButton; + public static int infoSlot; + public static int eliteItemInputInformationSlot; + public static int eliteUpgradeOrbInputInformationSlot; + public static int outputInformationSlot; + public static int eliteItemInputSlot; + public static int eliteUpgradeOrbInputSlot; + public static int outputSlot; + public static ItemStack cancelButton; + public static int cancelSlot; + public static ItemStack confirmButton; + public static int confirmSlot; + + public EnhancementMenuConfig() { + super("enhancement_menu", true); + } + + @Override + public void processAdditionalFields() { + shopName = ConfigurationEngine.setString(fileConfiguration, "shopName", "[EM] Enhancement menu!"); + infoSlot = ConfigurationEngine.setInt(fileConfiguration, "infoButtonSlot", 4); + eliteItemInputInformationSlot = ConfigurationEngine.setInt(fileConfiguration, "eliteItemInputInformationSlot", 20); + eliteItemInputSlot = ConfigurationEngine.setInt(fileConfiguration, "eliteItemInputSlot", 29); + eliteUpgradeOrbInputInformationSlot = ConfigurationEngine.setInt(fileConfiguration, "eliteUpgradeOrbInputInformationSlot", 22); + eliteUpgradeOrbInputSlot = ConfigurationEngine.setInt(fileConfiguration, "eliteUpgradeOrbInputSlot", 31); + outputInformationSlot = ConfigurationEngine.setInt(fileConfiguration, "informationOutputButtonSlot", 24); + outputSlot = ConfigurationEngine.setInt(fileConfiguration, "outputSlot", 33); + ItemStackSerializer.serialize( + "infoButton", + ItemStackGenerator.generateSkullItemStack("magmaguy", + "&4&lEliteMobs &r&cby &4&lMagmaGuy", + Arrays.asList("&8Support the plugins you enjoy!", + "&aUse Item Upgrade Orbs one level higher", " than your Elite Item in order to", "upgrade Elite Items!")), + fileConfiguration); + ItemStackSerializer.serialize( + "eliteItemInputInformationButton", + ItemStackGenerator.generateItemStack(Material.GREEN_BANNER, + "&2Elite Item Input slots", + Arrays.asList("&aThis slot is for your elite item!")), + fileConfiguration); + ItemStackSerializer.serialize( + "eliteUpgradeOrbInputInformationButton", + ItemStackGenerator.generateItemStack(Material.GREEN_BANNER, + "&2Upgrade Orb Input slot", + Arrays.asList("&aThis slot is for your Elite Item Upgrade Orb!")), + fileConfiguration); + ItemStackSerializer.serialize("cancelButton", ItemStackGenerator.generateItemStack(Material.BARRIER, + "&4Cancel", Arrays.asList("&cCancel upgrade!")), fileConfiguration); + ItemStackSerializer.serialize( + "outputInformationButton", + ItemStackGenerator.generateItemStack(Material.RED_BANNER, + "&2Output slots", + Arrays.asList("&aThis slot previews the result of your upgrade!")), + fileConfiguration); + outputInfoButton = ItemStackSerializer.deserialize("outputInformationButton", fileConfiguration); + cancelButton = ItemStackSerializer.deserialize("cancelButton", fileConfiguration); + eliteUpgradeOrbInputInfoButton = ItemStackSerializer.deserialize("eliteUpgradeOrbInputInformationButton", fileConfiguration); + eliteItemInputInfoButton = ItemStackSerializer.deserialize("eliteItemInputInformationButton", fileConfiguration); + cancelSlot = ConfigurationEngine.setInt(fileConfiguration, "cancelButtonSlot", 27); + infoButton = ItemStackSerializer.deserialize("infoButton", fileConfiguration); + ItemStackSerializer.serialize("confirmButton", ItemStackGenerator.generateItemStack(Material.EMERALD, + "&2Confirm!", Arrays.asList("&aUpgrade items!")), fileConfiguration); + confirmButton = ItemStackSerializer.deserialize("confirmButton", fileConfiguration); + confirmSlot = ConfigurationEngine.setInt(fileConfiguration, "confirmRepairSlot", 35); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/menus/premade/GetLootMenuConfig.java b/src/main/java/com/magmaguy/elitemobs/config/menus/premade/GetLootMenuConfig.java new file mode 100644 index 000000000..2e7f5e82f --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/menus/premade/GetLootMenuConfig.java @@ -0,0 +1,71 @@ +package com.magmaguy.elitemobs.config.menus.premade; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.menus.MenusConfigFields; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import com.magmaguy.elitemobs.utils.ItemStackSerializer; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class GetLootMenuConfig extends MenusConfigFields { + public static String menuName; + public static ItemStack infoItem; + public static ItemStack leftArrowItem, rightArrowItem, previousLootItem, nextLootItem; + public static String tierTranslation, itemFilterTranslation; + + public GetLootMenuConfig() { + super("get_loot_menu", true); + } + + @Override + public void processAdditionalFields() { + + menuName = ConfigurationEngine.setString(fileConfiguration, "Menu name", "[EM] Getloot menu"); + + ItemStackSerializer.serialize( + "Info button", + ItemStackGenerator.generateSkullItemStack("magmaguy", + "&4&lEliteMobs &r&cby &4&lMagmaGuy", + Arrays.asList("&8Support the plugins you enjoy!")), + fileConfiguration); + infoItem = ItemStackSerializer.deserialize("Info button", fileConfiguration); + + ItemStackSerializer.serialize( + "Left button", + ItemStackGenerator.generateSkullItemStack("MHF_ArrowLeft", + "Previous Item Ranks", + Arrays.asList("")), + fileConfiguration); + leftArrowItem = ItemStackSerializer.deserialize("Left button", fileConfiguration); + + ItemStackSerializer.serialize( + "Right button", + ItemStackGenerator.generateSkullItemStack("MHF_ArrowRight", + "Next Item Ranks", + Arrays.asList("")), + fileConfiguration); + rightArrowItem = ItemStackSerializer.deserialize("Right button", fileConfiguration); + + tierTranslation = ConfigurationEngine.setString(fileConfiguration, "tierTranslation", "Tier"); + itemFilterTranslation = ConfigurationEngine.setString(fileConfiguration, "itemFilterTranslation", "Filter by items of this rank."); + + ItemStackSerializer.serialize( + "previousLoot", + ItemStackGenerator.generateSkullItemStack("MHF_ArrowLeft", + "Previous Loot Page", + Arrays.asList("")), + fileConfiguration); + previousLootItem = ItemStackSerializer.deserialize("previousLoot", fileConfiguration); + + ItemStackSerializer.serialize( + "nextLoot", + ItemStackGenerator.generateSkullItemStack("MHF_ArrowRight", + "Next Loot Page", + Arrays.asList("")), + fileConfiguration); + nextLootItem = ItemStackSerializer.deserialize("nextLoot", fileConfiguration); + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/menus/premade/GuildRankMenuConfig.java b/src/main/java/com/magmaguy/elitemobs/config/menus/premade/GuildRankMenuConfig.java new file mode 100644 index 000000000..09808d564 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/menus/premade/GuildRankMenuConfig.java @@ -0,0 +1,180 @@ +package com.magmaguy.elitemobs.config.menus.premade; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.menus.MenusConfigFields; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import com.magmaguy.elitemobs.utils.ItemStackSerializer; +import lombok.Getter; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class GuildRankMenuConfig extends MenusConfigFields { + @Getter + private static String menuName; + @Getter + private static String lowTierWarning; + @Getter + private static String normalTierWarning; + @Getter + private static ItemStack unlockedButton; + @Getter + private static ItemStack lockedButton; + @Getter + private static ItemStack currentButton; + @Getter + private static ItemStack nextButton; + @Getter + private static ItemStack prestigeLockedButton; + @Getter + private static ItemStack prestigeNextUnlockButton; + @Getter + private static String notEnoughCurrencyMessage; + @Getter + private static String unlockMessage; + @Getter + private static String broadcastMessage; + @Getter + private static String failedMessage; + @Getter + private static String spawnRateModifierMessage; + @Getter + private static String lootModifierMessage; + @Getter + private static String difficultyModifierMessage; + @Getter + private static String lootTierMessage; + @Getter + private static String currencyBonusMessage; + @Getter + private static String healthBonusMessage; + @Getter + private static String critBonusMessage; + @Getter + private static String dodgeBonusMessage; + + public GuildRankMenuConfig() { + super("guild_rank_selector_menu", true); + } + + @Override + public void processAdditionalFields() { + + menuName = ConfigurationEngine.setString(fileConfiguration, "questTierSelectorMenuTitle", "[EM] Guild Rank Selection"); + lowTierWarning = ConfigurationEngine.setString(fileConfiguration, "lowTierWarning", "&cElites can't drop better loot!"); + normalTierWarning = ConfigurationEngine.setString(fileConfiguration, "normalTierWarning", "&aElite can drop better loot!"); + + ItemStackSerializer.serialize( + "unlockedButtons", + ItemStackGenerator.generateItemStack(Material.GRAY_STAINED_GLASS_PANE, + "$rankName", + Arrays.asList("&f&m-------------------------------", + "&aThis rank is unlocked!", + "&fYou can select it.", + "&f&m-------------------------------", + "$lootTier", + "$currencyBonusMessage", + "$maxHealthIncrease", + "$chanceToCrit", + "$chanceToDodge")), fileConfiguration); + unlockedButton = ItemStackSerializer.deserialize("unlockedButtons", fileConfiguration); + + ItemStackSerializer.serialize( + "lockedButtons", + ItemStackGenerator.generateItemStack(Material.RED_STAINED_GLASS_PANE, + "$rankName", + Arrays.asList("&f&m-------------------------------", + "&aThis rank is locked!", + "&cYou need the $previousRank rank first!", + "&f&m-------------------------------", + "$lootTier", + "$currencyBonusMessage", + "$maxHealthIncrease", + "$chanceToCrit", + "$chanceToDodge")), fileConfiguration); + lockedButton = ItemStackSerializer.deserialize("lockedButtons", fileConfiguration); + + ItemStackSerializer.serialize( + "currentButtons", + ItemStackGenerator.generateItemStack(Material.GREEN_STAINED_GLASS_PANE, + "$rankName", + Arrays.asList("&f&m-------------------------------", + "&aThis is your current rank!", + "&f&m-------------------------------", + "$lootTier", + "$currencyBonusMessage", + "$maxHealthIncrease", + "$chanceToCrit", + "$chanceToDodge")), fileConfiguration); + currentButton = ItemStackSerializer.deserialize("currentButtons", fileConfiguration); + + ItemStackSerializer.serialize( + "nextButtons", + ItemStackGenerator.generateItemStack(Material.YELLOW_STAINED_GLASS_PANE, + "Prestige $prestigeNumber", + Arrays.asList( + "&6This is the next rank you can unlock", + "&aSelect it when you're ready!", + "&6Costs $price &6$currencyName", + "&fYou have &a$currentCurrency $currencyName", + "&f&m-------------------------------", + "$lootTier", + "$currencyBonusMessage", + "$maxHealthIncrease", + "$chanceToCrit", + "$chanceToDodge")), fileConfiguration); + nextButton = ItemStackSerializer.deserialize("nextButtons", fileConfiguration); + + ItemStackSerializer.serialize( + "prestigeLockedButtons", + ItemStackGenerator.generateItemStack(Material.RED_STAINED_GLASS, + "Prestige $rank", + Arrays.asList("&f&m-------------------------------", + "&4You must unlock all guild ranks first!", + "&f&m-------------------------------")), fileConfiguration); + prestigeLockedButton = ItemStackSerializer.deserialize("prestigeLockedButtons", fileConfiguration); + + ItemStackSerializer.serialize( + "prestigeNextUnlockButtons", + ItemStackGenerator.generateItemStack(Material.GOLD_BLOCK, + "Prestige $rank", + Arrays.asList("&f&m-------------------------------", + "&2Prestige unlock is ready!", + "&6Costs $price &6$currencyName", + "&cBuying prestige will reset guild ranks", + "&abut will allow you to unlock:", + "&a- Access to higher guild tiers", + "&a- Access to higher tier loot", + "&a- More coins from kills and quests", + "&a- Higher max health", + "&a- Base chance to crit", + "&a- Base chance to dodge", + "&4Warning: this resets you current", + "&4EliteMobs ITEMS AND CURRENCY!", + "&f&m-------------------------------")), fileConfiguration); + prestigeNextUnlockButton = ItemStackSerializer.deserialize("prestigeNextUnlockButtons", fileConfiguration); + + notEnoughCurrencyMessage = ConfigurationEngine.setString(fileConfiguration, "notEnoughCurrencyMessages", + "&7[EliteMobs] &4You don't have enough Elite Coins ($neededAmount $currencyName)! Sell some Elite Mob loot to [/em shop]! " + + "You have $currentAmount $currencyName."); + + unlockMessage = ConfigurationEngine.setString(fileConfiguration, "unlockMessages", "&7[EliteMobs] &aYou have unlocked the $rankName &arank for $price $currencyName. \n&6Happy hunting!"); + + broadcastMessage = ConfigurationEngine.setString(fileConfiguration, "questCompleteBroadcastMessages", "&7[EliteMobs] &a$player &ahas reached the $rankName &aguild rank!"); + + failedMessage = ConfigurationEngine.setString(fileConfiguration, "failedMessages", "&7[EliteMobs] &cYou need to unlock other ranks first!"); + + spawnRateModifierMessage = ConfigurationEngine.setString(fileConfiguration, "spawnRateModifierMessages", "&fElite Mob spawn rate modifier: &c$modifier%"); + lootModifierMessage = ConfigurationEngine.setString(fileConfiguration, "lootModifierMessages", "&fElite Mob loot modifier: &a$modifier%"); + difficultyModifierMessage = ConfigurationEngine.setString(fileConfiguration, "difficultyModifierMessages", "&fElite Mob difficulty modifier: &c$modifier%"); + + lootTierMessage = ConfigurationEngine.setString(fileConfiguration, "lootTierMessages", "&2Elites can drop up to tier $tier loot!"); + currencyBonusMessage = ConfigurationEngine.setString(fileConfiguration, "currencyBonusMessages", "&a$amountx coins from drops and quests!"); + healthBonusMessage = ConfigurationEngine.setString(fileConfiguration, "healthBonusMessages", "&cAdds $amount ❤ of max health"); + critBonusMessage = ConfigurationEngine.setString(fileConfiguration, "critBonusMessages", "&eAdds $amount% chance to crit"); + dodgeBonusMessage = ConfigurationEngine.setString(fileConfiguration, "dodgeBonusMessages", "&8Adds $amount% chance to dodge"); + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/menus/premade/PlayerStatusMenuConfig.java b/src/main/java/com/magmaguy/elitemobs/config/menus/premade/PlayerStatusMenuConfig.java new file mode 100644 index 000000000..02c0664ff --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/menus/premade/PlayerStatusMenuConfig.java @@ -0,0 +1,525 @@ +package com.magmaguy.elitemobs.config.menus.premade; + +import com.magmaguy.elitemobs.config.AdventurersGuildConfig; +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.menus.MenusConfigFields; +import com.magmaguy.elitemobs.playerdata.statusscreen.PlayerStatusScreen; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import com.magmaguy.elitemobs.utils.VersionChecker; +import lombok.Getter; +import org.bukkit.Material; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class PlayerStatusMenuConfig extends MenusConfigFields { + @Getter + private static boolean doIndexPage; + @Getter + private static boolean doStatsPage; + @Getter + private static boolean doGearPage; + @Getter + private static boolean doTeleportsPage; + @Getter + private static boolean doCommandsPage; + @Getter + private static boolean doQuestTrackingPage; + @Getter + private static boolean doBossTrackingPage; + @Getter + private static String[] indexTextLines = new String[13]; + @Getter + private static String[] indexHoverLines = new String[13]; + @Getter + private static String[] indexCommandLines = new String[13]; + @Getter + private static String[] statsTextLines = new String[13]; + @Getter + private static String[] statsHoverLines = new String[13]; + @Getter + private static String[] statsCommandLines = new String[13]; + @Getter + private static String[] gearTextLines = new String[13]; + @Getter + private static String[] gearHoverLines = new String[13]; + @Getter + private static String[] gearCommandLines = new String[13]; + @Getter + private static String teleportChestMenuName; + @Getter + private static String[] teleportTextLines = new String[13]; + @Getter + private static String[] teleportHoverLines = new String[13]; + @Getter + private static String[] teleportCommandLines = new String[13]; + @Getter + private static String[] commandsTextLines = new String[13]; + @Getter + private static String[] commandsHoverLines = new String[13]; + @Getter + private static String[] commandsCommandLines = new String[13]; + @Getter + private static String bossTrackerChestMenuName; + @Getter + private static String[] bossTrackerTextLines = new String[13]; + @Getter + private static String[] bossTrackerHoverLines = new String[13]; + @Getter + private static String[] bossTrackerCommandLines = new String[13]; + @Getter + private static String[] questTrackerTextLines = new String[13]; + @Getter + private static String[] questTrackerHoverLines = new String[13]; + @Getter + private static String[] questTrackerCommandLines = new String[13]; + @Getter + private static String onBossTrackHover; + @Getter + private static String onQuestTrackHover; + @Getter + private static String onTeleportHover; + + @Getter + private static String indexChestMenuName; + @Getter + private static ItemStack backItem; + @Getter + private static ItemStack indexHeaderItem; + @Getter + private static int indexHeaderSlot; + @Getter + private static ItemStack indexStatsItem; + @Getter + private static int indexStatsSlot; + @Getter + private static ItemStack indexGearItem; + @Getter + private static int indexGearSlot; + @Getter + private static ItemStack indexTeleportsItem; + @Getter + private static int indexTeleportsSlot; + @Getter + private static ItemStack indexCommandsItem; + @Getter + private static int indexCommandsSlot; + @Getter + private static ItemStack indexQuestTrackingItem; + @Getter + private static int indexQuestTrackingSlot; + @Getter + private static ItemStack indexBossTrackingItem; + @Getter + private static int indexBossTrackingSlot; + @Getter + private static String gearChestMenuName; + @Getter + private static ItemStack gearDamageItem; + @Getter + private static int gearDamageSlot; + @Getter + private static ItemStack gearArmorItem; + @Getter + private static int gearArmorSlot; + @Getter + private static ItemStack gearThreatItem; + @Getter + private static int gearThreatSlot; + @Getter + private static String statsChestMenuName; + @Getter + private static ItemStack statsMoneyItem; + @Getter + private static int statsMoneySlot; + @Getter + private static ItemStack statsGuildTierItem; + @Getter + private static int statsGuildTierSlot; + @Getter + private static ItemStack statsEliteKillsItem; + @Getter + private static int statsEliteKillsSlot; + @Getter + private static ItemStack statsMaxEliteLevelKilledItem; + @Getter + private static int statsMaxEliteLevelKilledSlot; + @Getter + private static ItemStack statsEliteDeathsItem; + @Getter + private static int statsEliteDeathsSlot; + @Getter + private static ItemStack statsQuestsCompletedItem; + @Getter + private static int statsQuestsCompletedSlot; + @Getter + private static ItemStack statsScoreItem; + @Getter + private static int statsScoreSlot; + @Getter + private static String commandsChestMenuName; + @Getter + private static ItemStack commandsAGItem; + @Getter + private static int commandsAGSlot; + @Getter + private static ItemStack commandsShareItemItem; + @Getter + private static int commandsShareItemSlot; + + + public PlayerStatusMenuConfig() { + super("player_status_screen", true); + } + + private static void indexLineCreator(int line, String text, String hover, String command, FileConfiguration fileConfiguration) { + indexTextLines[line] = ConfigurationEngine.setString(fileConfiguration, "indexTexts" + line, text); + indexHoverLines[line] = ConfigurationEngine.setString(fileConfiguration, "indexHovers" + line, hover); + indexCommandLines[line] = ConfigurationEngine.setString(fileConfiguration, "indexCommands" + line, command); + } + + private static void statsLineCreator(int line, String text, String hover, String command, FileConfiguration fileConfiguration) { + statsTextLines[line] = ConfigurationEngine.setString(fileConfiguration, "statsText" + line, text); + statsHoverLines[line] = ConfigurationEngine.setString(fileConfiguration, "statsHover" + line, hover); + statsCommandLines[line] = ConfigurationEngine.setString(fileConfiguration, "statsCommand" + line, command); + } + + private static void gearLineCreator(int line, String text, String hover, String command, FileConfiguration fileConfiguration) { + gearTextLines[line] = ConfigurationEngine.setString(fileConfiguration, "gearText" + line, text); + gearHoverLines[line] = ConfigurationEngine.setString(fileConfiguration, "gearHover" + line, hover); + gearCommandLines[line] = ConfigurationEngine.setString(fileConfiguration, "gearCommand" + line, command); + } + + private static void teleportLineCreator(int line, String text, String hover, String command, FileConfiguration fileConfiguration) { + teleportTextLines[line] = ConfigurationEngine.setString(fileConfiguration, "teleportText" + line, text); + teleportHoverLines[line] = ConfigurationEngine.setString(fileConfiguration, "teleportHover" + line, hover); + teleportCommandLines[line] = ConfigurationEngine.setString(fileConfiguration, "teleportCommand" + line, command); + } + + private static void commandsLineCreator(int line, String text, String hover, String command, FileConfiguration fileConfiguration) { + commandsTextLines[line] = ConfigurationEngine.setString(fileConfiguration, "commandsText" + line, text); + commandsHoverLines[line] = ConfigurationEngine.setString(fileConfiguration, "commandsHover" + line, hover); + commandsCommandLines[line] = ConfigurationEngine.setString(fileConfiguration, "commandsCommand" + line, command); + } + + private static void questTrackerLineCreator(int line, String text, String hover, String command, FileConfiguration fileConfiguration) { + questTrackerTextLines[line] = ConfigurationEngine.setString(fileConfiguration, "questTrackerText" + line, text); + questTrackerHoverLines[line] = ConfigurationEngine.setString(fileConfiguration, "questTrackerHover" + line, hover); + questTrackerCommandLines[line] = ConfigurationEngine.setString(fileConfiguration, "questTrackerCommand" + line, command); + } + + private static void bossTrackerLineCreator(int line, String text, String hover, String command, FileConfiguration fileConfiguration) { + bossTrackerTextLines[line] = ConfigurationEngine.setString(fileConfiguration, "bossTrackerText" + line, text); + bossTrackerHoverLines[line] = ConfigurationEngine.setString(fileConfiguration, "bossTrackerHover" + line, hover); + bossTrackerCommandLines[line] = ConfigurationEngine.setString(fileConfiguration, "bossTrackerCommand" + line, command); + } + + @Override + public void processAdditionalFields() { + + doIndexPage = ConfigurationEngine.setBoolean(fileConfiguration, "doIndexPage", true); + doStatsPage = ConfigurationEngine.setBoolean(fileConfiguration, "doStatsPage", true); + doGearPage = ConfigurationEngine.setBoolean(fileConfiguration, "doGearPage", true); + doTeleportsPage = ConfigurationEngine.setBoolean(fileConfiguration, "doTeleportsPage", true); + doCommandsPage = ConfigurationEngine.setBoolean(fileConfiguration, "doCommandsPage", true); + doQuestTrackingPage = ConfigurationEngine.setBoolean(fileConfiguration, "doQuestTrackingPage", true); + doBossTrackingPage = ConfigurationEngine.setBoolean(fileConfiguration, "doBossTrackingPage", true); + + indexLineCreator(0, "&0&m⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯", "", "", fileConfiguration); + indexLineCreator(1, "&5&l/ag &7- &6EliteMobs Hub", + "CLICK TO USE\n" + + "The place where you can find\n" + + "NPCs that give quests, buy and\n" + + "sell items, give advice and more!", + "/ag", fileConfiguration); + indexLineCreator(2, "&0&m⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯", "", "", fileConfiguration); + indexLineCreator(3, "", "", "", fileConfiguration); + indexLineCreator(4, "&6&lIndex", "", "", fileConfiguration); + indexLineCreator(5, "", "", "", fileConfiguration); + indexLineCreator(6, "&bp. $statsPage &8- &6Stats", "Click to go!", "$statsPage", fileConfiguration); + indexLineCreator(7, "&bp. $gearPage &8- &6Gear", "Click to go!", "$gearPage", fileConfiguration); + indexLineCreator(8, "&bp. $teleportsPage &8- &6Teleports", "Click to go!", "$teleportsPage", fileConfiguration); + indexLineCreator(9, "&bp. $commandsPage &8- &6Commands", "Click to go!", "$commandsPage", fileConfiguration); + indexLineCreator(10, "&bp. $questsPage &8- &6Quest Tracking", "Click to go!", "$questsPage", fileConfiguration); + indexLineCreator(11, "&bp. $bossTrackingPage &8- &6Boss Tracking", "Click to go!", "$bossTrackingPage", fileConfiguration); + indexLineCreator(12, "", "", "", fileConfiguration); + + + statsLineCreator(0, "&m⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯", "", "", fileConfiguration); + statsLineCreator(1, "&5&lPlayer Stats:", "", "", fileConfiguration); + statsLineCreator(2, "&m⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯", "", "", fileConfiguration); + statsLineCreator(3, "", "", "", fileConfiguration); + statsLineCreator(4, "&2Money: &a$money", "Kill Elite Mobs to loot currency or\n" + + "sell their drops in /em shop or\n" + + "complete quests!", "", fileConfiguration); + statsLineCreator(5, "", "", "", fileConfiguration); + statsLineCreator(6, "&6Guild Tier: &3$guildtier", "Prestige Tier and Guild Rank:\n" + + "Guild Rank determines how good your loot can " + + "be, sets your bonus from the Prestige Tier, among " + + "other things. The Prestige Tier unlocks extremely " + + "powerful rewards, like increased max health, chance " + + "to dodge/crit, increased currency rewards and more! " + + "You can unlock Guild Ranks and Prestige Tiers at /ag!\n" + + "⚜ = prestige rank, ✧ = guild rank!", "", fileConfiguration); + statsLineCreator(7, "&4Elite Kills: &c$kills", "Amount of Elite Mobs killed.", "", fileConfiguration); + statsLineCreator(8, "&4Max Lvl Killed: &c$highestkill", "Level of the highest Elite Mob killed.\n" + + "Elite Mob levels are based on the tier\n" + + "of your gear! Higher tiers, higher\n" + + "Elite Mob levels!\n" + + "Note: only non-exploity kills get counted!", "", fileConfiguration); + statsLineCreator(9, "&4Elite Deaths: &c$deaths", "Times killed by Elite Mobs.", "", fileConfiguration); + statsLineCreator(10, "&5Quests Completed: &d$quests", "Amount of EliteMobs quests completed.\n" + + "You can accept quests by talking to NPCs!", "", fileConfiguration); + statsLineCreator(11, "", "", "", fileConfiguration); + statsLineCreator(12, "&bScore: &3$score", "Your EliteMobs score. It goes up\n" + + "when you kill and elite mob,\n" + + "and it goes down when you die\n" + + "to an elite. Higher level\n" + + "elites give more score.", "", fileConfiguration); + + gearLineCreator(0, "&m⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯", "", "", fileConfiguration); + gearLineCreator(1, "&7&lArmor & Weapons:", "", "", fileConfiguration); + gearLineCreator(2, "&m⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯", "", "", fileConfiguration); + gearLineCreator(3, "&8&lGear Tiers:", "", "", fileConfiguration); + gearLineCreator(4, " ☠ - $helmettier", "$helmet", "", fileConfiguration); + gearLineCreator(5, " ▼ - $chestplatetier", "$chestplate", "", fileConfiguration); + gearLineCreator(6, " Π - $leggingstier", "$leggings", "", fileConfiguration); + gearLineCreator(7, " ╯╰ - $bootstier", "$boots", "", fileConfiguration); + gearLineCreator(8, "{⚔ - $mainhandtier} {⛨ - $offhandtier}", "{$mainhand}{$offhand}", "", fileConfiguration); + gearLineCreator(9, "", "", "", fileConfiguration); + gearLineCreator(10, "{dmg : $damage} {armr: $armor}", "{Base damage dealt to Elite Mobs}{Damage reduction from Elite Mobs}", + "", fileConfiguration); + gearLineCreator(11, "Threat level: $threat", + "This determines the level of the\n" + + "Elite Mobs that spawns near you.\n" + + "Takes armor, weapon in hand, guild\n" + + "tier into account.\n", + "", fileConfiguration); + gearLineCreator(12, "", "", "", fileConfiguration); + + teleportLineCreator(0, "&m⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯", "", "", fileConfiguration); + teleportLineCreator(1, "&2&lTeleports", "", "", fileConfiguration); + teleportLineCreator(2, "&m⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯", "", "", fileConfiguration); + teleportLineCreator(3, "Spawn", "Teleport to spawn!", "/em spawntp", fileConfiguration); + teleportLineCreator(4, PlayerStatusScreen.convertLightColorsToBlack(AdventurersGuildConfig.getAdventurersGuildMenuName()), "Teleport to the Adventurer's Guild Hub!", "/ag", fileConfiguration); + + onTeleportHover = ConfigurationEngine.setString(fileConfiguration, "onTeleportsHover", "Click to teleport!"); + + commandsLineCreator(0, "&m⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯", "", "", fileConfiguration); + commandsLineCreator(1, "&3&lCommands:", "", "", fileConfiguration); + commandsLineCreator(2, "&m⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯", "", "", fileConfiguration); + commandsLineCreator(3, "", "", "", fileConfiguration); + commandsLineCreator(4, "&5/ag", "CLICK TO USE\n" + + "The place where you can find\n" + + "NPCs that give quests, buy and\n" + + "sell items, give advice and more!", "/ag", fileConfiguration); + commandsLineCreator(5, "", "", "", fileConfiguration); + commandsLineCreator(6, "&5/shareitem", "CLICK TO USE\n" + + "Shares the item you're holding\n" + + "on chat!", "/shareitem", fileConfiguration); + commandsLineCreator(7, "", "", "", fileConfiguration); + commandsLineCreator(8, "", "", "", fileConfiguration); + commandsLineCreator(9, "", "", "", fileConfiguration); + commandsLineCreator(10, "", "", "", fileConfiguration); + commandsLineCreator(11, "", "", "", fileConfiguration); + commandsLineCreator(12, "", "", "", fileConfiguration); + + questTrackerLineCreator(0, "&m⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯", "", "", fileConfiguration); + questTrackerLineCreator(1, "&6&lQuests:", "Talk to NPCs to accept quests!", "", fileConfiguration); + questTrackerLineCreator(2, "&m⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯", "", "", fileConfiguration); + + onQuestTrackHover = ConfigurationEngine.setString(fileConfiguration, "onQuestTrackHover", "Click to abandon!"); + + bossTrackerLineCreator(0, "&m⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯", "", "", fileConfiguration); + bossTrackerLineCreator(1, "&4&lBoss Tracker:", "Big bosses get displayed here!", "", fileConfiguration); + bossTrackerLineCreator(2, "&m⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯", "", "", fileConfiguration); + + onBossTrackHover = ConfigurationEngine.setString(fileConfiguration, "onBossTrackHover", "Click to track/untrack!"); + + teleportChestMenuName = ConfigurationEngine.setString(fileConfiguration, "teleportChestMenuName", "&2EliteMobs Teleports"); + + bossTrackerChestMenuName = ConfigurationEngine.setString(fileConfiguration, "bossTrackerChestMenuName", "&2EliteMobs Boss Tracking"); + + //inventory-based menus for bedrock + indexChestMenuName = ConfigurationEngine.setString(fileConfiguration, "indexChestMenuName", "&2EliteMobs Index"); + indexHeaderItem = ConfigurationEngine.setItemStack(fileConfiguration, "indexHeaderItem", + ItemStackGenerator.generateItemStack(Material.PAPER, + "&5&l/ag &7- &6EliteMobs Hub", + Arrays.asList("CLICK TO USE", + "The place where you can find", + "NPCs that give quests, buy and", + "sell items, give advice and more!"))); + indexHeaderSlot = ConfigurationEngine.setInt(fileConfiguration, "indexHeaderSlot", 4); + + indexStatsItem = ConfigurationEngine.setItemStack(fileConfiguration, "indexStatsItem", + ItemStackGenerator.generateItemStack(Material.MAP, + "&6Stats", + Arrays.asList("Click to go!"))); + indexStatsSlot = ConfigurationEngine.setInt(fileConfiguration, "indexStatsSlot", 10); + + indexGearItem = ConfigurationEngine.setItemStack(fileConfiguration, "indexGearItem", + ItemStackGenerator.generateItemStack(Material.DIAMOND_SWORD, + "&6Gear", + Arrays.asList("Click to go!"))); + indexGearSlot = ConfigurationEngine.setInt(fileConfiguration, "indexGearSlot", 12); + + indexTeleportsItem = ConfigurationEngine.setItemStack(fileConfiguration, "indexTeleportsItem", + ItemStackGenerator.generateItemStack(Material.END_PORTAL_FRAME, + "&6Teleports", + Arrays.asList("Click to go!"))); + indexTeleportsSlot = ConfigurationEngine.setInt(fileConfiguration, "indexTeleportsSlot", 14); + + indexCommandsItem = ConfigurationEngine.setItemStack(fileConfiguration, "indexCommandsItem", + ItemStackGenerator.generateItemStack(Material.JUKEBOX, + "&6Commands", + Arrays.asList("Click to go!"))); + indexCommandsSlot = ConfigurationEngine.setInt(fileConfiguration, "indexCommandsSlot", 16); + + + indexQuestTrackingItem = ConfigurationEngine.setItemStack(fileConfiguration, "indexQuestTrackingItem", + ItemStackGenerator.generateItemStack(Material.WRITABLE_BOOK, + "&6Quest Tracking", + Arrays.asList("Click to go!"))); + indexQuestTrackingSlot = ConfigurationEngine.setInt(fileConfiguration, "indexQuestTrackingSlot", 20); + + if (!VersionChecker.serverVersionOlderThan(16, 0)) + indexBossTrackingItem = ConfigurationEngine.setItemStack(fileConfiguration, "indexBossTrackingItem", + ItemStackGenerator.generateItemStack(Material.TARGET, + "&6Boss Tracking", + Arrays.asList("Click to go!"))); + else + indexBossTrackingItem = ConfigurationEngine.setItemStack(fileConfiguration, "indexBossTrackingItem", + ItemStackGenerator.generateItemStack(Material.DIAMOND, + "&6Boss Tracking", + Arrays.asList("Click to go!"))); + indexBossTrackingSlot = ConfigurationEngine.setInt(fileConfiguration, "indexBossTrackingSlot", 24); + + + backItem = ConfigurationEngine.setItemStack(fileConfiguration, "backItem", + ItemStackGenerator.generateItemStack(Material.BARRIER, "&cBack")); + + gearChestMenuName = ConfigurationEngine.setString(fileConfiguration, "gearChestMenuName", "&2EliteMobs Gear"); + gearDamageItem = ConfigurationEngine.setItemStack(fileConfiguration, "gearDamageItem", + ItemStackGenerator.generateItemStack(Material.DIAMOND_SWORD, + "&4Damage: $damage", + Arrays.asList("&fBase damage dealt to Elites.", + "&fBased on the level of your weapon!"))); + gearDamageSlot = ConfigurationEngine.setInt(fileConfiguration, "gearDamageSlot", 23); + gearArmorItem = ConfigurationEngine.setItemStack(fileConfiguration, "gearArmorItem", + ItemStackGenerator.generateItemStack(Material.SHIELD, + "&2Defense: $defense", + Arrays.asList("&fBase damage reduction from Elites.", + "&fBased on the average level of your armor!"))); + gearArmorSlot = ConfigurationEngine.setInt(fileConfiguration, "gearArmorSlot", 24); + if (!VersionChecker.serverVersionOlderThan(16, 0)) + gearThreatItem = ConfigurationEngine.setItemStack(fileConfiguration, "gearThreatItem", + ItemStackGenerator.generateItemStack(Material.TARGET, + "&cTreat Level: $threat", + Arrays.asList("&fThis determines the level of the", + "&fElite Mobs that spawns near you", + "&fTakes armor, weapon in hand, guild", + "&ftier into account."))); + else + gearThreatItem = ConfigurationEngine.setItemStack(fileConfiguration, "gearThreatItem", + ItemStackGenerator.generateItemStack(Material.DIAMOND, + "&cTreat Level: $threat", + Arrays.asList("&fThis determines the level of the", + "&fElite Mobs that spawns near you", + "&fTakes armor, weapon in hand, guild", + "&ftier into account."))); + gearThreatSlot = ConfigurationEngine.setInt(fileConfiguration, "gearThreatSlot", 25); + + statsChestMenuName = ConfigurationEngine.setString(fileConfiguration, "statsChestMenuName", "&2EliteMobs Stats"); + + statsMoneyItem = ConfigurationEngine.setItemStack(fileConfiguration, "statsMoneyItem", + ItemStackGenerator.generateItemStack(Material.GOLD_INGOT, + "&2Elite Coins: $money", + Arrays.asList("&fKill Elite Mobs to loot currency,", + "&fsell their drops in /em shop or", + "&fcomplete quests!"))); + statsMoneySlot = ConfigurationEngine.setInt(fileConfiguration, "statsMoneySlot", 10); + + if (!VersionChecker.serverVersionOlderThan(16, 0)) + statsGuildTierItem = ConfigurationEngine.setItemStack(fileConfiguration, "statsGuildTierItem", + ItemStackGenerator.generateItemStack(Material.TARGET, + "&6Guild Tier: $tier", + Arrays.asList("&fGuild Rank determines how good your loot can ", + "&fbe, sets your bonus from the Prestige Tier, among ", + "&fother things. The Prestige Tier unlocks extremely ", + "&fpowerful rewards, like increased max health, chance ", + "&fto dodge/crit, increased currency rewards and more! ", + "&fYou can unlock Guild Ranks and Prestige Tiers at /ag!", + "&f⚜ = prestige rank, ✧ = guild rank!"))); + else + statsGuildTierItem = ConfigurationEngine.setItemStack(fileConfiguration, "statsGuildTierItem", + ItemStackGenerator.generateItemStack(Material.DIAMOND, + "&6Guild Tier: $tier", + Arrays.asList("&fGuild Rank determines how good your loot can ", + "&fbe, sets your bonus from the Prestige Tier, among ", + "&fother things. The Prestige Tier unlocks extremely ", + "&fpowerful rewards, like increased max health, chance ", + "&fto dodge/crit, increased currency rewards and more! ", + "&fYou can unlock Guild Ranks and Prestige Tiers at /ag!", + "&f⚜ = prestige rank, ✧ = guild rank!"))); + statsGuildTierSlot = ConfigurationEngine.setInt(fileConfiguration, "statsGuildTierSlot", 11); + + statsEliteKillsItem = ConfigurationEngine.setItemStack(fileConfiguration, "statsEliteKillsItem", + ItemStackGenerator.generateItemStack(Material.DIAMOND_SWORD, + "&4Elite Kils: &c$kills", + Arrays.asList("&fAmount of EliteMobs killed."))); + statsEliteKillsSlot = ConfigurationEngine.setInt(fileConfiguration, "statsEliteKillsSlot", 12); + + statsMaxEliteLevelKilledItem = ConfigurationEngine.setItemStack(fileConfiguration, "statsMaxEliteLevelKilledItem", + ItemStackGenerator.generateItemStack(Material.GOLDEN_SWORD, + "&4Max Lvl Killed: &c$maxKill", + Arrays.asList("&fElite Mob levels are based on the tier", + "&fof your gear! Higher tiers, higher", + "&fElite Mob levels!\n", + "&eNote: only non-exploity kills get counted!"))); + statsMaxEliteLevelKilledSlot = ConfigurationEngine.setInt(fileConfiguration, "statsMaxEliteLevelKilledSlot", 13); + + statsEliteDeathsItem = ConfigurationEngine.setItemStack(fileConfiguration, "statsEliteDeathsItem", + ItemStackGenerator.generateItemStack(Material.TOTEM_OF_UNDYING, + "&4Elite Deaths: $deaths", + Arrays.asList("&fTimes killed by Elite Mobs."))); + statsEliteDeathsSlot = ConfigurationEngine.setInt(fileConfiguration, "statsEliteDeathsSlot", 14); + + statsQuestsCompletedItem = ConfigurationEngine.setItemStack(fileConfiguration, "statsQuestsCompletedItem", + ItemStackGenerator.generateItemStack(Material.LECTERN, + "&5Quests Completed: &d$questsCompleted", + Arrays.asList("&fAmount of EliteMobs quests completed.", + "&fYou can accept quests by talking to NPCs!"))); + statsQuestsCompletedSlot = ConfigurationEngine.setInt(fileConfiguration, "statsQuestsCompletedSlot", 15); + + statsScoreItem = ConfigurationEngine.setItemStack(fileConfiguration, "statsScoreItem", + ItemStackGenerator.generateItemStack(Material.ITEM_FRAME, + "&3Score: &b$score", + Arrays.asList("&fYour EliteMobs score. It goes up", + "&fwhen you kill and elite mob,", + "&fand it goes down when you die", + "&fto an elite. Higher level", + "&felites give more score."))); + statsScoreSlot = ConfigurationEngine.setInt(fileConfiguration, "statsScoreSlot", 16); + + commandsChestMenuName = ConfigurationEngine.setString(fileConfiguration, "commandsChestMenuName", "&2EliteMobs Commands"); + + commandsAGItem = ConfigurationEngine.setItemStack(fileConfiguration, "commandsAGItem", + ItemStackGenerator.generateItemStack(Material.END_PORTAL_FRAME, + "&5/ag", + Arrays.asList("&fClick to use!", + "&fThe place where you can find", + "&fNPCs that give quests, buy and", + "&fsell items, give advice and more!"))); + commandsAGSlot = ConfigurationEngine.setInt(fileConfiguration, "commandsAGSlot", 11); + + commandsShareItemItem = ConfigurationEngine.setItemStack(fileConfiguration, "commandsShareItemItem", + ItemStackGenerator.generateItemStack(Material.PAPER, + "&5/shareitem", + Arrays.asList("&fClick to use!", + "&fShares the Elite Item you're holding", + "&fon chat!"))); + commandsShareItemSlot = ConfigurationEngine.setInt(fileConfiguration, "commandsShareItemSlot", 15); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/menus/premade/ProceduralShopMenuConfig.java b/src/main/java/com/magmaguy/elitemobs/config/menus/premade/ProceduralShopMenuConfig.java new file mode 100644 index 000000000..2e17127fc --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/menus/premade/ProceduralShopMenuConfig.java @@ -0,0 +1,44 @@ +package com.magmaguy.elitemobs.config.menus.premade; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.menus.MenusConfigFields; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import com.magmaguy.elitemobs.utils.ItemStackSerializer; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; +import java.util.List; + +public class ProceduralShopMenuConfig extends MenusConfigFields { + public static String shopName; + public static ItemStack rerollItem; + public static int rerollSlot; + public static List storeSlots; + public static int minTier, maxTier; + public static String messageFullInventory; + + public ProceduralShopMenuConfig() { + super("procedural_shop_menu", true); + } + + @Override + public void processAdditionalFields() { + shopName = ConfigurationEngine.setString(fileConfiguration, "Shop name", "[EM] Procedural Item Shop"); + ItemStackSerializer.serialize( + "Reroll button", + ItemStackGenerator.generateSkullItemStack("magmaguy", + "&4&lEliteMobs &r&cby &4&lMagmaGuy", + Arrays.asList("&8Support the plugins you enjoy!")), + fileConfiguration); + rerollItem = ItemStackSerializer.deserialize("Reroll button", fileConfiguration); + rerollSlot = ConfigurationEngine.setInt(fileConfiguration, "Reroll button slot", 4); + storeSlots = ConfigurationEngine.setList(fileConfiguration, "Store item slots", Arrays.asList(9, 10, 11, 12, + 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, + 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53)); + minTier = ConfigurationEngine.setInt(fileConfiguration, "Minimum store item tier", 0); + maxTier = ConfigurationEngine.setInt(fileConfiguration, "Maximum store item tier", 5); + messageFullInventory = ConfigurationEngine.setString(fileConfiguration, "Full inventory message", + "&7[EliteMobs] &4Your inventory is full! You can't buy items until you get some free space."); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/menus/premade/QuestMenuConfig.java b/src/main/java/com/magmaguy/elitemobs/config/menus/premade/QuestMenuConfig.java new file mode 100644 index 000000000..75e3bf7ab --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/menus/premade/QuestMenuConfig.java @@ -0,0 +1,68 @@ +package com.magmaguy.elitemobs.config.menus.premade; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.menus.MenusConfigFields; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import com.magmaguy.elitemobs.utils.ItemStackSerializer; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class QuestMenuConfig extends MenusConfigFields { + public static String menuName, questSelectorMenuTitle; + public static ItemStack validTierButton, inactiveTierButton, invalidTierButton; + public static String cancelMessagePart1, cancelMessagePart2, cancelMessagePart3; + public static ItemStack killObjectiveButton; + public static String questCancelMessage, questStartTitle, questStartSubtitle, questCompleteTitle, questCompleteSubtitle, + objectiveString, rewardMessage, questCompleteBroadcastMessage, questStatusMessage, questStartBroadcastMessage; + + public QuestMenuConfig() { + super("quest_menu", true); + } + + @Override + public void processAdditionalFields() { + menuName = ConfigurationEngine.setString(fileConfiguration, "menuName", "[EM] Quest Selection"); + + ItemStackSerializer.serialize( + "validTierButton", + ItemStackGenerator.generateItemStack(Material.GREEN_STAINED_GLASS_PANE, + "&2Take on a $rank &2quest!", + Arrays.asList( + "&aAccept a $rank &aquest and", + "&aget special rewards!")), + fileConfiguration); + validTierButton = ItemStackSerializer.deserialize("validTierButton", fileConfiguration); + + cancelMessagePart1 = ConfigurationEngine.setString(fileConfiguration, "cancelQuestMessage1", + "&c&l&m&o---------------------------------------------" + + "&cYou can only have one quest at a time! Cancelling your ongoing quest will reset quest progress!"); + cancelMessagePart2 = ConfigurationEngine.setString(fileConfiguration, "cancelQuestMessage2", "&2[Click here to cancel current quest!]"); + cancelMessagePart3 = ConfigurationEngine.setString(fileConfiguration, "cancelQuestMessage3", + "&7You can see your quest status with the command &a/em quest status" + + "&c&l&m&o---------------------------------------------"); + + ItemStackSerializer.serialize( + "killObjectiveButton", + ItemStackGenerator.generateItemStack(Material.YELLOW_STAINED_GLASS_PANE, + "&2Kill $objectiveAmount $objectiveName", + Arrays.asList( + "&aKill $objectiveAmount $objectiveName &amobs.", + "&fProgress: &a$currentAmount &f/&c $objectiveAmount", + "&aReward: &e $rewardAmount")), + fileConfiguration); + killObjectiveButton = ItemStackSerializer.deserialize("killObjectiveButton", fileConfiguration); + + questCancelMessage = ConfigurationEngine.setString(fileConfiguration, "questCancelMessage", "&7[EliteMobs] &cYour ongoing quest has been cancelled!"); + questStartTitle = ConfigurationEngine.setString(fileConfiguration, "questStartTitle", "You have accepted a quest!"); + questStartSubtitle = ConfigurationEngine.setString(fileConfiguration, "questStartSubtitle", "Slay $objectiveAmount $objectiveName"); + questCompleteTitle = ConfigurationEngine.setString(fileConfiguration, "questCompleteTitle", "Quest complete!"); + questCompleteSubtitle = ConfigurationEngine.setString(fileConfiguration, "questCompleteSubtitle", "You have slain $objectiveAmount $objectiveName"); + objectiveString = ConfigurationEngine.setString(fileConfiguration, "bossBarObjective", "Slay $objectiveAmount $objectiveName"); + rewardMessage = ConfigurationEngine.setString(fileConfiguration, "questRewardMessage", "&7[EM] &aQuest completed! &6Your reward is &2$reward $currencyName"); + questCompleteBroadcastMessage = ConfigurationEngine.setString(fileConfiguration, "questCompleteBroadcastMessage", "&7[EM] $player &2has completed a $rank &2quest!"); + questStartBroadcastMessage = ConfigurationEngine.setString(fileConfiguration, "questStartBroadcastMessage", "&7[EM] $player &2has accepted a $rank &2quest!"); + questStatusMessage = ConfigurationEngine.setString(fileConfiguration, "questStatusMessage", "&7[EM] &aYou've slain &a$currentAmount &f/ &c$objectiveAmount &a$objectiveName"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/menus/premade/RefinerMenuConfig.java b/src/main/java/com/magmaguy/elitemobs/config/menus/premade/RefinerMenuConfig.java new file mode 100644 index 000000000..986db5576 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/menus/premade/RefinerMenuConfig.java @@ -0,0 +1,88 @@ +package com.magmaguy.elitemobs.config.menus.premade; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.menus.MenusConfigFields; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import com.magmaguy.elitemobs.utils.ItemStackSerializer; +import lombok.Getter; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; +import java.util.List; + +public class RefinerMenuConfig extends MenusConfigFields { + @Getter + private static String shopName; + @Getter + private static ItemStack infoButton; + @Getter + private static ItemStack inputInfoButton; + @Getter + private static ItemStack outputInfoButton; + @Getter + private static int infoSlot; + @Getter + private static int inputInformationSlot; + @Getter + private static int outputInformationSlot; + @Getter + private static List inputSlots; + @Getter + private static List outputSlots; + @Getter + private static ItemStack cancelButton; + @Getter + private static int cancelSlot; + @Getter + private static ItemStack confirmButton; + @Getter + private static int confirmSlot; + + public RefinerMenuConfig() { + super("refiner_menu", true); + } + + @Override + public void processAdditionalFields() { + shopName = ConfigurationEngine.setString(fileConfiguration, "shopName", "[EM] Place 10 scrap!"); + ItemStackSerializer.serialize( + "infoButton", + ItemStackGenerator.generateSkullItemStack("magmaguy", + "&4&lEliteMobs &r&cby &4&lMagmaGuy", + Arrays.asList("&8Support the plugins you enjoy!", + "&aClick on &c10 &ascrap in your inventory", + "&ain order to upgrade it to higher", + "&alevel scrap!")), + fileConfiguration); + infoButton = ItemStackSerializer.deserialize("infoButton", fileConfiguration); + infoSlot = ConfigurationEngine.setInt(fileConfiguration, "infoButtonSlot", 4); + inputInformationSlot = ConfigurationEngine.setInt(fileConfiguration, "informationInputButtonSlot", 11); + inputSlots = ConfigurationEngine.setList(fileConfiguration, "inputSlots", Arrays.asList(19, 20, 21, 28, 29, 30, 37, 38, 39)); + ItemStackSerializer.serialize( + "inputInformationButton", + ItemStackGenerator.generateItemStack(Material.GREEN_BANNER, + "&2Scrap Input slots", + Arrays.asList("&aPut 10 scrap here to upgrade your", + "&ascrap to a &9higher level&a!")), + fileConfiguration); + inputInfoButton = ItemStackSerializer.deserialize("inputInformationButton", fileConfiguration); + outputInformationSlot = ConfigurationEngine.setInt(fileConfiguration, "informationOutputButtonSlot", 15); + outputSlots = ConfigurationEngine.setList(fileConfiguration, "outputSlots", Arrays.asList(23, 24, 25, 32, 33, 34, 41, 42, 43)); + ItemStackSerializer.serialize("cancelButton", ItemStackGenerator.generateItemStack(Material.BARRIER, + "&4Cancel", Arrays.asList("&cCancel upgrade!")), fileConfiguration); + ItemStackSerializer.serialize( + "outputInformationButton", + ItemStackGenerator.generateItemStack(Material.RED_BANNER, + "&2Scrap Output slots", + Arrays.asList("&aPreview what you're crafting here!")), + fileConfiguration); + outputInfoButton = ItemStackSerializer.deserialize("outputInformationButton", fileConfiguration); + cancelButton = ItemStackSerializer.deserialize("cancelButton", fileConfiguration); + cancelSlot = ConfigurationEngine.setInt(fileConfiguration, "cancelButtonSlot", 27); + ItemStackSerializer.serialize("confirmButton", ItemStackGenerator.generateItemStack(Material.EMERALD, + "&2Confirm Scrap", Arrays.asList("&aUpgrade your scrap!")), fileConfiguration); + confirmButton = ItemStackSerializer.deserialize("confirmButton", fileConfiguration); + confirmSlot = ConfigurationEngine.setInt(fileConfiguration, "confirmScrapSlot", 35); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/menus/premade/RepairMenuConfig.java b/src/main/java/com/magmaguy/elitemobs/config/menus/premade/RepairMenuConfig.java new file mode 100644 index 000000000..2baee5479 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/menus/premade/RepairMenuConfig.java @@ -0,0 +1,84 @@ +package com.magmaguy.elitemobs.config.menus.premade; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.menus.MenusConfigFields; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import com.magmaguy.elitemobs.utils.ItemStackSerializer; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class RepairMenuConfig extends MenusConfigFields { + + public static String shopName; + public static ItemStack infoButton; + public static ItemStack eliteItemInputInfoButton; + public static ItemStack eliteScrapInputInfoButton; + public static ItemStack outputInfoButton; + public static int infoSlot; + public static int eliteItemInputInformationSlot; + public static int eliteScrapInputInformationSlot; + public static int outputInformationSlot; + public static int eliteItemInputSlot; + public static int eliteScrapInputSlot; + public static int outputSlot; + public static ItemStack cancelButton; + public static int cancelSlot; + public static ItemStack confirmButton; + public static int confirmSlot; + + public RepairMenuConfig() { + super("repair_menu", true); + } + + @Override + public void processAdditionalFields() { + shopName = ConfigurationEngine.setString(fileConfiguration, "shopName", "[EM] Repair menu!"); + ItemStackSerializer.serialize( + "infoButton", + ItemStackGenerator.generateSkullItemStack("magmaguy", + "&4&lEliteMobs &r&cby &4&lMagmaGuy", + Arrays.asList("&8Support the plugins you enjoy!", + "&aUse scrap to repair elite items!")), + fileConfiguration); + infoButton = ItemStackSerializer.deserialize("infoButton", fileConfiguration); + infoSlot = ConfigurationEngine.setInt(fileConfiguration, "infoButtonSlot", 4); + eliteItemInputInformationSlot = ConfigurationEngine.setInt(fileConfiguration, "eliteItemInputInformationSlot", 20); + eliteItemInputSlot = ConfigurationEngine.setInt(fileConfiguration, "eliteItemInputSlot", 29); + ItemStackSerializer.serialize( + "eliteItemInputInformationButton", + ItemStackGenerator.generateItemStack(Material.GREEN_BANNER, + "&2 Elite Item Input slots", + Arrays.asList("&aThis slot is for your elite item!")), + fileConfiguration); + eliteItemInputInfoButton = ItemStackSerializer.deserialize("eliteItemInputInformationButton", fileConfiguration); + eliteScrapInputInformationSlot = ConfigurationEngine.setInt(fileConfiguration, "eliteScrapInputInformationSlot", 22); + eliteScrapInputSlot = ConfigurationEngine.setInt(fileConfiguration, "eliteScrapInputSlot", 31); + ItemStackSerializer.serialize( + "eliteScrapInputInformationButton", + ItemStackGenerator.generateItemStack(Material.GREEN_BANNER, + "&2Elite Scrap Input slots", + Arrays.asList("&aThis slot is for your elite scrap!")), + fileConfiguration); + eliteScrapInputInfoButton = ItemStackSerializer.deserialize("eliteScrapInputInformationButton", fileConfiguration); + outputInformationSlot = ConfigurationEngine.setInt(fileConfiguration, "informationOutputButtonSlot", 24); + outputSlot = ConfigurationEngine.setInt(fileConfiguration, "outputSlot", 33); + ItemStackSerializer.serialize("cancelButton", ItemStackGenerator.generateItemStack(Material.BARRIER, + "&4Cancel", Arrays.asList("&cCancel repair!")), fileConfiguration); + ItemStackSerializer.serialize( + "outputInformationButton", + ItemStackGenerator.generateItemStack(Material.RED_BANNER, + "&2Output slots", + Arrays.asList("&aThis slot previews the result of your repair!")), + fileConfiguration); + outputInfoButton = ItemStackSerializer.deserialize("outputInformationButton", fileConfiguration); + cancelButton = ItemStackSerializer.deserialize("cancelButton", fileConfiguration); + cancelSlot = ConfigurationEngine.setInt(fileConfiguration, "cancelButtonSlot", 27); + ItemStackSerializer.serialize("confirmButton", ItemStackGenerator.generateItemStack(Material.EMERALD, + "&2Confirm!", Arrays.asList("&aRepair item!")), fileConfiguration); + confirmButton = ItemStackSerializer.deserialize("confirmButton", fileConfiguration); + confirmSlot = ConfigurationEngine.setInt(fileConfiguration, "confirmRepairSlot", 35); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/menus/premade/ScrapperMenuConfig.java b/src/main/java/com/magmaguy/elitemobs/config/menus/premade/ScrapperMenuConfig.java new file mode 100644 index 000000000..a1bd1b469 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/menus/premade/ScrapperMenuConfig.java @@ -0,0 +1,57 @@ +package com.magmaguy.elitemobs.config.menus.premade; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.menus.MenusConfigFields; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import com.magmaguy.elitemobs.utils.ItemStackSerializer; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; +import java.util.List; + +public class ScrapperMenuConfig extends MenusConfigFields { + + public static String shopName; + public static ItemStack infoButton; + public static int infoSlot; + public static List storeSlots; + public static ItemStack cancelButton; + public static int cancelSlot; + public static ItemStack confirmButton; + public static int confirmSlot; + + public ScrapperMenuConfig() { + super("scrapper_menu", true); + } + + @Override + public void processAdditionalFields() { + shopName = ConfigurationEngine.setString(fileConfiguration, "shopName", "[EM] Scrapper"); + ItemStackSerializer.serialize( + "infoButton", + ItemStackGenerator.generateSkullItemStack("magmaguy", + "&4&lEliteMobs &r&cby &4&lMagmaGuy", + Arrays.asList("&8Support the plugins you enjoy!", + "&4Warning!", + "&cItems scrapped here are lost!", + "&cThere is a 50% chance to get", + "&cscrap when scrapping items!", + "&aUse scrap at the smelter,", + "&arepairman and refiner!")), + fileConfiguration); + infoButton = ItemStackSerializer.deserialize("infoButton", fileConfiguration); + infoSlot = ConfigurationEngine.setInt(fileConfiguration, "infoButtonSlot", 4); + storeSlots = ConfigurationEngine.setList(fileConfiguration, "scrapSlots", Arrays.asList(19, 20, 21, 22, 23, + 24, 25, 28, 29, 30, 31, 32, 33, 34, 37, 38, 39, 40, 41, 42, 43)); + ItemStackSerializer.serialize("cancelButton", ItemStackGenerator.generateItemStack(Material.BARRIER, + "&4Cancel", Arrays.asList("&cCancel scrap!")), fileConfiguration); + cancelButton = ItemStackSerializer.deserialize("cancelButton", fileConfiguration); + cancelSlot = ConfigurationEngine.setInt(fileConfiguration, "cancelButtonSlot", 27); + ItemStackSerializer.serialize("confirmButton", ItemStackGenerator.generateItemStack(Material.EMERALD, + "&2Confirm Scrap", Arrays.asList("&aScrap items!", "&a50% chance of success!")), fileConfiguration); + confirmButton = ItemStackSerializer.deserialize("confirmButton", fileConfiguration); + confirmSlot = ConfigurationEngine.setInt(fileConfiguration, "confirmScrapSlot", 35); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/menus/premade/SellMenuConfig.java b/src/main/java/com/magmaguy/elitemobs/config/menus/premade/SellMenuConfig.java new file mode 100644 index 000000000..171e308b7 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/menus/premade/SellMenuConfig.java @@ -0,0 +1,55 @@ +package com.magmaguy.elitemobs.config.menus.premade; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.menus.MenusConfigFields; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import com.magmaguy.elitemobs.utils.ItemStackSerializer; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; +import java.util.List; + +public class SellMenuConfig extends MenusConfigFields { + public static String shopName; + public static ItemStack infoButton; + public static int infoSlot; + public static List storeSlots; + public static ItemStack cancelButton; + public static int cancelSlot; + public static ItemStack confirmButton; + public static int confirmSlot; + + public SellMenuConfig() { + super("sell_menu", true); + } + + @Override + public void processAdditionalFields() { + shopName = ConfigurationEngine.setString(fileConfiguration, "shopName", "[EM] Sell Shop"); + ItemStackSerializer.serialize( + "infoButton", + ItemStackGenerator.generateSkullItemStack("magmaguy", + "&4&lEliteMobs &r&cby &4&lMagmaGuy", + Arrays.asList("&8Support the plugins you enjoy!", + "&4Warning!", + "&cYou can only sell special", + "&cElite Mobs drops in this", + "&cshop! These should have", + "&ca value on their lore.")), + fileConfiguration); + infoButton = ItemStackSerializer.deserialize("infoButton", fileConfiguration); + infoSlot = ConfigurationEngine.setInt(fileConfiguration, "infoButtonSlot", 4); + storeSlots = ConfigurationEngine.setList(fileConfiguration, "sellSlots", Arrays.asList(19, 20, 21, 22, 23, + 24, 25, 28, 29, 30, 31, 32, 33, 34, 37, 38, 39, 40, 41, 42, 43)); + ItemStackSerializer.serialize("cancelButton", ItemStackGenerator.generateItemStack(Material.BARRIER, + "&4Cancel", Arrays.asList("&cCancel purchase!")), fileConfiguration); + cancelButton = ItemStackSerializer.deserialize("cancelButton", fileConfiguration); + cancelSlot = ConfigurationEngine.setInt(fileConfiguration, "cancelButtonSlot", 27); + ItemStackSerializer.serialize("confirmButton", ItemStackGenerator.generateItemStack(Material.EMERALD, + "&2Confirm Sale", Arrays.asList("&aSell item for", "&a$currency_amount $currency_name")), fileConfiguration); + confirmButton = ItemStackSerializer.deserialize("confirmButton", fileConfiguration); + confirmSlot = ConfigurationEngine.setInt(fileConfiguration, "confirmSaleSlot", 35); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/menus/premade/SmeltMenuConfig.java b/src/main/java/com/magmaguy/elitemobs/config/menus/premade/SmeltMenuConfig.java new file mode 100644 index 000000000..e9b1cc490 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/menus/premade/SmeltMenuConfig.java @@ -0,0 +1,74 @@ +package com.magmaguy.elitemobs.config.menus.premade; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.menus.MenusConfigFields; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import com.magmaguy.elitemobs.utils.ItemStackSerializer; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; +import java.util.List; + +public class SmeltMenuConfig extends MenusConfigFields { + + public static String shopName; + public static ItemStack infoButton; + public static ItemStack inputInfoButton; + public static ItemStack outputInfoButton; + public static int infoSlot; + public static int inputInformationSlot; + public static int outputInformationSlot; + public static List inputSlots; + public static List outputSlots; + public static ItemStack cancelButton; + public static int cancelSlot; + public static ItemStack confirmButton; + public static int confirmSlot; + + public SmeltMenuConfig() { + super("smelt_menu", true); + } + + @Override + public void processAdditionalFields() { + shopName = ConfigurationEngine.setString(fileConfiguration, "shopName", "[EM] Place 25 scrap!"); + ItemStackSerializer.serialize( + "infoButton", + ItemStackGenerator.generateSkullItemStack("magmaguy", + "&4&lEliteMobs &r&cby &4&lMagmaGuy", + Arrays.asList("&8Support the plugins you enjoy!", + "&aClick on &c25 &ascrap in your inventory", + "&ain order to craft item upgrade orbs!")), + fileConfiguration); + infoButton = ItemStackSerializer.deserialize("infoButton", fileConfiguration); + infoSlot = ConfigurationEngine.setInt(fileConfiguration, "infoButtonSlot", 4); + inputInformationSlot = ConfigurationEngine.setInt(fileConfiguration, "informationInputButtonSlot", 11); + inputSlots = ConfigurationEngine.setList(fileConfiguration, "inputSlots", Arrays.asList(19, 20, 21, 28, 29, 30, 37, 38, 39)); + ItemStackSerializer.serialize( + "inputInformationButton", + ItemStackGenerator.generateItemStack(Material.GREEN_BANNER, + "&2Scrap Input slots", + Arrays.asList("&aPut &c25 &ascrap of the same level", "&ahere in order to craft an Item Upgrade Orb!")), + fileConfiguration); + inputInfoButton = ItemStackSerializer.deserialize("inputInformationButton", fileConfiguration); + outputInformationSlot = ConfigurationEngine.setInt(fileConfiguration, "informationOutputButtonSlot", 15); + outputSlots = ConfigurationEngine.setList(fileConfiguration, "outputSlots", Arrays.asList(23, 24, 25, 32, 33, 34, 41, 42, 43)); + ItemStackSerializer.serialize("cancelButton", ItemStackGenerator.generateItemStack(Material.BARRIER, + "&4Cancel", Arrays.asList("&cCancel craft!")), fileConfiguration); + ItemStackSerializer.serialize( + "outputInformationButton", + ItemStackGenerator.generateItemStack(Material.RED_BANNER, + "&2Elite Orb Output slots", + Arrays.asList("&aPreview what you're crafting here!")), + fileConfiguration); + outputInfoButton = ItemStackSerializer.deserialize("outputInformationButton", fileConfiguration); + cancelButton = ItemStackSerializer.deserialize("cancelButton", fileConfiguration); + cancelSlot = ConfigurationEngine.setInt(fileConfiguration, "cancelButtonSlot", 27); + ItemStackSerializer.serialize("confirmButton", ItemStackGenerator.generateItemStack(Material.EMERALD, + "&2Confirm Craft", Arrays.asList("&aCraft Item Upgrade Orbs!")), fileConfiguration); + confirmButton = ItemStackSerializer.deserialize("confirmButton", fileConfiguration); + confirmSlot = ConfigurationEngine.setInt(fileConfiguration, "confirmScrapSlot", 35); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/menus/premade/UnbinderMenuConfig.java b/src/main/java/com/magmaguy/elitemobs/config/menus/premade/UnbinderMenuConfig.java new file mode 100644 index 000000000..ca25006cf --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/menus/premade/UnbinderMenuConfig.java @@ -0,0 +1,100 @@ +package com.magmaguy.elitemobs.config.menus.premade; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.menus.MenusConfigFields; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import com.magmaguy.elitemobs.utils.ItemStackSerializer; +import lombok.Getter; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; + +import java.util.Arrays; + +public class UnbinderMenuConfig extends MenusConfigFields { + + @Getter + private static String shopName; + @Getter + private static ItemStack infoButton; + @Getter + private static ItemStack eliteItemInputInfoButton; + @Getter + private static ItemStack eliteUnbindInputInfoButton; + @Getter + private static ItemStack outputInfoButton; + @Getter + private static int infoSlot; + @Getter + private static int eliteItemInputInformationSlot; + @Getter + private static int eliteScrapInputInformationSlot; + @Getter + private static int outputInformationSlot; + @Getter + private static int eliteItemInputSlot; + @Getter + private static int eliteUnbindInputSlot; + @Getter + private static int outputSlot; + @Getter + private static ItemStack cancelButton; + @Getter + private static int cancelSlot; + @Getter + private static ItemStack confirmButton; + @Getter + private static int confirmSlot; + + public UnbinderMenuConfig() { + super("unbind_menu", true); + } + + @Override + public void processAdditionalFields() { + shopName = ConfigurationEngine.setString(fileConfiguration, "shopName", "[EM] Unbind menu!"); + ItemStackSerializer.serialize( + "infoButton", + ItemStackGenerator.generateSkullItemStack("magmaguy", + "&4&lEliteMobs &r&cby &4&lMagmaGuy", + Arrays.asList("&8Support the plugins you enjoy!", + "&aUse an &5Unbind Scroll &ato remove Soulbind from an item!")), + fileConfiguration); + infoButton = ItemStackSerializer.deserialize("infoButton", fileConfiguration); + infoSlot = ConfigurationEngine.setInt(fileConfiguration, "infoButtonSlot", 4); + eliteItemInputInformationSlot = ConfigurationEngine.setInt(fileConfiguration, "eliteItemInputInformationSlot", 20); + eliteItemInputSlot = ConfigurationEngine.setInt(fileConfiguration, "eliteItemInputSlot", 29); + ItemStackSerializer.serialize( + "eliteItemInputInformationButton", + ItemStackGenerator.generateItemStack(Material.GREEN_BANNER, + "&2Elite Item Input slots", + Arrays.asList("&aThis slot is for your elite item!")), + fileConfiguration); + eliteItemInputInfoButton = ItemStackSerializer.deserialize("eliteItemInputInformationButton", fileConfiguration); + eliteScrapInputInformationSlot = ConfigurationEngine.setInt(fileConfiguration, "unbindScrollInputInformationSlot", 22); + eliteUnbindInputSlot = ConfigurationEngine.setInt(fileConfiguration, "unbindScrollInputSlot", 31); + ItemStackSerializer.serialize( + "unbindScrollInputInformationButton", + ItemStackGenerator.generateItemStack(Material.GREEN_BANNER, + "&5Unbind Scroll &aInput slots", + Arrays.asList("&aThis slot is for your &9Unbind Scroll&a!")), + fileConfiguration); + eliteUnbindInputInfoButton = ItemStackSerializer.deserialize("unbindScrollInputInformationButton", fileConfiguration); + outputInformationSlot = ConfigurationEngine.setInt(fileConfiguration, "informationOutputButtonSlot", 24); + outputSlot = ConfigurationEngine.setInt(fileConfiguration, "outputSlot", 33); + ItemStackSerializer.serialize("cancelButton", ItemStackGenerator.generateItemStack(Material.BARRIER, + "&4Cancel", Arrays.asList("&cCancel unbind!")), fileConfiguration); + ItemStackSerializer.serialize( + "outputInformationButton", + ItemStackGenerator.generateItemStack(Material.RED_BANNER, + "&2Unbound Item Output slot", + Arrays.asList("&aThis slot previews the result of your unbind!")), + fileConfiguration); + outputInfoButton = ItemStackSerializer.deserialize("outputInformationButton", fileConfiguration); + cancelButton = ItemStackSerializer.deserialize("cancelButton", fileConfiguration); + cancelSlot = ConfigurationEngine.setInt(fileConfiguration, "cancelButtonSlot", 27); + ItemStackSerializer.serialize("confirmButton", ItemStackGenerator.generateItemStack(Material.EMERALD, + "&2Confirm!", Arrays.asList("&aUnbind item!")), fileConfiguration); + confirmButton = ItemStackSerializer.deserialize("confirmButton", fileConfiguration); + confirmSlot = ConfigurationEngine.setInt(fileConfiguration, "confirmUnbindSlot", 35); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/MobPropertiesConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/MobPropertiesConfig.java new file mode 100644 index 000000000..c10ebb510 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/MobPropertiesConfig.java @@ -0,0 +1,103 @@ +package com.magmaguy.elitemobs.config.mobproperties; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.mobproperties.premade.*; +import com.magmaguy.elitemobs.utils.VersionChecker; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.EntityType; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; + +public class MobPropertiesConfig { + + private static final HashMap mobProperties = new HashMap<>(); + private static final ArrayList mobPropertiesConfigFieldsList = new ArrayList(Arrays.asList( + new EliteBlazeConfig(), + new EliteCaveSpiderConfig(), + new EliteCreeperConfig(), + new EliteDrownedConfig(), + new EliteElderGuardianConfig(), + new EliteGuardianConfig(), + new EliteEndermanConfig(), + new EliteEndermiteConfig(), + new EliteEvokerConfig(), + new EliteHuskConfig(), + new EliteIllusionerConfig(), + new EliteIronGolemConfig(), + new ElitePhantomConfig(), + new ElitePillagerConfig(), + new ElitePolarBearConfig(), + new EliteRavagerConfig(), + new EliteSilverfishConfig(), + new EliteSkeletonConfig(), + new EliteSpiderConfig(), + new EliteStrayConfig(), + new EliteVexConfig(), + new EliteVindicatorConfig(), + new EliteWitchConfig(), + new EliteWitherSkeletonConfig(), + new EliteZombieConfig(), + new EliteGhastConfig(), + new EliteWolfConfig(), + new EliteEnderDragon(), + new EliteShulkerConfig(), + new SuperChickenConfig(), + new SuperCowConfig(), + new SuperMushroomCowConfig(), + new SuperPigConfig(), + new SuperSheepConfig(), + new EliteKillerBunnyConfig(), + new EliteLlamaConfig() + )); + + public static HashMap getMobProperties() { + return mobProperties; + } + + public static void addMobProperties(EntityType entityType, MobPropertiesConfigFields mobPropertiesConfigFields) { + mobProperties.put(entityType, mobPropertiesConfigFields); + } + + public static void initializeConfigs() { + if (!VersionChecker.serverVersionOlderThan(17, 0)) { + mobPropertiesConfigFieldsList.add(new EliteGoatConfig()); + } + + if (!VersionChecker.serverVersionOlderThan(16, 0)) { + mobPropertiesConfigFieldsList.add(new EliteZombiefiedPiglin()); + mobPropertiesConfigFieldsList.add(new EliteZoglinConfig()); + mobPropertiesConfigFieldsList.add(new ElitePiglinConfig()); + mobPropertiesConfigFieldsList.add(new EliteHoglinConfig()); + } + + if (!VersionChecker.serverVersionOlderThan(16, 2)) + mobPropertiesConfigFieldsList.add(new ElitePiglinBruteConfig()); + + if (!VersionChecker.serverVersionOlderThan(15, 0)) + mobPropertiesConfigFieldsList.add(new EliteBeeConfig()); + + for (MobPropertiesConfigFields mobPropertiesConfigFields : mobPropertiesConfigFieldsList) + initializeConfiguration(mobPropertiesConfigFields); + + } + + /** + * Initializes a single instance of a premade configuration using the default values. + */ + private static FileConfiguration initializeConfiguration(MobPropertiesConfigFields mobPropertiesConfigFields) { + + File file = ConfigurationEngine.fileCreator("mobproperties", mobPropertiesConfigFields.getFileName()); + FileConfiguration fileConfiguration = ConfigurationEngine.fileConfigurationCreator(file); + mobPropertiesConfigFields.generateConfigDefaults(fileConfiguration); + ConfigurationEngine.fileSaverOnlyDefaults(fileConfiguration, file); + + addMobProperties(mobPropertiesConfigFields.getEntityType(), new MobPropertiesConfigFields(fileConfiguration, file)); + + return fileConfiguration; + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/MobPropertiesConfigFields.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/MobPropertiesConfigFields.java new file mode 100644 index 000000000..5a87d936f --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/MobPropertiesConfigFields.java @@ -0,0 +1,74 @@ +package com.magmaguy.elitemobs.config.mobproperties; + +import com.magmaguy.elitemobs.ChatColorConverter; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.EntityType; + +import java.io.File; +import java.util.List; + +public class MobPropertiesConfigFields { + + private final String fileName; + private final EntityType entityType; + private final boolean isEnabled; + private final String name; + private final List deathMessages; + private final double baseDamage; + + public MobPropertiesConfigFields(String fileName, + EntityType entityType, + boolean isEnabled, + String name, + List deathMessages, + double baseDamage) { + this.fileName = fileName + ".yml"; + this.entityType = entityType; + this.isEnabled = isEnabled; + this.name = name; + this.deathMessages = deathMessages; + this.baseDamage = baseDamage; + } + + public MobPropertiesConfigFields(FileConfiguration configuration, File file) { + this.fileName = file.getName(); + this.entityType = EntityType.valueOf(configuration.getString("entityType")); + this.isEnabled = configuration.getBoolean("isEnabled"); + this.name = configuration.getString("name"); + this.deathMessages = configuration.getStringList("deathMessages"); + this.baseDamage = configuration.getDouble("baseDamage"); + } + + public void generateConfigDefaults(FileConfiguration fileConfiguration) { + fileConfiguration.addDefault("isEnabled", isEnabled); + fileConfiguration.addDefault("entityType", entityType.toString()); + fileConfiguration.addDefault("name", name); + fileConfiguration.addDefault("deathMessages", deathMessages); + fileConfiguration.addDefault("baseDamage", baseDamage); + } + + public String getFileName() { + return fileName; + } + + public EntityType getEntityType() { + return entityType; + } + + public boolean isEnabled() { + return isEnabled; + } + + public String getName() { + return ChatColorConverter.convert(name); + } + + public List getDeathMessages() { + return deathMessages; + } + + public double getBaseDamage() { + return this.baseDamage; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteBeeConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteBeeConfig.java new file mode 100644 index 000000000..f0a470253 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteBeeConfig.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class EliteBeeConfig extends MobPropertiesConfigFields { + public EliteBeeConfig() { + super("elite_bee", + EntityType.BEE, + true, + "&fLvl &2$level &fElite &eBee", + Arrays.asList("$player &cwas stung by $entity!"), + 3); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteBlazeConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteBlazeConfig.java new file mode 100644 index 000000000..8e949e3c6 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteBlazeConfig.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class EliteBlazeConfig extends MobPropertiesConfigFields { + public EliteBlazeConfig() { + super("elite_blaze", + EntityType.BLAZE, + true, + "&fLvl &2$level &fElite &eBlaze", + Arrays.asList("$player &cwas lit ablaze by $entity!"), + 9); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteCaveSpiderConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteCaveSpiderConfig.java new file mode 100644 index 000000000..a5082216f --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteCaveSpiderConfig.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class EliteCaveSpiderConfig extends MobPropertiesConfigFields { + public EliteCaveSpiderConfig() { + super("elite_cave_spider", + EntityType.CAVE_SPIDER, + true, + "&fLvl &2$level &fElite &3Cave Spider", + Arrays.asList("$player &cbecame entangled in $entity's &cweb!"), + 3); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteCreeperConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteCreeperConfig.java new file mode 100644 index 000000000..ddf6dc52b --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteCreeperConfig.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class EliteCreeperConfig extends MobPropertiesConfigFields { + public EliteCreeperConfig() { + super("elite_creeper", + EntityType.CREEPER, + true, + "&fLvl &2$level &fElite &2Creeper", + Arrays.asList("$player &cwas blasted away by $entity!", + "$entity &cjust oh man'd $player&c!"), + 73); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteDrownedConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteDrownedConfig.java new file mode 100644 index 000000000..19c805ba9 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteDrownedConfig.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class EliteDrownedConfig extends MobPropertiesConfigFields { + public EliteDrownedConfig() { + super("elite_drowned", + EntityType.DROWNED, + true, + "&fLvl &2$level &fElite &3Drowned", + Arrays.asList("$player &chas been brought down to the depths by $entity!", + "$player &chas been drowned by $entity!"), + 4); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteElderGuardianConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteElderGuardianConfig.java new file mode 100644 index 000000000..d358240b9 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteElderGuardianConfig.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class EliteElderGuardianConfig extends MobPropertiesConfigFields { + public EliteElderGuardianConfig() { + super("elite_elder_guardian", + EntityType.ELDER_GUARDIAN, + true, + "&fLvl &2$level &fElite &3Elder Guardian", + Arrays.asList("$entity &cprevented $player &cfrom exploring the depths!"), + 12); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteEnderDragon.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteEnderDragon.java new file mode 100644 index 000000000..80d32eb79 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteEnderDragon.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class EliteEnderDragon extends MobPropertiesConfigFields { + public EliteEnderDragon() { + super("elite_ender_dragon", + EntityType.ENDER_DRAGON, + true, + "&fLvl &2$level &fElite &5Ender Dragon", + Arrays.asList("$entity &chas ended $player!"), + 7); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteEndermanConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteEndermanConfig.java new file mode 100644 index 000000000..379718b35 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteEndermanConfig.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class EliteEndermanConfig extends MobPropertiesConfigFields { + public EliteEndermanConfig() { + super("elite_enderman", + EntityType.ENDERMAN, + true, + "&fLvl &2$level &fElite &5Enderman", + Arrays.asList("$entity &csent $player &cinto the void!", + "$player &clooked at $entity &cwrong!", + "$player &cand $entity &cbecame best friends!"), + 10); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteEndermiteConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteEndermiteConfig.java new file mode 100644 index 000000000..c8d4aa021 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteEndermiteConfig.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class EliteEndermiteConfig extends MobPropertiesConfigFields { + public EliteEndermiteConfig() { + super("elitemob_endermite", + EntityType.ENDERMITE, + true, + "&fLvl &2$level &fElite &7Endermite", + Arrays.asList("$entity &cis to $player &cwhat David is to Goliath!"), + 3); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteEvokerConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteEvokerConfig.java new file mode 100644 index 000000000..3535b4671 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteEvokerConfig.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class EliteEvokerConfig extends MobPropertiesConfigFields { + public EliteEvokerConfig() { + super("elite_evoker", + EntityType.EVOKER, + true, + "&fLvl &2$level &fElite &5Evoker", + Arrays.asList("$player &cwas enchanted by $entity&c!"), + 9); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteGhastConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteGhastConfig.java new file mode 100644 index 000000000..aba75ff2b --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteGhastConfig.java @@ -0,0 +1,20 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class EliteGhastConfig extends MobPropertiesConfigFields { + public EliteGhastConfig() { + super("elite_ghast", + EntityType.GHAST, + true, + "&fLvl &2$level &fElite &fGhast", + Arrays.asList("$player &cdidn't dodge $entity&c &cfireballs!", + "$player &cwas blown to bits $entity&c!", + "$entity &cgot $player's &cbacon!"), + 25); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteGoatConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteGoatConfig.java new file mode 100644 index 000000000..c77faa9fc --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteGoatConfig.java @@ -0,0 +1,20 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class EliteGoatConfig extends MobPropertiesConfigFields { + public EliteGoatConfig() { + super("elite_goat", + EntityType.GOAT, + true, + "&fLvl &2$level &fElite &5Goat", + Arrays.asList("$player &cwas rammed by $entity&c!", + "$player &cwas run over by $entity&c!", + "$player &cwas trampled by $entity&c!", + "$player &cgot $entity&c horns!"), + 3); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteGuardianConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteGuardianConfig.java new file mode 100644 index 000000000..a9c1052ac --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteGuardianConfig.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class EliteGuardianConfig extends MobPropertiesConfigFields { + public EliteGuardianConfig() { + super("elite_guardian", + EntityType.GUARDIAN, + true, + "&fLvl &2$level &fElite &3Guardian", + Arrays.asList("$entity &cprevented $player &cfrom exploring the depths!"), + 9); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteHoglinConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteHoglinConfig.java new file mode 100644 index 000000000..a7a01d08e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteHoglinConfig.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class EliteHoglinConfig extends MobPropertiesConfigFields { + public EliteHoglinConfig() { + super("elite_hoglin", + EntityType.HOGLIN, + true, + "&fLvl &2$level &fElite &dHoglin", + Arrays.asList("$player &cmessed with the $entity &cand got the horns!", + "$entity &cgot $player's &cbacon!"), + 8); + } +} \ No newline at end of file diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteHuskConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteHuskConfig.java new file mode 100644 index 000000000..977ffa438 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteHuskConfig.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class EliteHuskConfig extends MobPropertiesConfigFields { + public EliteHuskConfig() { + super("elite_husk", + EntityType.HUSK, + true, + "&fLvl &2$level &fElite &7Husk", + Arrays.asList("$player &cwas hollowed out by $entity&c!"), + 5); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteIllusionerConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteIllusionerConfig.java new file mode 100644 index 000000000..1c00fd04a --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteIllusionerConfig.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class EliteIllusionerConfig extends MobPropertiesConfigFields { + public EliteIllusionerConfig() { + super("elite_illusioner", + EntityType.ILLUSIONER, + true, + "&fLvl &2$level &fElite &8Illusioner", + Arrays.asList("$player&c fell for $entity's &cillusions!"), + 5); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteIronGolemConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteIronGolemConfig.java new file mode 100644 index 000000000..f7adf0a7c --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteIronGolemConfig.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class EliteIronGolemConfig extends MobPropertiesConfigFields { + public EliteIronGolemConfig() { + super("elite_iron_golem", + EntityType.IRON_GOLEM, + true, + "&fLvl &2$level &fElite &fIron Golem", + Arrays.asList("$player &cmessed with the wrong $entity&c!", + "$player &chas been taught the way of fist by $entity&c!"), + 15); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteKillerBunnyConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteKillerBunnyConfig.java new file mode 100644 index 000000000..7185f8a64 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteKillerBunnyConfig.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class EliteKillerBunnyConfig extends MobPropertiesConfigFields { + public EliteKillerBunnyConfig() { + super("elite_killer_bunny", + EntityType.RABBIT, + true, + "&fLvl &2$level &fElite &cKiller Rabbit", + Arrays.asList("$entity &cmade $player &cgo live in a farm upstate!", + "$entity &ceducated $player using a stick and not a carrot!"), + 12); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteLlamaConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteLlamaConfig.java new file mode 100644 index 000000000..098986abd --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteLlamaConfig.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class EliteLlamaConfig extends MobPropertiesConfigFields { + public EliteLlamaConfig() { + super("elite_llama", + EntityType.LLAMA, + true, + "&fLvl &2$level &fElite &5Llama", + Arrays.asList("$player &cwas spit on by $entity&c!", + "$player &cwas made $entity&c angry!"), + 1); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/ElitePhantomConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/ElitePhantomConfig.java new file mode 100644 index 000000000..6616f5d86 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/ElitePhantomConfig.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class ElitePhantomConfig extends MobPropertiesConfigFields { + public ElitePhantomConfig() { + super("elite_phantom", + EntityType.PHANTOM, + true, + "&fLvl &2$level &fElite &9Phantom", + Arrays.asList("$player &cjust had a bad nightmare about $entity&c!", + "$player &cwill be having nightmares about $entity&c!", + "$entity &chas taught $player &cthe value of sleep!"), + 9); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/ElitePiglinBruteConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/ElitePiglinBruteConfig.java new file mode 100644 index 000000000..42536bdc1 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/ElitePiglinBruteConfig.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class ElitePiglinBruteConfig extends MobPropertiesConfigFields { + public ElitePiglinBruteConfig() { + super("elite_piglin_brute", + EntityType.PIGLIN_BRUTE, + true, + "&fLvl &2$level &fElite &cPiglin Brute", + Arrays.asList("$entity &ctenderized $player!", + "$entity &cbrutalized $player!"), + 19.5); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/ElitePiglinConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/ElitePiglinConfig.java new file mode 100644 index 000000000..a5d0e69bb --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/ElitePiglinConfig.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class ElitePiglinConfig extends MobPropertiesConfigFields { + public ElitePiglinConfig() { + super("elite_piglin", + EntityType.PIGLIN, + true, + "&fLvl &2$level &fElite &ePiglin", + Arrays.asList("$entity &cwill fetch a good price for $player's remains!", + "$entity &ctaught $player &cthe value of gold!"), + 13); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/ElitePillagerConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/ElitePillagerConfig.java new file mode 100644 index 000000000..c7b7a5b82 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/ElitePillagerConfig.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class ElitePillagerConfig extends MobPropertiesConfigFields { + public ElitePillagerConfig() { + super("elite_pillager", + EntityType.PILLAGER, + true, + "&fLvl &2$level &fElite &8Pillager", + Arrays.asList("$entity &cplundered $player&c!", + "$entity &cpillaged $player&c!"), + 5); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/ElitePolarBearConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/ElitePolarBearConfig.java new file mode 100644 index 000000000..da031bb3a --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/ElitePolarBearConfig.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class ElitePolarBearConfig extends MobPropertiesConfigFields { + public ElitePolarBearConfig() { + super("elite_polar_bear", + EntityType.POLAR_BEAR, + true, + "&fLvl &2$level &fElite &fPolar Bear", + Arrays.asList("$player &cwas clawed to death by $entity&c!", + "$player &cwas mauled to death by $entity&c!"), + 9); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteRavagerConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteRavagerConfig.java new file mode 100644 index 000000000..b27d2d065 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteRavagerConfig.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class EliteRavagerConfig extends MobPropertiesConfigFields { + public EliteRavagerConfig() { + super("elite_ravager", + EntityType.RAVAGER, + true, + "&fLvl &2$level &fElite &6Ravager", + Arrays.asList("$entity &cshowed $player &cwho's in charge!"), + 18); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteShulkerConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteShulkerConfig.java new file mode 100644 index 000000000..74f14056a --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteShulkerConfig.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class EliteShulkerConfig extends MobPropertiesConfigFields { + public EliteShulkerConfig() { + super("elite_shulker", + EntityType.SHULKER, + true, + "&fLvl &2$level &fElite &5Shulker", + Arrays.asList("$entity &cshowed $player &cnew heights!"), + 4); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteSilverfishConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteSilverfishConfig.java new file mode 100644 index 000000000..93ea8874d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteSilverfishConfig.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class EliteSilverfishConfig extends MobPropertiesConfigFields { + public EliteSilverfishConfig() { + super("elite_silverfish", + EntityType.SILVERFISH, + true, + "&fLvl &2$level &fElite &7Silverfish", + Arrays.asList("$player &cmistook $entity &cfor a stone block!"), + 1); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteSkeletonConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteSkeletonConfig.java new file mode 100644 index 000000000..82ef52003 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteSkeletonConfig.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class EliteSkeletonConfig extends MobPropertiesConfigFields { + public EliteSkeletonConfig() { + super("elite_skeleton", + EntityType.SKELETON, + true, + "&fLvl &2$level &fElite &fSkeleton", + Arrays.asList("$player &cbecame $entity's &cpin cushion!", + "$entity &cwanted to see $player's &cbones!"), + 5); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteSpiderConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteSpiderConfig.java new file mode 100644 index 000000000..1d73f6bff --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteSpiderConfig.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class EliteSpiderConfig extends MobPropertiesConfigFields { + public EliteSpiderConfig() { + super("elite_spider", + EntityType.SPIDER, + true, + "&fLvl &2$level &fElite &7Spider", + Arrays.asList("$player &cbecame entangled in $entity's &cweb!", + "$entity &chas devoured $player&c!"), + 3); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteStrayConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteStrayConfig.java new file mode 100644 index 000000000..697fb39a5 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteStrayConfig.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class EliteStrayConfig extends MobPropertiesConfigFields { + public EliteStrayConfig() { + super("elite_stray", + EntityType.STRAY, + true, + "&fLvl &2$level &fElite &bStray", + Arrays.asList("$player &cwas led astray by $entity&c!"), + 5); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteVexConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteVexConfig.java new file mode 100644 index 000000000..b1889e86e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteVexConfig.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class EliteVexConfig extends MobPropertiesConfigFields { + public EliteVexConfig() { + super("elite_vex", + EntityType.VEX, + true, + "&fLvl &2$level &fElite &bVex", + Arrays.asList("$entity &chas vexed $player&c!"), + 13); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteVindicatorConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteVindicatorConfig.java new file mode 100644 index 000000000..5913eb6bb --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteVindicatorConfig.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class EliteVindicatorConfig extends MobPropertiesConfigFields { + public EliteVindicatorConfig() { + super("elite_vindicator", + EntityType.VINDICATOR, + true, + "&fLvl &2$level &fElite &8Vindicator", + Arrays.asList("$entity &cvindicated his fighting skills over $player&c!"), + 19.5); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteWitchConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteWitchConfig.java new file mode 100644 index 000000000..bac58a188 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteWitchConfig.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class EliteWitchConfig extends MobPropertiesConfigFields { + public EliteWitchConfig() { + super("elite_witch", + EntityType.WITCH, + true, + "&fLvl &2$level &fElite &5Witch", + Arrays.asList("$player &cbecame $entity's &ctest subject!", + "$player &chas been bewitched by $entity&c!"), + 6); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteWitherSkeletonConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteWitherSkeletonConfig.java new file mode 100644 index 000000000..22c0ea741 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteWitherSkeletonConfig.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class EliteWitherSkeletonConfig extends MobPropertiesConfigFields { + public EliteWitherSkeletonConfig() { + super("elite_wither_skeleton", + EntityType.WITHER_SKELETON, + true, + "&fLvl &2$level &fElite &8Wither Skeleton", + Arrays.asList("$entity's &carrows withered away $player&c!", + "$entity's &chas withered $player &caway!"), + 12); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteWolfConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteWolfConfig.java new file mode 100644 index 000000000..d641f529e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteWolfConfig.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class EliteWolfConfig extends MobPropertiesConfigFields { + public EliteWolfConfig() { + super("elite_wolf", + EntityType.WOLF, + true, + "[$level] Elite Wolf", + Arrays.asList("$entity tore $player apart!", + "$player was torn to shreds by $entity!"), + 6); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteZoglinConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteZoglinConfig.java new file mode 100644 index 000000000..e575075fa --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteZoglinConfig.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class EliteZoglinConfig extends MobPropertiesConfigFields { + public EliteZoglinConfig() { + super("elite_zoglin", + EntityType.ZOGLIN, + true, + "&fLvl &2$level &fElite &dZoglin", + Arrays.asList("$player &cmessed with the $entity &cand got the horns!", + "$entity &cgot $player's &cbacon!"), + 12); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteZombieConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteZombieConfig.java new file mode 100644 index 000000000..7c93e3097 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteZombieConfig.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class EliteZombieConfig extends MobPropertiesConfigFields { + public EliteZombieConfig() { + super("elite_zombie", + EntityType.ZOMBIE, + true, + "&fLvl &2$level &fElite &2Zombie", + Arrays.asList("$player &cwas devoured by $entity&c!", + "$entity &cgot to $player's &cbrains!"), + 5); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteZombiefiedPiglin.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteZombiefiedPiglin.java new file mode 100644 index 000000000..506a121f3 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/EliteZombiefiedPiglin.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +import java.util.Arrays; + +public class EliteZombiefiedPiglin extends MobPropertiesConfigFields { + public EliteZombiefiedPiglin() { + super("elite_zombified_piglin", + EntityType.ZOMBIFIED_PIGLIN, + true, + "&fLvl &2$level &fElite &6Zombified Piglin", + Arrays.asList("$player &cwas mobbed to death by $entity&c!", + "$entity &cgot $player's &cbacon!"), + 12); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/SuperChickenConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/SuperChickenConfig.java new file mode 100644 index 000000000..3dd9d8643 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/SuperChickenConfig.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +public class SuperChickenConfig extends MobPropertiesConfigFields { + public SuperChickenConfig() { + super("super_chicken", + EntityType.CHICKEN, + true, + "&2Super Chicken", + null, + 0); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/SuperCowConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/SuperCowConfig.java new file mode 100644 index 000000000..39beffeb9 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/SuperCowConfig.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +public class SuperCowConfig extends MobPropertiesConfigFields { + public SuperCowConfig() { + super("super_cow", + EntityType.COW, + true, + "&2Super Cow", + null, + 0); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/SuperMushroomCowConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/SuperMushroomCowConfig.java new file mode 100644 index 000000000..ca1d3df67 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/SuperMushroomCowConfig.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +public class SuperMushroomCowConfig extends MobPropertiesConfigFields { + public SuperMushroomCowConfig() { + super("super_mushroom_cow", + EntityType.MUSHROOM_COW, + true, + "&2Super Mooshroom Cow", + null, + 0); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/SuperPigConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/SuperPigConfig.java new file mode 100644 index 000000000..458e3a5c3 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/SuperPigConfig.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +public class SuperPigConfig extends MobPropertiesConfigFields { + public SuperPigConfig() { + super("super_pig", + EntityType.PIG, + true, + "&dSuper Pig", + null, + 0); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/SuperSheepConfig.java b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/SuperSheepConfig.java new file mode 100644 index 000000000..abc72b8fd --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/mobproperties/premade/SuperSheepConfig.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.config.mobproperties.premade; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfigFields; +import org.bukkit.entity.EntityType; + +public class SuperSheepConfig extends MobPropertiesConfigFields { + public SuperSheepConfig() { + super("super_sheep", + EntityType.SHEEP, + true, + "Super Sheep", + null, + 0); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/npcs/NPCsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/npcs/NPCsConfig.java new file mode 100644 index 000000000..7d66fa7d0 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/npcs/NPCsConfig.java @@ -0,0 +1,26 @@ +package com.magmaguy.elitemobs.config.npcs; + +import com.magmaguy.elitemobs.config.CustomConfig; +import com.magmaguy.elitemobs.npcs.NPCEntity; + +import java.util.HashMap; + +public class NPCsConfig extends CustomConfig { + + public static HashMap npcEntities; + + public NPCsConfig() { + super("npcs", "com.magmaguy.elitemobs.config.npcs.premade", NPCsConfigFields.class); + npcEntities = new HashMap<>(); + for (String key : super.getCustomConfigFieldsHashMap().keySet()) { + npcEntities.put(key, (NPCsConfigFields) super.getCustomConfigFieldsHashMap().get(key)); + //Initializes NPC entities + new NPCEntity((NPCsConfigFields) super.getCustomConfigFieldsHashMap().get(key)); + } + } + + public static HashMap getNpcEntities() { + return npcEntities; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/npcs/NPCsConfigFields.java b/src/main/java/com/magmaguy/elitemobs/config/npcs/NPCsConfigFields.java new file mode 100644 index 000000000..7515b9681 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/npcs/NPCsConfigFields.java @@ -0,0 +1,143 @@ +package com.magmaguy.elitemobs.config.npcs; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.CustomConfigFields; +import com.magmaguy.elitemobs.config.CustomConfigFieldsInterface; +import com.magmaguy.elitemobs.npcs.NPCInteractions; +import lombok.Getter; +import lombok.Setter; +import org.bukkit.Bukkit; +import org.bukkit.entity.Villager; + +import java.util.ArrayList; +import java.util.List; + +public class NPCsConfigFields extends CustomConfigFields implements CustomConfigFieldsInterface { + + @Getter + @Setter + public String noPreviousLocationMessage; + @Getter + @Setter + private String name = ""; + @Getter + @Setter + private String role = ""; + @Getter + @Setter + private Villager.Profession profession = Villager.Profession.NITWIT; + @Getter + private String location; + @Getter + @Setter + private List greetings = new ArrayList<>(); + @Getter + @Setter + private List dialog = new ArrayList<>(); + @Getter + @Setter + private List farewell = new ArrayList<>(); + @Getter + @Setter + private boolean canTalk = true; + @Getter + @Setter + private double activationRadius = 3; + @Getter + @Setter + private NPCInteractions.NPCInteractionType interactionType = NPCInteractions.NPCInteractionType.NONE; + @Getter + @Setter + private double timeout = 0; + @Getter + @Setter + private List questFilenames = null; + /** + * Integration with LibsDisguises. Only used if that plugin is loaded. + */ + @Getter + @Setter + private String disguise = null; + @Getter + @Setter + private String customDisguiseData = null; + @Getter + @Setter + private String customModel = null; + @Getter + @Setter + private String arenaFilename; + + public NPCsConfigFields(String fileName, + boolean isEnabled, + String name, + String role, + Villager.Profession profession, + String location, + List greetings, + List dialog, + List farewell, + boolean canTalk, + double activationRadius, + NPCInteractions.NPCInteractionType interactionType) { + super(fileName, isEnabled); + this.name = name; + this.role = role; + this.profession = profession; + this.location = location; + this.greetings = greetings; + this.dialog = dialog; + this.farewell = farewell; + this.canTalk = canTalk; + this.activationRadius = activationRadius; + this.interactionType = interactionType; + } + + public NPCsConfigFields(String filename, + boolean isEnabled) { + super(filename, isEnabled); + } + + public void setLocation(String location) { + this.location = location; + this.fileConfiguration.set("spawnLocation", location); + try { + ConfigurationEngine.fileSaverCustomValues(fileConfiguration, this.file); + } catch (Exception ex) { + Bukkit.getLogger().warning("[EliteMobs] Attempted to update the location status for an NPC with no config file! Did you delete it during runtime?"); + } + } + + @Override + public void processConfigFields() { + this.isEnabled = processBoolean("isEnabled", isEnabled, true, true); + this.name = processString("name", name, "", true); + this.role = processString("role", role, "", true); + this.profession = processEnum("profession", profession, Villager.Profession.NITWIT, Villager.Profession.class, true); + this.location = processString("spawnLocation", location, null, true); + this.greetings = processStringList("greetings", greetings, new ArrayList<>(), true); + this.dialog = processStringList("dialog", dialog, new ArrayList<>(), true); + this.farewell = processStringList("farewell", farewell, new ArrayList<>(), true); + this.canTalk = processBoolean("canTalk", canTalk, true, true); + this.activationRadius = processDouble("activationRadius", activationRadius, 3, true); + this.interactionType = processEnum("interactionType", interactionType, NPCInteractions.NPCInteractionType.NONE, NPCInteractions.NPCInteractionType.class, true); + this.timeout = processDouble("timeout", timeout, 0, false); + this.noPreviousLocationMessage = processString("noPreviousLocationMessage", noPreviousLocationMessage, "", false); + this.questFilenames = processStringList("questFileName", questFilenames, new ArrayList<>(), false); + this.disguise = processString("disguise", disguise, null, false); + this.customDisguiseData = processString("customDisguiseData", customDisguiseData, null, false); + this.customModel = processString("customModel", customModel, null, false); + this.arenaFilename = processString("arena", arenaFilename, null, false); + } + + public void setEnabled(boolean enabled) { + this.isEnabled = enabled; + this.fileConfiguration.set("isEnabled", enabled); + try { + ConfigurationEngine.fileSaverCustomValues(this.fileConfiguration, this.file); + } catch (Exception e) { + Bukkit.getLogger().warning("[EliteMobs] Attempted to update the enabled status for an NPC with no config file! Did you delete it during runtime?"); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/BackTeleporter.java b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/BackTeleporter.java new file mode 100644 index 000000000..39332b8f9 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/BackTeleporter.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.npcs.premade; + +import com.magmaguy.elitemobs.config.npcs.NPCsConfigFields; +import com.magmaguy.elitemobs.npcs.NPCInteractions; +import org.bukkit.entity.Villager; + +import java.util.Arrays; + +public class BackTeleporter extends NPCsConfigFields { + public BackTeleporter() { + super("back_teleporter", + true, + "Hermes", + "", + Villager.Profession.FLETCHER, + "em_adventurers_guild,213.5,88,232,0,0", + Arrays.asList("Welcome to the\\nAdventurer's Guild Hub!"), + Arrays.asList("Need to go back?"), + Arrays.asList("Safe travels, friend."), + true, + 3, + NPCInteractions.NPCInteractionType.TELEPORT_BACK); + setNoPreviousLocationMessage("&8[EliteMobs] &cCouldn't send you back to your previous location - no previous location found!"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/BarkeepConfig.java b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/BarkeepConfig.java new file mode 100644 index 000000000..2e0e0155e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/BarkeepConfig.java @@ -0,0 +1,44 @@ +package com.magmaguy.elitemobs.config.npcs.premade; + +import com.magmaguy.elitemobs.config.npcs.NPCsConfigFields; +import com.magmaguy.elitemobs.npcs.NPCInteractions; +import org.bukkit.entity.Villager; + +import java.util.Arrays; + +public class BarkeepConfig extends NPCsConfigFields { + public BarkeepConfig() { + super("barkeep", + true, + "Bartley", + "", + Villager.Profession.BUTCHER, + "em_adventurers_guild,285.5,91,209.5,0,0", + Arrays.asList( + "Need a drink?", + "Want a drink", + "Thirsty?", + "Howdy, partner."), + Arrays.asList( + "Have one of our house specialties.", + "Special drinks won't find them\\nanywhere else.", + "One taste and will keep you\\ncoming back from more."), + Arrays.asList( + "Come back anytime", + "Bottoms up!", + "Kampai!", + "Salut!", + "Brosd!", + "Salud!", + "À la vôtre !", + "Prost!", + "Santi!", + "Salute!", + "Saúde!", + "Cheers!", + "乾杯!"), + true, + 3, + NPCInteractions.NPCInteractionType.BAR); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/BlacksmithConfig.java b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/BlacksmithConfig.java new file mode 100644 index 000000000..c7fafa685 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/BlacksmithConfig.java @@ -0,0 +1,44 @@ +package com.magmaguy.elitemobs.config.npcs.premade; + +import com.magmaguy.elitemobs.config.npcs.NPCsConfigFields; +import com.magmaguy.elitemobs.npcs.NPCInteractions; +import org.bukkit.entity.Villager; + +import java.util.Arrays; + +public class BlacksmithConfig extends NPCsConfigFields { + public BlacksmithConfig() { + super("blacksmith", + true, + "Greg", + "", + Villager.Profession.TOOLSMITH, + "em_adventurers_guild,285.5,93,261.5,179,0", + Arrays.asList( + "Welcome to our shop!", + "Sell your goods here!", + "Fresh goods, just for you!", + "Got something to sell?", + "Want to buy something good?", + "Fresh goods every time!"), + Arrays.asList( + "Higher level mobs drop\\nhigher value items!", + "Items with lots of \\nenchantments are worth more!", + "Higher level mobs drop\\nbetter items!", + "Higher level mobs have\\na higher chance of dropping loot!", + "Elite mobs are attracted to\\ngood armor, the better the\\narmor the higher their level!", + "Some items have special\\npotion effects!", + "Some items have unique\\neffects!", + "The hunter enchantment\\nattracts elite mobs to your\\nlocation!", + "Special weapons and armor\\ndropped by elite mobs can\\nbe sold here!", + "Higher guild ranks will\\nincrease the quality of the\\nloot from elite mobs!"), + Arrays.asList( + "Thank you for your business!", + "Come back soon!", + "Come back any time!", + "Recommend this shop to your\\nfriends!"), + true, + 3, + NPCInteractions.NPCInteractionType.PROCEDURALLY_GENERATED_SHOP); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/CombatInstructorConfig.java b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/CombatInstructorConfig.java new file mode 100644 index 000000000..b6583315f --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/CombatInstructorConfig.java @@ -0,0 +1,63 @@ +package com.magmaguy.elitemobs.config.npcs.premade; + +import com.magmaguy.elitemobs.config.npcs.NPCsConfigFields; +import com.magmaguy.elitemobs.npcs.NPCInteractions; +import org.bukkit.entity.Villager; + +import java.util.Arrays; + +public class CombatInstructorConfig extends NPCsConfigFields { + public CombatInstructorConfig() { + super("combat_instructor", + true, + "Charles", + "", + Villager.Profession.NITWIT, + "em_adventurers_guild,277.41,90.0,286.23,-214.85,-1.95", + Arrays.asList( + "Want to learn about combat?", + "Need a combat lesson?", + "Want to know more about combat?", + "Ready to fight Elite Mobs?"), + Arrays.asList( + "The items around Elite Mobs\\nshow what powers they have.", + "The higher the level of\\nthe Elite Mob, the\\nmore powers they can have", + "The higher the level of\\nthe Elite Mob, the\\nbetter the loot they can drop", + "Higher level Elite Mobs\\nhave higher chances\\nof dropping special items", + "Elite Mobs with floating\\narrows fire arrows at\\nnearby players", + "Elite Mobs with floating\\nender eyes blind you\\nwhen they hit you", + "Elite Mobs with floating\\nspell particles confuse you\\nwhen they hit you", + "Elite Mobs with floating\\nlava buckets set you on fire\\nwhen they hit you", + "Elite Mobs with floating\\nfireballs fire fireballs\nat nearby players", + "Elite Mobs with floating\\npacked ice freeze you\\nwhen they hit you", + "Elite Mobs with floating\\nelytras make you float\\nwhen they hit you", + "Elite Mobs with floating\\nemeralds poison you\\nwhen they hit you", + "Elite Mobs with floating\\npistons push you\\nwhen they hit you", + "Elite Mobs with floating\\ntotems weaken you\\nwhen they hit you", + "Elite Mobs with floating\\nwebs web you\\nwhen they hit you", + "Elite Mobs with floating\\nskulls wither you\\nwhen they hit you", + "Elite Mobs with floating\\nchests drop bonus loot\\nwhen you kill them", + "Elite Mobs with floating\\ngold boots are faster", + "Elite Mobs with floating\\njukeboxes taunt you\\nduring combat", + "Elite Mobs with floating\\nglass panes are invisible", + "Elite Mobs with floating\\nspectral arrows are immune\\nto arrows", + "Elite Mobs with floating\\nfeathers are immune\\nto fall damage", + "Elite Mobs with floating\\nflames are immune\\nto fire", + "Elite Mobs with floating\\nanvils are heavier\\nthan usual", + "Elite Mobs with floating\\nbone blocks leave their\\ncorpses behind when killed", + "Elite Mobs with floating\\nslime blocks jump higher\\nthan usual", + "Elite Mobs with floating\\nslime balls create a vaccum\\nupon death", + "Elite Mobs with floating\\nleads pull you\\nwhen they hit you", + "Elite Mobs with floating\\nbones create bone pillars\\nduring combat", + "Elite Mobs with floating\\ntipped arrows fire tracking\\narrows during combat", + "Elite Mobs with floating\\nmushrooms bloat up to become giants\\nwhen hit", + "Elite Mobs with floating\\nskulls summon reinforcements\\nwhen hit", + "Elite Mobs with floating\\nbooks summon reinforcements\\nuntil you kill the summoner", + "Elite Mobs with floating\\neggs summon reinforcements\\nwhen hit", + "Elite Mobs with floating\\nfireworks summon Team Rocket\\nwhen hit"), + null, + true, + 3, + NPCInteractions.NPCInteractionType.CHAT); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/EnhancerConfig.java b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/EnhancerConfig.java new file mode 100644 index 000000000..81c125631 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/EnhancerConfig.java @@ -0,0 +1,37 @@ +package com.magmaguy.elitemobs.config.npcs.premade; + +import com.magmaguy.elitemobs.config.npcs.NPCsConfigFields; +import com.magmaguy.elitemobs.npcs.NPCInteractions; +import org.bukkit.entity.Villager; + +import java.util.Arrays; + +public class EnhancerConfig extends NPCsConfigFields { + public EnhancerConfig() { + super("enhancer_config", + true, + "Tim", + "", + Villager.Profession.WEAPONSMITH, + "em_adventurers_guild,282.5,77,242.5,0,0", + Arrays.asList( + "Want to uprade yer items?", + "Got upgrade orbs?", + "Get yer items upgraded here!", + "Ahoy!", + "Ye got scrap son?"), + Arrays.asList( + "Yer items are lousy,\\n get an upgrade here!", + "Upgrade yer items here!", + "Ye got an upgrade orb?", + "That sword looks awful,\\nget it upgraded here!", + "Need an upgrade?"), + Arrays.asList( + "Don't embarrass yourself out there!", + "Come back when you have more orbs!", + "Go get more orbs!"), + true, + 3, + NPCInteractions.NPCInteractionType.ENHANCER); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/Guide0Config.java b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/Guide0Config.java new file mode 100644 index 000000000..184ec7de9 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/Guide0Config.java @@ -0,0 +1,38 @@ +package com.magmaguy.elitemobs.config.npcs.premade; + +import com.magmaguy.elitemobs.config.npcs.NPCsConfigFields; +import com.magmaguy.elitemobs.npcs.NPCInteractions; +import org.bukkit.entity.Villager; + +import java.util.Arrays; +import java.util.Collections; + +public class Guide0Config extends NPCsConfigFields { + public Guide0Config() { + super("guide_0.yml", + true, + "Dux", + "", + Villager.Profession.NITWIT, + "null", + Arrays.asList( + "Heard about the AG?", + "Been to the AG?", + "Heard of the Adventurer's Guild?", + "Know about the Adventurer's Guild?"), + Arrays.asList( + "Heard about the AG?", + "Been to the AG?", + "Heard of the Adventurer's Guild?", + "Know about the Adventurer's Guild?"), + Arrays.asList( + "Come back anytime", + "I'll be here if you need me!", + "I'll be around!", + "See you later!"), + true, + 5, + NPCInteractions.NPCInteractionType.CUSTOM_QUEST_GIVER); + super.setQuestFilenames(Collections.singletonList("ag_welcome_quest_0.yml")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/Guide1Config.java b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/Guide1Config.java new file mode 100644 index 000000000..309149c7b --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/Guide1Config.java @@ -0,0 +1,37 @@ +package com.magmaguy.elitemobs.config.npcs.premade; + +import com.magmaguy.elitemobs.config.npcs.NPCsConfigFields; +import com.magmaguy.elitemobs.npcs.NPCInteractions; +import org.bukkit.entity.Villager; + +import java.util.Arrays; +import java.util.Collections; + +public class Guide1Config extends NPCsConfigFields { + public Guide1Config() { + super("guide_1.yml", + true, + "Casus", + "", + Villager.Profession.NITWIT, + "em_adventurers_guild,215.5,87,239.5,131,0", + Arrays.asList( + "Need guidance?", + "Need a hint", + "Are you lost?", + "Need help?"), + Arrays.asList( + "I know everything about\\nthis place!", + "Want to meet the other members\\nof the Adventurer's Guild?", + "Need to learn your way around\\nthis place?"), + Arrays.asList( + "Come back anytime", + "I'll be here if you need me!", + "I'll be around!", + "See you later!"), + true, + 5, + NPCInteractions.NPCInteractionType.CUSTOM_QUEST_GIVER); + super.setQuestFilenames(Collections.singletonList("ag_welcome_quest_1.yml")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/GuildAttendantConfig.java b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/GuildAttendantConfig.java new file mode 100644 index 000000000..cd6d8d248 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/GuildAttendantConfig.java @@ -0,0 +1,36 @@ +package com.magmaguy.elitemobs.config.npcs.premade; + +import com.magmaguy.elitemobs.config.npcs.NPCsConfigFields; +import com.magmaguy.elitemobs.npcs.NPCInteractions; +import org.bukkit.entity.Villager; + +import java.util.Arrays; + +public class GuildAttendantConfig extends NPCsConfigFields { + public GuildAttendantConfig() { + super("guild_attendant", + true, + "Gillian", + "", + Villager.Profession.LIBRARIAN, + "em_adventurers_guild,283.5,91,229.5,179,0", + Arrays.asList( + "Welcome to the\\nAdventurer's Guild!", + "Welcome!"), + Arrays.asList( + "Check the questboard to\\nsee active quests!", + "You can talk to me to\\nchange your guild rank!", + "You can sell items to the\\nblacksmith for coins!", + "You can talk to the arena\\nmaster to take the arena on!", + "You can buy equipment from\\nthe blacksmith!", + "You can talk to the combat\\nmaster to check your combat level!", + "Unlocking new guid tiers\\nincreases your maximum health!"), + Arrays.asList( + "See you soon!", + "Thanks for stopping by!", + "Happy hunting!"), + true, + 3, + NPCInteractions.NPCInteractionType.GUILD_GREETER); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/QuestGiverConfig.java b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/QuestGiverConfig.java new file mode 100644 index 000000000..ce60e7077 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/QuestGiverConfig.java @@ -0,0 +1,39 @@ +package com.magmaguy.elitemobs.config.npcs.premade; + +import com.magmaguy.elitemobs.config.npcs.NPCsConfigFields; +import com.magmaguy.elitemobs.npcs.NPCInteractions; +import org.bukkit.entity.Villager; + +import java.util.Arrays; + +public class QuestGiverConfig extends NPCsConfigFields { + public QuestGiverConfig() { + super("quest_giver", + true, + "Qel'Thuzad", + "", + Villager.Profession.FLETCHER, + "em_adventurers_guild,278.5,91,215.5,0,0", + Arrays.asList( + "Greetings, adventurer!\\nFancy a quest?", + "You! I've got a quest!", + "Feeling... adventurous?"), + Arrays.asList( + "Complete guild quests\\nfor cool rewards!", + "Higher tier quests have\\nbetter rewards!", + "Higher tier quests make\\nyou hunt higher level mobs!", + "Want a harder challenge?\\nIncrease your guild rank!", + "Make sure you're well equipped\\nfor these quests!"), + Arrays.asList( + "Safe travels, friend.", + "Happy hunting!", + "Live long and prosper!", + "Come back with your shield,\\n or on it.", + "Life before death!", + "Strength before weakness!", + "Journey before destination!"), + true, + 3, + NPCInteractions.NPCInteractionType.QUEST_GIVER); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/RefinerConfig.java b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/RefinerConfig.java new file mode 100644 index 000000000..7aa3fd328 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/RefinerConfig.java @@ -0,0 +1,37 @@ +package com.magmaguy.elitemobs.config.npcs.premade; + +import com.magmaguy.elitemobs.config.npcs.NPCsConfigFields; +import com.magmaguy.elitemobs.npcs.NPCInteractions; +import org.bukkit.entity.Villager; + +import java.util.Arrays; + +public class RefinerConfig extends NPCsConfigFields { + public RefinerConfig() { + super("refiner_config", + true, + "Ralph", + "", + Villager.Profession.WEAPONSMITH, + "em_adventurers_guild,292.5,81,269.5,90,0", + Arrays.asList( + "Want to uprade your scrap?", + "Got scrap?", + "Looking for low level scrap!", + "Greetings, got scrap?", + "I'll recycle your scrap!"), + Arrays.asList( + "Need your scrap upgraded?", + "Upgrade your scrap here!", + "Upgrade 10 scrap to a higher level!", + "Make your scrap more useful!", + "Got low level scrap?"), + Arrays.asList( + "Come back when you have\\nmore to low level scrap", + "Don't forget to make that\\nscrap useful!", + "Go get into a scrap!"), + true, + 3, + NPCInteractions.NPCInteractionType.REFINER); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/RepairmanConfig.java b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/RepairmanConfig.java new file mode 100644 index 000000000..62f1e3d2c --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/RepairmanConfig.java @@ -0,0 +1,37 @@ +package com.magmaguy.elitemobs.config.npcs.premade; + +import com.magmaguy.elitemobs.config.npcs.NPCsConfigFields; +import com.magmaguy.elitemobs.npcs.NPCInteractions; +import org.bukkit.entity.Villager; + +import java.util.Arrays; + +public class RepairmanConfig extends NPCsConfigFields { + public RepairmanConfig() { + super("repairman_config", + true, + "Reggie", + "", + Villager.Profession.WEAPONSMITH, + "em_adventurers_guild,278.5,81,263.5,-90,0", + Arrays.asList( + "Get your items repaired!", + "Repairing items for scrap!", + "Turn that scrap into durability!", + "Need a repair?", + "Got damaged items?"), + Arrays.asList( + "Best repairs in town!", + "I got your fix!", + "Need a fix?", + "I'll repair your items!", + "Need elite items repaired?"), + Arrays.asList( + "Don't forget to do maintenance!", + "I'll be here if you need me!", + "Call me beep me if you wanna reach me,\\nif you wanna page me that's ok"), + true, + 3, + NPCInteractions.NPCInteractionType.REPAIRMAN); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/SantaConfig.java b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/SantaConfig.java new file mode 100644 index 000000000..563bad3da --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/SantaConfig.java @@ -0,0 +1,46 @@ +package com.magmaguy.elitemobs.config.npcs.premade; + +import com.magmaguy.elitemobs.config.npcs.NPCsConfigFields; +import com.magmaguy.elitemobs.npcs.NPCInteractions; +import org.bukkit.entity.Villager; + +import java.util.Arrays; +import java.util.Collections; + +public class SantaConfig extends NPCsConfigFields { + public SantaConfig() { + super("santa.yml", + false, + "&4Saint Nick", + "&c", + Villager.Profession.NITWIT, + "em_adventurers_guild,212.5,88,236.5,104,0", + Arrays.asList( + "Ho ho ho!"), + Arrays.asList( + "I have lost some presents, \\ncan you help me?", + "Dear traveller, I have\\na request for you!", + "Can you help an old man\\nin his time of need?"), + Arrays.asList( + "Ho ho ho!"), + true, + 5, + NPCInteractions.NPCInteractionType.CUSTOM_QUEST_GIVER); + super.setQuestFilenames(Collections.singletonList("xmas_quest_0.yml")); + super.setDisguise("custom:elitemobs_saint_nick_skin"); + super.setCustomDisguiseData("player elitemobs_saint_nick_skin setskin " + + "{\"id\":\"017f3d21-319d-48ab-b6b0-1084ca56c078\",\"name\":\"Unknown\",\"properties\":[{\"name\":\"" + + "textures\",\"value\":\"ewogICJ0aW1lc3RhbXAiIDogMTY0MDAzNzk0Nzg2MywKICAicHJvZmlsZUlkIiA6ICJjNjEwOTExMDh" + + "lOTQ0MWRhODQyZDA5MDVmMDAyOWVhOCIsCiAgInByb2ZpbGVOYW1lIiA6ICJkZVlvbm8iLAogICJzaWduYXR1cmVSZXF1aXJlZCIgOi" + + "B0cnVlLAogICJ0ZXh0dXJlcyIgOiB7CiAgICAiU0tJTiIgOiB7CiAgICAgICJ1cmwiIDogImh0dHA6Ly90ZXh0dXJlcy5taW5lY3JhZ" + + "nQubmV0L3RleHR1cmUvYThjNWMwZThhZmZkNTgyY2FiNjdhMGI1OGMyMDVkZjNjMGJhYTUwMzIxMDI3ZjZiY2FmYWQ2YjNjNDM4ZDMx" + + "NiIKICAgIH0KICB9Cn0=\",\"signature\":\"TvI5R8ftaZKTBAl5t6ON2aWbApJ5tQKN8caWuy3f/NJ0MFSk6PRiFzEfFIMHxLICJ" + + "D5sAQm8NhSGHCWMecLQtPJSoK9u3SSjSxr6wIHCD+AYFNeWAGRZP1swYq8E87nGslChlVB/1++MIpWAudM3HI5qxO3lzs9hDgLXRIEr" + + "MTolyqltAJXCyJbuho60+z8qRZaVx6NKiIB9bGwYYsDzAraPgn/bXd15nHW0hkal6adXBp45nRcGuD2iUp1X9tC1OBtTcAsjkhZjgki" + + "sw9b5gR0TFQpdvzezJbJCHKMIb0xAkRCIMaxnt2VSZ8eXGzg6wpTV8PXCRRNN0TXe/Bhodh/T8R7IUts6rz+6aYUCco4dCMDbfqWIFz" + + "NQ6JfFUPPXM5WhzmU0e/T05NYEKcP8dKAywC1OUPOT2MUNkS0IIXcQdwcdPxT2/YgWGUKKwaDcTcMqBVwbDhAvEl8xG8N8Wsm54YYy0" + + "McrnoogQZQ7VOMVZJDfeZmbA45fkHp5kSCJ5g9txgR4mRMmVz9mTxzyYUtTTrloey4EqOxJb8Rg/3S6QXGwIdMY+V7yptXAijm0T8qU" + + "VIWWcNlo7GeeSQ3VUI4L2EOk0xbiQMWMWDFwMcbKBrd6OHuyRbCe6CIZFLGjQDAM1xo/I4reRaagneM57rUTg/4xgGHWRhX1oFmZxGE=" + + "\"}],\"legacy\":false}"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/ScrapperConfig.java b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/ScrapperConfig.java new file mode 100644 index 000000000..921b6a00c --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/ScrapperConfig.java @@ -0,0 +1,37 @@ +package com.magmaguy.elitemobs.config.npcs.premade; + +import com.magmaguy.elitemobs.config.npcs.NPCsConfigFields; +import com.magmaguy.elitemobs.npcs.NPCInteractions; +import org.bukkit.entity.Villager; + +import java.util.Arrays; + +public class ScrapperConfig extends NPCsConfigFields { + public ScrapperConfig() { + super("scrapper_config", + true, + "Kelly", + "", + Villager.Profession.WEAPONSMITH, + "em_adventurers_guild,292.5,81,263.5,90,0", + Arrays.asList( + "Want to get rid of items?", + "Need to recycle items?", + "Looking to scrap?", + "It's scrap 'o clock!", + "Scrap time!"), + Arrays.asList( + "Scrappy deals!", + "Get your scrap here!", + "75% chance to work!", + "There are no refunds.", + "Recycle, reuse, reduce!"), + Arrays.asList( + "Come back when you have\\nmore to scrap", + "Don't forget to make that\\nscrap useful!", + "Happy scrapping!"), + true, + 3, + NPCInteractions.NPCInteractionType.SCRAPPER); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/SmelterConfig.java b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/SmelterConfig.java new file mode 100644 index 000000000..b703da241 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/SmelterConfig.java @@ -0,0 +1,34 @@ +package com.magmaguy.elitemobs.config.npcs.premade; + +import com.magmaguy.elitemobs.config.npcs.NPCsConfigFields; +import com.magmaguy.elitemobs.npcs.NPCInteractions; +import org.bukkit.entity.Villager; + +import java.util.Arrays; + +public class SmelterConfig extends NPCsConfigFields { + public SmelterConfig() { + super("smelter", + true, + "Sam", + "", + Villager.Profession.WEAPONSMITH, + "em_adventurers_guild,276.5,77,243.5,0,0", + Arrays.asList( + "Got scrap?", + "Got extra scrap?", + "I smell scrap on you!?", + "Please I need scrap!", + "Feed me scrap!"), + Arrays.asList( + "I'll make your scrap useful!", + "Give me scrap and I'll\\ngive you upgrade orbs!", + "Scrap is useless, give it to me!"), + Arrays.asList( + "Come back when you have\\nmore scrap", + "Off to the upgrader you go!"), + true, + 3, + NPCInteractions.NPCInteractionType.SMELTER); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/SpecialBlacksmithConfig.java b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/SpecialBlacksmithConfig.java new file mode 100644 index 000000000..1d251967b --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/SpecialBlacksmithConfig.java @@ -0,0 +1,39 @@ +package com.magmaguy.elitemobs.config.npcs.premade; + +import com.magmaguy.elitemobs.config.npcs.NPCsConfigFields; +import com.magmaguy.elitemobs.npcs.NPCInteractions; +import org.bukkit.entity.Villager; + +import java.util.Arrays; + +public class SpecialBlacksmithConfig extends NPCsConfigFields { + public SpecialBlacksmithConfig() { + super("special_blacksmith", + true, + "Grog", + "", + Villager.Profession.WEAPONSMITH, + "em_adventurers_guild,282.5,93,258.5,-90,0", + Arrays.asList( + "Need something?", + "Got anything good?", + "We have nothing but the best", + "Got anything worth selling?", + "We only buy elite mob gear."), + Arrays.asList( + "We buy low and sell high.", + "No refunds.", + "Absolutely no refunds.", + "There are no refunds.", + "No taksies backsies.", + "Shop purchases are final."), + Arrays.asList( + "Come back when you have\\nmore to spend", + "Don't get yourself killed,\\nwe want you to bring us\\nmore gear.", + "Next time buy something \\nmore expensive.", + "Don't forget, no refunds."), + true, + 3, + NPCInteractions.NPCInteractionType.CUSTOM_SHOP); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/TestNPCConfig.java b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/TestNPCConfig.java new file mode 100644 index 000000000..3e3155b5b --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/TestNPCConfig.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.npcs.premade; + +import com.magmaguy.elitemobs.config.npcs.NPCsConfigFields; +import com.magmaguy.elitemobs.npcs.NPCInteractions; +import org.bukkit.entity.Villager; + +import java.util.Arrays; + +public class TestNPCConfig extends NPCsConfigFields { + public TestNPCConfig() { + super("test_npc", + true, + "Test NPC", + "Testing!", + Villager.Profession.NITWIT, + null, + Arrays.asList("Test Greeting!"), + Arrays.asList("Test Dialog!"), + Arrays.asList("Test Farewell!"), + true, + 3, + NPCInteractions.NPCInteractionType.CUSTOM_QUEST_GIVER); + super.setQuestFilenames(Arrays.asList("test_quest.yml")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/TravellingMerchantConfig.java b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/TravellingMerchantConfig.java new file mode 100644 index 000000000..c495b3085 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/TravellingMerchantConfig.java @@ -0,0 +1,36 @@ +package com.magmaguy.elitemobs.config.npcs.premade; + +import com.magmaguy.elitemobs.config.npcs.NPCsConfigFields; +import com.magmaguy.elitemobs.npcs.NPCInteractions; +import org.bukkit.entity.Villager; + +import java.util.Arrays; + +public class TravellingMerchantConfig extends NPCsConfigFields { + public TravellingMerchantConfig() { + super("travelling_merchant", + true, + "Jeeves", + "", + Villager.Profession.LIBRARIAN, + null, + Arrays.asList( + "Got something to sell?", + "You called?", + "Huh?"), + Arrays.asList( + "I'll buy it on the cheap!", + "Got something for me?", + "Time is money!"), + Arrays.asList( + "Call me again anytime!", + "Was that all?", + "Safe travels!", + "Don't get yourself killed!", + "Good hunting!"), + true, + 3, + NPCInteractions.NPCInteractionType.SELL); + setTimeout(2); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/UnbinderConfig.java b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/UnbinderConfig.java new file mode 100644 index 000000000..3bf3b80fe --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/UnbinderConfig.java @@ -0,0 +1,34 @@ +package com.magmaguy.elitemobs.config.npcs.premade; + +import com.magmaguy.elitemobs.config.npcs.NPCsConfigFields; +import com.magmaguy.elitemobs.npcs.NPCInteractions; +import org.bukkit.entity.Villager; + +import java.util.Arrays; + +public class UnbinderConfig extends NPCsConfigFields { + public UnbinderConfig() { + super("unbinder", + true, + "Ulfric", + "", + Villager.Profession.WEAPONSMITH, + "em_adventurers_guild,296.5,81,253.5,90,0", + Arrays.asList( + "Greetings.", + "Well met.", + "Hail, friend.", + "Yes?", + "May I help you?"), + Arrays.asList( + "I will unbind your items\\nfor an extremely rare unbind scroll.", + "I am the only one qualified\\nto unbind your goods.", + "Have an unbind scroll?"), + Arrays.asList( + "Remember: Use unbind\\nscrolls wisely.", + "Safe travels, friend."), + true, + 3, + NPCInteractions.NPCInteractionType.UNBINDER); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/WoodLeagueArenaMasterConfig.java b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/WoodLeagueArenaMasterConfig.java new file mode 100644 index 000000000..8f69aa86d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/npcs/premade/WoodLeagueArenaMasterConfig.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.config.npcs.premade; + +import com.magmaguy.elitemobs.config.npcs.NPCsConfigFields; +import com.magmaguy.elitemobs.npcs.NPCInteractions; +import org.bukkit.entity.Villager; + +import java.util.Arrays; + +public class WoodLeagueArenaMasterConfig extends NPCsConfigFields { + public WoodLeagueArenaMasterConfig() { + super("wood_league_arena_master", + true, + "Gladius", + "", + Villager.Profession.ARMORER, + "em_adventurers_guild,240.5,92,270,-108,0", + Arrays.asList("Welcome to the\\nArena!"), + Arrays.asList("Prepared to face the arena?"), + Arrays.asList("Return with your shield, or on it!"), + true, + 3, + NPCInteractions.NPCInteractionType.ARENA_MASTER); + setArenaFilename("wood_league.yml"); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/potioneffects/PotionEffectsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/PotionEffectsConfig.java new file mode 100644 index 000000000..daf9b7de7 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/PotionEffectsConfig.java @@ -0,0 +1,79 @@ +package com.magmaguy.elitemobs.config.potioneffects; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.potioneffects.premade.*; +import org.bukkit.configuration.file.FileConfiguration; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; + +public class PotionEffectsConfig { + + private static final HashMap potionEffects = new HashMap(); + private static final List potionEffectsConfigFields = new ArrayList<>(Arrays.asList( + new AbsorptionConfig(), + new BlindnessConfig(), + new ConduitPowerConfig(), + new ConfusionConfig(), + new DamageResistanceConfig(), + new DolphinsGraceConfig(), + new FastDiggingConfig(), + new FireResistanceConfig(), + new GlowingConfig(), + new HarmConfig(), + new HealConfig(), + new HealthBoostConfig(), + new HungerConfig(), + new IncreaseDamageConfig(), + new InvisibilityConfig(), + new JumpConfig(), + new LevitationConfig(), + new LuckConfig(), + new NightVisionConfig(), + new PoisonConfig(), + new RegenerationConfig(), + new SaturationConfig(), + new SlowConfig(), + new SlowDiggingConfig(), + new SlowFallingConfig(), + new SpeedConfig(), + new UnluckConfig(), + new WaterBreathingConfig(), + new WeaknessConfig(), + new WitherConfig() + )); + + public static void addPotionEffect(String fileName, PotionEffectsConfigFields powersConfigFields) { + potionEffects.put(fileName, powersConfigFields); + } + + public static PotionEffectsConfigFields getPotionEffect(String fileName) { + fileName = fileName.toLowerCase(); + if (!fileName.contains(".yml")) + fileName += ".yml"; + return potionEffects.get(fileName); + } + + public static void initializeConfigs() { + for (PotionEffectsConfigFields powersConfigFields : potionEffectsConfigFields) + initializeConfiguration(powersConfigFields); + } + + /** + * Initializes a single instance of a premade configuration using the default values. + */ + private static FileConfiguration initializeConfiguration(PotionEffectsConfigFields potionEffectsConfigFields) { + + File file = ConfigurationEngine.fileCreator("potionEffects", potionEffectsConfigFields.getFileName()); + FileConfiguration fileConfiguration = ConfigurationEngine.fileConfigurationCreator(file); + potionEffectsConfigFields.generateConfigDefaults(fileConfiguration); + ConfigurationEngine.fileSaverOnlyDefaults(fileConfiguration, file); + addPotionEffect(file.getName(), new PotionEffectsConfigFields(fileConfiguration, file)); + return fileConfiguration; + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/potioneffects/PotionEffectsConfigFields.java b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/PotionEffectsConfigFields.java new file mode 100644 index 000000000..658b33cb6 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/PotionEffectsConfigFields.java @@ -0,0 +1,83 @@ +package com.magmaguy.elitemobs.config.potioneffects; + +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.potion.PotionEffectType; + +import java.io.File; +import java.util.HashMap; +import java.util.Map; + +public class PotionEffectsConfigFields { + + private final String fileName; + private final boolean isEnabled; + private final String name; + private final int onHitDuration; + private final double value; + private final HashMap additionalConfigOptions = new HashMap<>(); + private PotionEffectType potionEffectType; + private FileConfiguration configuration; + + public PotionEffectsConfigFields(String fileName, + boolean isEnabled, + String name, + int onHitDuration, + double value) { + this.fileName = fileName + ".yml"; + this.isEnabled = isEnabled; + this.name = name; + this.onHitDuration = onHitDuration; + this.value = value; + } + + public PotionEffectsConfigFields(FileConfiguration fileConfiguration, File file) { + this.fileName = file.getName(); + this.isEnabled = fileConfiguration.getBoolean("isEnabled"); + this.name = fileConfiguration.getString("name"); + this.onHitDuration = fileConfiguration.getInt("onHitDuration"); + this.value = fileConfiguration.getDouble("value"); + this.potionEffectType = PotionEffectType.getByName(this.fileName.toUpperCase()); + this.configuration = fileConfiguration; + } + + public void generateConfigDefaults(FileConfiguration fileConfiguration) { + fileConfiguration.addDefault("isEnabled", isEnabled); + fileConfiguration.addDefault("name", name); + fileConfiguration.addDefault("onHitDuration", onHitDuration); + fileConfiguration.addDefault("value", value); + if (!additionalConfigOptions.isEmpty()) + fileConfiguration.addDefaults(additionalConfigOptions); + } + + public String getFileName() { + return fileName; + } + + public boolean isEnabled() { + return isEnabled; + } + + public String getName() { + return name; + } + + public PotionEffectType getPotionEffectType() { + return potionEffectType; + } + + public Map getAdditionalConfigOptions() { + return additionalConfigOptions; + } + + public FileConfiguration getConfiguration() { + return configuration; + } + + public double getValue() { + return value; + } + + public int getOnHitDuration() { + return onHitDuration; + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/AbsorptionConfig.java b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/AbsorptionConfig.java new file mode 100644 index 000000000..804a2c2ad --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/AbsorptionConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.potioneffects.premade; + +import com.magmaguy.elitemobs.config.potioneffects.PotionEffectsConfigFields; + +public class AbsorptionConfig extends PotionEffectsConfigFields { + public AbsorptionConfig() { + super("absorption", + true, + "Absorption", + 2, + 100); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/BlindnessConfig.java b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/BlindnessConfig.java new file mode 100644 index 000000000..8726ef592 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/BlindnessConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.potioneffects.premade; + +import com.magmaguy.elitemobs.config.potioneffects.PotionEffectsConfigFields; + +public class BlindnessConfig extends PotionEffectsConfigFields { + public BlindnessConfig() { + super("blindness", + true, + "Blindness", + 5, + 50); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/ConduitPowerConfig.java b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/ConduitPowerConfig.java new file mode 100644 index 000000000..472d7176f --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/ConduitPowerConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.potioneffects.premade; + +import com.magmaguy.elitemobs.config.potioneffects.PotionEffectsConfigFields; + +public class ConduitPowerConfig extends PotionEffectsConfigFields { + public ConduitPowerConfig() { + super("conduit_power", + true, + "Conduit Power", + 30, + 100); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/ConfusionConfig.java b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/ConfusionConfig.java new file mode 100644 index 000000000..1a0d05578 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/ConfusionConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.potioneffects.premade; + +import com.magmaguy.elitemobs.config.potioneffects.PotionEffectsConfigFields; + +public class ConfusionConfig extends PotionEffectsConfigFields { + public ConfusionConfig() { + super("confusion", + true, + "Nausea", + 10, + 50); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/DamageResistanceConfig.java b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/DamageResistanceConfig.java new file mode 100644 index 000000000..62760cf3e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/DamageResistanceConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.potioneffects.premade; + +import com.magmaguy.elitemobs.config.potioneffects.PotionEffectsConfigFields; + +public class DamageResistanceConfig extends PotionEffectsConfigFields { + public DamageResistanceConfig() { + super("damage_resistance", + true, + "Resistance", + 30, + 100); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/DolphinsGraceConfig.java b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/DolphinsGraceConfig.java new file mode 100644 index 000000000..8d64e3efd --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/DolphinsGraceConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.potioneffects.premade; + +import com.magmaguy.elitemobs.config.potioneffects.PotionEffectsConfigFields; + +public class DolphinsGraceConfig extends PotionEffectsConfigFields { + public DolphinsGraceConfig() { + super("dolphins_grace", + true, + "Dolphin's Grace", + 30, + 100); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/FastDiggingConfig.java b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/FastDiggingConfig.java new file mode 100644 index 000000000..47e2aa1fd --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/FastDiggingConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.potioneffects.premade; + +import com.magmaguy.elitemobs.config.potioneffects.PotionEffectsConfigFields; + +public class FastDiggingConfig extends PotionEffectsConfigFields { + public FastDiggingConfig() { + super("fast_digging", + true, + "Haste", + 30, + 100); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/FireResistanceConfig.java b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/FireResistanceConfig.java new file mode 100644 index 000000000..d29a4f58c --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/FireResistanceConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.potioneffects.premade; + +import com.magmaguy.elitemobs.config.potioneffects.PotionEffectsConfigFields; + +public class FireResistanceConfig extends PotionEffectsConfigFields { + public FireResistanceConfig() { + super("fire_resistance", + true, + "Fire Resistance", + 15, + 50); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/GlowingConfig.java b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/GlowingConfig.java new file mode 100644 index 000000000..99380b613 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/GlowingConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.potioneffects.premade; + +import com.magmaguy.elitemobs.config.potioneffects.PotionEffectsConfigFields; + +public class GlowingConfig extends PotionEffectsConfigFields { + public GlowingConfig() { + super("glowing", + true, + "Glowing", + 60, + 10); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/HarmConfig.java b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/HarmConfig.java new file mode 100644 index 000000000..282a83915 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/HarmConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.potioneffects.premade; + +import com.magmaguy.elitemobs.config.potioneffects.PotionEffectsConfigFields; + +public class HarmConfig extends PotionEffectsConfigFields { + public HarmConfig() { + super("harm", + true, + "Instant Damage", + 1, + 100); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/HealConfig.java b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/HealConfig.java new file mode 100644 index 000000000..6b7cd9c0e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/HealConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.potioneffects.premade; + +import com.magmaguy.elitemobs.config.potioneffects.PotionEffectsConfigFields; + +public class HealConfig extends PotionEffectsConfigFields { + public HealConfig() { + super("heal", + true, + "Instant Health", + 1, + 100); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/HealthBoostConfig.java b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/HealthBoostConfig.java new file mode 100644 index 000000000..4755e0789 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/HealthBoostConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.potioneffects.premade; + +import com.magmaguy.elitemobs.config.potioneffects.PotionEffectsConfigFields; + +public class HealthBoostConfig extends PotionEffectsConfigFields { + public HealthBoostConfig() { + super("health_boost", + true, + "Health Boost", + 90, + 100); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/HungerConfig.java b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/HungerConfig.java new file mode 100644 index 000000000..53339d68c --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/HungerConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.potioneffects.premade; + +import com.magmaguy.elitemobs.config.potioneffects.PotionEffectsConfigFields; + +public class HungerConfig extends PotionEffectsConfigFields { + public HungerConfig() { + super("hunger", + true, + "Hunger", + 30, + 10); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/IncreaseDamageConfig.java b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/IncreaseDamageConfig.java new file mode 100644 index 000000000..10c3221ff --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/IncreaseDamageConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.potioneffects.premade; + +import com.magmaguy.elitemobs.config.potioneffects.PotionEffectsConfigFields; + +public class IncreaseDamageConfig extends PotionEffectsConfigFields { + public IncreaseDamageConfig() { + super("increase_damage", + true, + "Strength", + 30, + 100); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/InvisibilityConfig.java b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/InvisibilityConfig.java new file mode 100644 index 000000000..4f1918abd --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/InvisibilityConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.potioneffects.premade; + +import com.magmaguy.elitemobs.config.potioneffects.PotionEffectsConfigFields; + +public class InvisibilityConfig extends PotionEffectsConfigFields { + public InvisibilityConfig() { + super("invisibility", + true, + "Invisibility", + 3, + 50); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/JumpConfig.java b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/JumpConfig.java new file mode 100644 index 000000000..b5b8ebff8 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/JumpConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.potioneffects.premade; + +import com.magmaguy.elitemobs.config.potioneffects.PotionEffectsConfigFields; + +public class JumpConfig extends PotionEffectsConfigFields { + public JumpConfig() { + super("jump", + true, + "Jump Boost", + 10, + 50); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/LevitationConfig.java b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/LevitationConfig.java new file mode 100644 index 000000000..de9e2c5ca --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/LevitationConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.potioneffects.premade; + +import com.magmaguy.elitemobs.config.potioneffects.PotionEffectsConfigFields; + +public class LevitationConfig extends PotionEffectsConfigFields { + public LevitationConfig() { + super("levitation", + true, + "Levitation", + 5, + 50); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/LuckConfig.java b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/LuckConfig.java new file mode 100644 index 000000000..3c08f7b16 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/LuckConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.potioneffects.premade; + +import com.magmaguy.elitemobs.config.potioneffects.PotionEffectsConfigFields; + +public class LuckConfig extends PotionEffectsConfigFields { + public LuckConfig() { + super("luck", + true, + "Luck", + 30, + 50); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/NightVisionConfig.java b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/NightVisionConfig.java new file mode 100644 index 000000000..dfdd8dafd --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/NightVisionConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.potioneffects.premade; + +import com.magmaguy.elitemobs.config.potioneffects.PotionEffectsConfigFields; + +public class NightVisionConfig extends PotionEffectsConfigFields { + public NightVisionConfig() { + super("night_vision", + true, + "Night Vision", + 30, + 50); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/PoisonConfig.java b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/PoisonConfig.java new file mode 100644 index 000000000..de91f0662 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/PoisonConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.potioneffects.premade; + +import com.magmaguy.elitemobs.config.potioneffects.PotionEffectsConfigFields; + +public class PoisonConfig extends PotionEffectsConfigFields { + public PoisonConfig() { + super("poison", + true, + "Poison", + 20, + 50); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/RegenerationConfig.java b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/RegenerationConfig.java new file mode 100644 index 000000000..de38e7383 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/RegenerationConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.potioneffects.premade; + +import com.magmaguy.elitemobs.config.potioneffects.PotionEffectsConfigFields; + +public class RegenerationConfig extends PotionEffectsConfigFields { + public RegenerationConfig() { + super("regeneration", + true, + "Regeneration", + 20, + 100); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/SaturationConfig.java b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/SaturationConfig.java new file mode 100644 index 000000000..66e7bb5ba --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/SaturationConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.potioneffects.premade; + +import com.magmaguy.elitemobs.config.potioneffects.PotionEffectsConfigFields; + +public class SaturationConfig extends PotionEffectsConfigFields { + public SaturationConfig() { + super("saturation", + true, + "Saturation", + 20, + 100); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/SlowConfig.java b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/SlowConfig.java new file mode 100644 index 000000000..0d6ebdfbf --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/SlowConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.potioneffects.premade; + +import com.magmaguy.elitemobs.config.potioneffects.PotionEffectsConfigFields; + +public class SlowConfig extends PotionEffectsConfigFields { + public SlowConfig() { + super("slow", + true, + "Slowness", + 15, + 50); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/SlowDiggingConfig.java b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/SlowDiggingConfig.java new file mode 100644 index 000000000..5a74071e4 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/SlowDiggingConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.potioneffects.premade; + +import com.magmaguy.elitemobs.config.potioneffects.PotionEffectsConfigFields; + +public class SlowDiggingConfig extends PotionEffectsConfigFields { + public SlowDiggingConfig() { + super("slow_digging", + true, + "Mining Fatigue", + 10, + 10); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/SlowFallingConfig.java b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/SlowFallingConfig.java new file mode 100644 index 000000000..b90473552 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/SlowFallingConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.potioneffects.premade; + +import com.magmaguy.elitemobs.config.potioneffects.PotionEffectsConfigFields; + +public class SlowFallingConfig extends PotionEffectsConfigFields { + public SlowFallingConfig() { + super("slow_falling", + true, + "Slow Falling", + 30, + 50); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/SpeedConfig.java b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/SpeedConfig.java new file mode 100644 index 000000000..271b40dcb --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/SpeedConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.potioneffects.premade; + +import com.magmaguy.elitemobs.config.potioneffects.PotionEffectsConfigFields; + +public class SpeedConfig extends PotionEffectsConfigFields { + public SpeedConfig() { + super("speed", + true, + "Speed", + 30, + 50); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/UnluckConfig.java b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/UnluckConfig.java new file mode 100644 index 000000000..7859e5080 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/UnluckConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.potioneffects.premade; + +import com.magmaguy.elitemobs.config.potioneffects.PotionEffectsConfigFields; + +public class UnluckConfig extends PotionEffectsConfigFields { + public UnluckConfig() { + super("unluck", + true, + "Bad Luck", + 30, + 10); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/WaterBreathingConfig.java b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/WaterBreathingConfig.java new file mode 100644 index 000000000..d5bec53ab --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/WaterBreathingConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.potioneffects.premade; + +import com.magmaguy.elitemobs.config.potioneffects.PotionEffectsConfigFields; + +public class WaterBreathingConfig extends PotionEffectsConfigFields { + public WaterBreathingConfig() { + super("water_breathing", + true, + "Water Breathing", + 30, + 50); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/WeaknessConfig.java b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/WeaknessConfig.java new file mode 100644 index 000000000..1033e94e6 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/WeaknessConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.potioneffects.premade; + +import com.magmaguy.elitemobs.config.potioneffects.PotionEffectsConfigFields; + +public class WeaknessConfig extends PotionEffectsConfigFields { + public WeaknessConfig() { + super("weakness", + true, + "Weakness", + 15, + 50); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/WitherConfig.java b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/WitherConfig.java new file mode 100644 index 000000000..96a388909 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/potioneffects/premade/WitherConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.potioneffects.premade; + +import com.magmaguy.elitemobs.config.potioneffects.PotionEffectsConfigFields; + +public class WitherConfig extends PotionEffectsConfigFields { + public WitherConfig() { + super("wither", + true, + "Wither", + 15, + 100); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/PowersConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/PowersConfig.java new file mode 100644 index 000000000..eb0bbed4c --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/PowersConfig.java @@ -0,0 +1,28 @@ +package com.magmaguy.elitemobs.config.powers; + +import com.magmaguy.elitemobs.config.CustomConfig; +import com.magmaguy.elitemobs.powers.meta.ElitePower; + +import java.util.HashMap; + +public class PowersConfig extends CustomConfig { + + private static HashMap powers = new HashMap<>(); + + public PowersConfig() { + super("powers", "com.magmaguy.elitemobs.config.powers.premade", PowersConfigFields.class); + powers = new HashMap<>(); + for (String key : super.getCustomConfigFieldsHashMap().keySet()) + powers.put(key, (PowersConfigFields) super.getCustomConfigFieldsHashMap().get(key)); + ElitePower.initializePowers(); + } + + public static HashMap getPowers() { + return powers; + } + + public static PowersConfigFields getPower(String filename) { + return powers.get(filename); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/PowersConfigFields.java b/src/main/java/com/magmaguy/elitemobs/config/powers/PowersConfigFields.java new file mode 100644 index 000000000..eab8eff54 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/PowersConfigFields.java @@ -0,0 +1,62 @@ +package com.magmaguy.elitemobs.config.powers; + +import com.magmaguy.elitemobs.config.CustomConfigFields; +import lombok.Getter; +import lombok.Setter; + +public class PowersConfigFields extends CustomConfigFields { + + @Getter + @Setter + private String name; + @Getter + @Setter + private String effect; + @Getter + @Setter + private int powerCooldown = 0; + @Getter + @Setter + private int globalCooldown = 0; + + public PowersConfigFields(String fileName, + boolean isEnabled, + String name, + String material) { + super(fileName, isEnabled); + this.name = name; + this.effect = material; + } + + public PowersConfigFields(String fileName, + boolean isEnabled, + String name, + String material, + int powerCooldown, + int globalCooldown) { + super(fileName, isEnabled); + this.name = name; + this.effect = material; + this.powerCooldown = powerCooldown; + this.globalCooldown = globalCooldown; + } + + public PowersConfigFields(String fileName, + boolean isEnabled) { + super(fileName, isEnabled); + } + + @Override + public void processConfigFields() { + this.isEnabled = processBoolean("isEnabled", isEnabled, true, true); + this.name = processString("name", name, null, true); + this.effect = processString("effect", effect, null, false); + this.powerCooldown = processInt("powerCooldown", powerCooldown, 0, false); + this.globalCooldown = processInt("globalCooldown", globalCooldown, 0, false); + processAdditionalFields(); + } + + public void processAdditionalFields() { + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/ArrowFireworksConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/ArrowFireworksConfig.java new file mode 100644 index 000000000..c348f5332 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/ArrowFireworksConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Material; + +public class ArrowFireworksConfig extends PowersConfigFields { + public ArrowFireworksConfig() { + super("arrow_fireworks", + true, + "Arrow Fireworks", + Material.FIREWORK_ROCKET.toString()); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/ArrowRainConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/ArrowRainConfig.java new file mode 100644 index 000000000..e83514dcf --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/ArrowRainConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Particle; + +public class ArrowRainConfig extends PowersConfigFields { + public ArrowRainConfig() { + super("arrow_rain", + true, + "Arrow Rain", + Particle.DRIP_WATER.toString()); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackArrowConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackArrowConfig.java new file mode 100644 index 000000000..88684f7c9 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackArrowConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Material; + +public class AttackArrowConfig extends PowersConfigFields { + public AttackArrowConfig() { + super("attack_arrow", + true, + "Arrow", + Material.DISPENSER.toString()); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackBlindingConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackBlindingConfig.java new file mode 100644 index 000000000..dfeb14ed9 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackBlindingConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Particle; + +public class AttackBlindingConfig extends PowersConfigFields { + public AttackBlindingConfig() { + super("attack_blinding", + true, + "Blinding", + Particle.SPELL_MOB.toString()); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackConfusingConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackConfusingConfig.java new file mode 100644 index 000000000..687103d11 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackConfusingConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Particle; + +public class AttackConfusingConfig extends PowersConfigFields { + public AttackConfusingConfig() { + super("attack_confusing", + true, + "Confusing", + Particle.SPELL_MOB.toString()); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackFireConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackFireConfig.java new file mode 100644 index 000000000..f5792ae64 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackFireConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Material; + +public class AttackFireConfig extends PowersConfigFields { + public AttackFireConfig() { + super("attack_fire", + true, + "Immolate", + Material.BLAZE_POWDER.toString()); + } +} \ No newline at end of file diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackFireballConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackFireballConfig.java new file mode 100644 index 000000000..7a5376a69 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackFireballConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Material; + +public class AttackFireballConfig extends PowersConfigFields { + public AttackFireballConfig() { + super("attack_fireball", + true, + "Fireball", + Material.FIRE_CHARGE.toString()); + } +} \ No newline at end of file diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackFreezeConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackFreezeConfig.java new file mode 100644 index 000000000..f155246c9 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackFreezeConfig.java @@ -0,0 +1,21 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Material; + +public class AttackFreezeConfig extends PowersConfigFields { + public static String freezeMessage; + + public AttackFreezeConfig() { + super("attack_freeze", + true, + "Cryomancer", + Material.PACKED_ICE.toString()); + } + + @Override + public void processAdditionalFields() { + freezeMessage = ConfigurationEngine.setString(fileConfiguration, "freezeMessage", "&8[EM] &9You've been frozen!"); + } +} \ No newline at end of file diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackGravityConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackGravityConfig.java new file mode 100644 index 000000000..a7a15a584 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackGravityConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Material; + +public class AttackGravityConfig extends PowersConfigFields { + public AttackGravityConfig() { + super("attack_gravity", + true, + "Levitator", + Material.ELYTRA.toString()); + } +} \ No newline at end of file diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackLightningConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackLightningConfig.java new file mode 100644 index 000000000..67224b8b8 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackLightningConfig.java @@ -0,0 +1,21 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Material; + +public class AttackLightningConfig extends PowersConfigFields { + public static int delayBetweenStrikes; + + public AttackLightningConfig() { + super("attack_lightning", + true, + "Thunderous", + Material.HORN_CORAL.toString()); + } + + @Override + public void processAdditionalFields() { + delayBetweenStrikes = ConfigurationEngine.setInt(fileConfiguration, "delayBetweenStrikes", 15); + } +} \ No newline at end of file diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackPoisonConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackPoisonConfig.java new file mode 100644 index 000000000..08d1ce5a2 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackPoisonConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Material; + +public class AttackPoisonConfig extends PowersConfigFields { + public AttackPoisonConfig() { + super("attack_poison", + true, + "Poisonous", + Material.EMERALD.toString()); + } +} \ No newline at end of file diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackPushConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackPushConfig.java new file mode 100644 index 000000000..4a8d2b26d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackPushConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Material; + +public class AttackPushConfig extends PowersConfigFields { + public AttackPushConfig() { + super("attack_push", + true, + "Knockback", + Material.PISTON.toString()); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackVacuumConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackVacuumConfig.java new file mode 100644 index 000000000..57fc8ea32 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackVacuumConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Material; + +public class AttackVacuumConfig extends PowersConfigFields { + public AttackVacuumConfig() { + super("attack_vacuum", + true, + "Vacuum", + Material.LEAD.toString()); + } +} \ No newline at end of file diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackWeaknessConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackWeaknessConfig.java new file mode 100644 index 000000000..dbcfd463d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackWeaknessConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Material; + +public class AttackWeaknessConfig extends PowersConfigFields { + public AttackWeaknessConfig() { + super("attack_weakness", + true, + "Weakening", + Material.TOTEM_OF_UNDYING.toString()); + } +} \ No newline at end of file diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackWebConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackWebConfig.java new file mode 100644 index 000000000..9cae7e7d2 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackWebConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Material; + +public class AttackWebConfig extends PowersConfigFields { + public AttackWebConfig() { + super("attack_web", + true, + "Webbing", + Material.COBWEB.toString()); + } +} \ No newline at end of file diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackWitherConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackWitherConfig.java new file mode 100644 index 000000000..3adf54fc7 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/AttackWitherConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Material; + +public class AttackWitherConfig extends PowersConfigFields { + public AttackWitherConfig() { + super("attack_wither", + true, + "Withering", + Material.WITHER_SKELETON_SKULL.toString()); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/BonusCoinsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/BonusCoinsConfig.java new file mode 100644 index 000000000..28d1fad4e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/BonusCoinsConfig.java @@ -0,0 +1,12 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; + +public class BonusCoinsConfig extends PowersConfigFields { + public BonusCoinsConfig() { + super("bonus_coins", + true, + "Bonus Coins", + null); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/BonusLootConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/BonusLootConfig.java new file mode 100644 index 000000000..7fd8c9ff1 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/BonusLootConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Material; + +public class BonusLootConfig extends PowersConfigFields { + public BonusLootConfig() { + super("bonus_loot", + true, + "Bonus Loot", + Material.CHEST.toString()); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/BulletHellConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/BulletHellConfig.java new file mode 100644 index 000000000..8e7b6e8f5 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/BulletHellConfig.java @@ -0,0 +1,12 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; + +public class BulletHellConfig extends PowersConfigFields { + public BulletHellConfig() { + super("bullet_hell", + true, + "Bullet Hell", + null); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/ChannelHealingConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/ChannelHealingConfig.java new file mode 100644 index 000000000..de307b379 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/ChannelHealingConfig.java @@ -0,0 +1,14 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; + +public class ChannelHealingConfig extends PowersConfigFields { + public ChannelHealingConfig() { + super("channel_healing", + true, + "Channel Healing", + null, + 1, + 0); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/CorpseConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/CorpseConfig.java new file mode 100644 index 000000000..a50579c6d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/CorpseConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Material; + +public class CorpseConfig extends PowersConfigFields { + public CorpseConfig() { + super("corpse", + true, + "Corpse", + Material.BONE_BLOCK.toString()); + } +} \ No newline at end of file diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/CustomSummonPowerConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/CustomSummonPowerConfig.java new file mode 100644 index 000000000..a0943462c --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/CustomSummonPowerConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Material; + +public class CustomSummonPowerConfig extends PowersConfigFields { + public CustomSummonPowerConfig() { + super("custom_summon", + true, + "Custom Summon", + Material.AIR.toString()); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/DeathSliceConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/DeathSliceConfig.java new file mode 100644 index 000000000..aa5183991 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/DeathSliceConfig.java @@ -0,0 +1,12 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; + +public class DeathSliceConfig extends PowersConfigFields { + public DeathSliceConfig() { + super("death_slice", + true, + "Death Slice", + null); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/EnderDragonAimedFireballConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/EnderDragonAimedFireballConfig.java new file mode 100644 index 000000000..e61c11141 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/EnderDragonAimedFireballConfig.java @@ -0,0 +1,14 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; + +public class EnderDragonAimedFireballConfig extends PowersConfigFields { + public EnderDragonAimedFireballConfig() { + super("ender_dragon_aimed_fireball", + true, + "Aimed Fireballs", + null, + 30, + 5); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/EnderDragonArrowBombardmentConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/EnderDragonArrowBombardmentConfig.java new file mode 100644 index 000000000..5dbb91f82 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/EnderDragonArrowBombardmentConfig.java @@ -0,0 +1,14 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; + +public class EnderDragonArrowBombardmentConfig extends PowersConfigFields { + public EnderDragonArrowBombardmentConfig() { + super("ender_dragon_arrow_bombardment", + true, + "Arrow Bombardment", + null, + 30, + 5); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/EnderDragonDiscoFireballsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/EnderDragonDiscoFireballsConfig.java new file mode 100644 index 000000000..7a9c95ed7 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/EnderDragonDiscoFireballsConfig.java @@ -0,0 +1,14 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; + +public class EnderDragonDiscoFireballsConfig extends PowersConfigFields { + public EnderDragonDiscoFireballsConfig() { + super("ender_dragon_disco_fireballs", + true, + "Disco Fireballs", + null, + 120, + 30); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/EnderDragonEmpoweredLightningConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/EnderDragonEmpoweredLightningConfig.java new file mode 100644 index 000000000..d2a2363e5 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/EnderDragonEmpoweredLightningConfig.java @@ -0,0 +1,14 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; + +public class EnderDragonEmpoweredLightningConfig extends PowersConfigFields { + public EnderDragonEmpoweredLightningConfig() { + super("ender_dragon_empowered_lightning", + true, + "Empowered Lightning", + null, + 120, + 30); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/EnderDragonEnderFireballBombardmentConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/EnderDragonEnderFireballBombardmentConfig.java new file mode 100644 index 000000000..924ec81a2 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/EnderDragonEnderFireballBombardmentConfig.java @@ -0,0 +1,14 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; + +public class EnderDragonEnderFireballBombardmentConfig extends PowersConfigFields { + public EnderDragonEnderFireballBombardmentConfig() { + super("ender_dragon_ender_fireball_bombardment", + true, + "Ender Fireball Bombardment", + null, + 30, + 5); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/EnderDragonEndermiteBombardmentConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/EnderDragonEndermiteBombardmentConfig.java new file mode 100644 index 000000000..12d829a24 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/EnderDragonEndermiteBombardmentConfig.java @@ -0,0 +1,14 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; + +public class EnderDragonEndermiteBombardmentConfig extends PowersConfigFields { + public EnderDragonEndermiteBombardmentConfig() { + super("ender_dragon_endermite_bombardment", + true, + "Endermite Bombardment", + null, + 120, + 30); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/EnderDragonFireballBombardment.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/EnderDragonFireballBombardment.java new file mode 100644 index 000000000..574b31aa9 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/EnderDragonFireballBombardment.java @@ -0,0 +1,14 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; + +public class EnderDragonFireballBombardment extends PowersConfigFields { + public EnderDragonFireballBombardment() { + super("ender_dragon_fireball_bombardment", + true, + "Fireball Bombardment", + null, + 30, + 5); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/EnderDragonPotionBombardmentConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/EnderDragonPotionBombardmentConfig.java new file mode 100644 index 000000000..3ebb66212 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/EnderDragonPotionBombardmentConfig.java @@ -0,0 +1,14 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; + +public class EnderDragonPotionBombardmentConfig extends PowersConfigFields { + public EnderDragonPotionBombardmentConfig() { + super("ender_dragon_potion_bombardment", + true, + "Potion Bombardment", + null, + 30, + 5); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/EnderDragonShockwaveConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/EnderDragonShockwaveConfig.java new file mode 100644 index 000000000..e745bfd13 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/EnderDragonShockwaveConfig.java @@ -0,0 +1,14 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; + +public class EnderDragonShockwaveConfig extends PowersConfigFields { + public EnderDragonShockwaveConfig() { + super("ender_dragon_shockwave", + true, + "Shockwave", + null, + 60, + 30); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/EnderDragonTornadoConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/EnderDragonTornadoConfig.java new file mode 100644 index 000000000..cacc31022 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/EnderDragonTornadoConfig.java @@ -0,0 +1,14 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; + +public class EnderDragonTornadoConfig extends PowersConfigFields { + public EnderDragonTornadoConfig() { + super("ender_dragon_tornado", + true, + "Tornado", + null, + 60, + 30); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/FirestormConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/FirestormConfig.java new file mode 100644 index 000000000..ac543041b --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/FirestormConfig.java @@ -0,0 +1,12 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; + +public class FirestormConfig extends PowersConfigFields { + public FirestormConfig() { + super("firestorm", + true, + "Firestorm", + null); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/FireworksBarrageConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/FireworksBarrageConfig.java new file mode 100644 index 000000000..459b34785 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/FireworksBarrageConfig.java @@ -0,0 +1,14 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; + +public class FireworksBarrageConfig extends PowersConfigFields { + public FireworksBarrageConfig() { + super("fireworks_barrage", + true, + "Fireworks Barrage", + null, + 30, + 20); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/FlamePyreConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/FlamePyreConfig.java new file mode 100644 index 000000000..f5bb4d2ce --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/FlamePyreConfig.java @@ -0,0 +1,12 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; + +public class FlamePyreConfig extends PowersConfigFields { + public FlamePyreConfig() { + super("flame_pyre", + true, + "Flame Pyre", + null); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/FlamethrowerConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/FlamethrowerConfig.java new file mode 100644 index 000000000..0780ee404 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/FlamethrowerConfig.java @@ -0,0 +1,12 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; + +public class FlamethrowerConfig extends PowersConfigFields { + public FlamethrowerConfig() { + super("flamethrower", + true, + "Flamethrower", + null); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/FrostConeConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/FrostConeConfig.java new file mode 100644 index 000000000..59a2917aa --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/FrostConeConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; + +public class FrostConeConfig extends PowersConfigFields { + public FrostConeConfig() { + super("frost_cone", + true, + "Frost Cone", + null + ); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/GoldExplosionConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/GoldExplosionConfig.java new file mode 100644 index 000000000..29c02357f --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/GoldExplosionConfig.java @@ -0,0 +1,12 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; + +public class GoldExplosionConfig extends PowersConfigFields { + public GoldExplosionConfig() { + super("gold_explosion", + true, + "Gold Explosion", + null); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/GoldShotgunConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/GoldShotgunConfig.java new file mode 100644 index 000000000..5011743db --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/GoldShotgunConfig.java @@ -0,0 +1,12 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; + +public class GoldShotgunConfig extends PowersConfigFields { + public GoldShotgunConfig() { + super("gold_shotgun", + true, + "Gold Shotgun", + null); + } +} \ No newline at end of file diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/GroundPoundConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/GroundPoundConfig.java new file mode 100644 index 000000000..5f9e40a48 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/GroundPoundConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Material; + +public class GroundPoundConfig extends PowersConfigFields { + public GroundPoundConfig() { + super("ground_pound", + true, + "Ground Pound", + Material.DIRT.toString()); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/HyperLootConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/HyperLootConfig.java new file mode 100644 index 000000000..f1bbf2749 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/HyperLootConfig.java @@ -0,0 +1,12 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; + +public class HyperLootConfig extends PowersConfigFields { + public HyperLootConfig() { + super("hyper_loot", + true, + "Hyper Loot", + null); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/ImplosionConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/ImplosionConfig.java new file mode 100644 index 000000000..80f253e46 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/ImplosionConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Material; + +public class ImplosionConfig extends PowersConfigFields { + public ImplosionConfig() { + super("implosion", + true, + "Implosion", + Material.SLIME_BALL.toString()); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/InvisibilityConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/InvisibilityConfig.java new file mode 100644 index 000000000..fd17998de --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/InvisibilityConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Material; + +public class InvisibilityConfig extends PowersConfigFields { + public InvisibilityConfig() { + super("invisibility", + true, + "Invisibility", + Material.GLASS_PANE.toString()); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/InvulnerabilityArrowConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/InvulnerabilityArrowConfig.java new file mode 100644 index 000000000..27495a512 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/InvulnerabilityArrowConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Material; + +public class InvulnerabilityArrowConfig extends PowersConfigFields { + public InvulnerabilityArrowConfig() { + super("invulnerability_arrow", + true, + "Arrow Invulnerability", + Material.SPECTRAL_ARROW.toString()); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/InvulnerabilityFallDamageConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/InvulnerabilityFallDamageConfig.java new file mode 100644 index 000000000..d39fb4c3a --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/InvulnerabilityFallDamageConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Material; + +public class InvulnerabilityFallDamageConfig extends PowersConfigFields { + public InvulnerabilityFallDamageConfig() { + super("invulnerability_fall_damage", + true, + "Fall Damage Invulnerability", + Material.FEATHER.toString()); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/InvulnerabilityFireConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/InvulnerabilityFireConfig.java new file mode 100644 index 000000000..cbe3983f3 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/InvulnerabilityFireConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Particle; + +public class InvulnerabilityFireConfig extends PowersConfigFields { + public InvulnerabilityFireConfig() { + super("invulnerability_fire", + true, + "Fire Invulnerability", + Particle.FLAME.toString()); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/InvulnerabilityKnockbackConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/InvulnerabilityKnockbackConfig.java new file mode 100644 index 000000000..2c77bf6cf --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/InvulnerabilityKnockbackConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Material; + +public class InvulnerabilityKnockbackConfig extends PowersConfigFields { + public InvulnerabilityKnockbackConfig() { + super("invulnerability_knockback", + true, + "Knockback Invulnerability", + Material.ANVIL.toString()); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/LightningBoltsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/LightningBoltsConfig.java new file mode 100644 index 000000000..eb24cee49 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/LightningBoltsConfig.java @@ -0,0 +1,20 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; + +public class LightningBoltsConfig extends PowersConfigFields { + public static int delayBetweenStrikes; + + public LightningBoltsConfig() { + super("lightning_bolts", + true, + "Lightning Bolt", + null); + } + + @Override + public void processAdditionalFields() { + delayBetweenStrikes = ConfigurationEngine.setInt(fileConfiguration, "delayBetweenStrikes", 15); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/MeteorShowerConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/MeteorShowerConfig.java new file mode 100644 index 000000000..ad558b77d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/MeteorShowerConfig.java @@ -0,0 +1,12 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; + +public class MeteorShowerConfig extends PowersConfigFields { + public MeteorShowerConfig() { + super("meteor_shower", + true, + "Meteor Shower", + null); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/MoonwalkConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/MoonwalkConfig.java new file mode 100644 index 000000000..c33545e54 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/MoonwalkConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Material; + +public class MoonwalkConfig extends PowersConfigFields { + public MoonwalkConfig() { + super("moonwalk", + true, + "Moonwalk", + Material.SLIME_BLOCK.toString()); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/MovementSpeedConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/MovementSpeedConfig.java new file mode 100644 index 000000000..24904b875 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/MovementSpeedConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Material; + +public class MovementSpeedConfig extends PowersConfigFields { + public MovementSpeedConfig() { + super("movement_speed", + true, + "movement_speed", + Material.GOLDEN_BOOTS.toString()); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/PhotonRayConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/PhotonRayConfig.java new file mode 100644 index 000000000..411034ba2 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/PhotonRayConfig.java @@ -0,0 +1,14 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; + +public class PhotonRayConfig extends PowersConfigFields { + public PhotonRayConfig() { + super("photon_ray", + true, + "Photon Ray", + null, + 60, + 20); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/PlasmaBlasterConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/PlasmaBlasterConfig.java new file mode 100644 index 000000000..ba040dc2e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/PlasmaBlasterConfig.java @@ -0,0 +1,12 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; + +public class PlasmaBlasterConfig extends PowersConfigFields { + public PlasmaBlasterConfig() { + super("plasma_blaster", + true, + "Plasma Blaster", + null); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/ShieldWallConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/ShieldWallConfig.java new file mode 100644 index 000000000..531c52c16 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/ShieldWallConfig.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Material; + +public class ShieldWallConfig extends PowersConfigFields { + public ShieldWallConfig() { + super("shield_wall", + true, + "Shield Wall", + Material.SHIELD.toString(), + 60, + 7); + } + + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/SkeletonPillarConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/SkeletonPillarConfig.java new file mode 100644 index 000000000..62784df52 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/SkeletonPillarConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Material; + +public class SkeletonPillarConfig extends PowersConfigFields { + public SkeletonPillarConfig() { + super("skeleton_pillar", + true, + "Pillar", + Material.BONE.toString()); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/SkeletonTrackingArrowConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/SkeletonTrackingArrowConfig.java new file mode 100644 index 000000000..1cc8459eb --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/SkeletonTrackingArrowConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Material; + +public class SkeletonTrackingArrowConfig extends PowersConfigFields { + public SkeletonTrackingArrowConfig() { + super("skeleton_tracking_arrow", + true, + "Tracking Arrow", + Material.ARROW.toString()); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/SpiritWalkConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/SpiritWalkConfig.java new file mode 100644 index 000000000..85028705f --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/SpiritWalkConfig.java @@ -0,0 +1,12 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; + +public class SpiritWalkConfig extends PowersConfigFields { + public SpiritWalkConfig() { + super("spirit_walk", + true, + "Spirit Walk", + null); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/SummonEmbersConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/SummonEmbersConfig.java new file mode 100644 index 000000000..dc0c451cb --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/SummonEmbersConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; + +public class SummonEmbersConfig extends PowersConfigFields { + public SummonEmbersConfig() { + super("summon_embers", + true, + "Summon Embers", + null); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/SummonTheReturnedConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/SummonTheReturnedConfig.java new file mode 100644 index 000000000..0213c07c0 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/SummonTheReturnedConfig.java @@ -0,0 +1,12 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; + +public class SummonTheReturnedConfig extends PowersConfigFields { + public SummonTheReturnedConfig() { + super("summon_the_returned", + true, + "Summon The Returned", + null); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/TauntConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/TauntConfig.java new file mode 100644 index 000000000..e0bead682 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/TauntConfig.java @@ -0,0 +1,312 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Material; + +import java.util.Arrays; +import java.util.List; + +public class TauntConfig extends PowersConfigFields { + public static List onDamaged, onDamagedByBow, onDamage, onDeath, onTarget; + + public TauntConfig() { + super("taunt", + true, + "Taunt", + Material.JUKEBOX.toString()); + } + + @Override + public void processAdditionalFields() { + onDamaged = ConfigurationEngine.setList(fileConfiguration, "onDamaged", Arrays.asList( + "Ow!", + "Oi!", + "Stop that!", + "Why?!", + "You fight like a Dairy Farmer!", + "You are a pain in the backside!", + "En garde! Touche!", + "Hacks!", + "My health is bugged, unkillable!", + "Your hits only make me stronger!", + "Sticks and stones...", + "'tis but a flesh wound!", + "Emperor protects!", + "Herobrine, aid me!", + "Behind you! A creeper!", + "I have made a terrible mistake.", + "What doesn't kill me...", + "Zombies dig scars", + "I shall show you my true power!", + "Prepare for my ultimate attack!", + "My reinforcements are arriving!", + "You're going to pay for that!", + "That's going to leave a mark!", + "An eye for an eye!", + "Health insurance will cover that", + "I felt that one in my bones", + "'tis but a scratch", + "What was that? A soft breeze?", + "You'll never defeat me like that", + "Pathetic.", + "Weak.", + "That didn't even dent my armor!", + "This is going to be an easy one", + "My grandchildren will feel that", + "Are you even trying?", + "An admin just fully healed me", + "Haxxor!", + "Me? Damaged? Hacks!", + "I can't be defeated!", + "Good thing I'm using hacks!", + "Watch out! Herobrine behind you!", + "My life for Aiur!", + "Your home is getting griefed!", + "Why can't we be friends?", + "Valhalla!", + "Notch save me!", + "No retreat!", + "Hit me with your best shot!")); + + onDamagedByBow = ConfigurationEngine.setList(fileConfiguration, "onDamagedByBow", Arrays.asList( + "Fight me like a Player!", + "Afraid to come up-close?", + "I can smell your fear from here!", + "Did you forget your sword?", + "Coward! Bow are no fair!", + "Bows? That's so 2011...", + "Bows are for the weak of mind!", + "Bows are for the weak of spirit!", + "Bows are for the weak of heart!", + "I thought we agreed no bows!", + "Bows? You'll regret that", + + //regular hits + "Ow!", + "Oi!", + "Stop that!", + "Why?!", + "You fight like a Dairy Farmer!", + "You are a pain in the backside!", + "En garde! Touche!", + "Hacks!", + "My health is bugged, unkillable!", + "Your hits only make me stronger!", + "Sticks and stones...", + "'tis but a flesh wound!", + "Emperor protects!", + "Herobrine, aid me!", + "Behind you! A creeper!", + "I have made a terrible mistake.", + "What doesn't kill me...", + "Zombies dig scars", + "I shall show you my true power!", + "Prepare for my ultimate attack!", + "My reinforcements are arriving!", + "You're going to pay for that!", + "That's going to leave a mark!", + "An eye for an eye!", + "Health insurance will cover that", + "I felt that one in my bones", + "'tis but a scratch", + "What was that? A soft breeze?", + "You'll never defeat me like that", + "Pathetic.", + "Weak.", + "That didn't even dent my armor!", + "This is going to be an easy one", + "My grandchildren will feel that", + "Are you even trying?", + "An admin just fully healed me", + "Haxxor!", + "Me? Damaged? Hacks!", + "I can't be defeated!", + "Good thing I'm using hacks!", + "Watch out! Herobrine behind you!", + "My life for Aiur!", + "Your home is getting griefed!", + "Why can't we be friends?", + "Valhalla!", + "Notch save me!", + "No retreat!", + "Hit me with your best shot!")); + + onDamage = ConfigurationEngine.setList(fileConfiguration, "onDamage", Arrays.asList( + "A solid hit!", + "He shoots, and he scores!", + "You'll feel that in the morning!", + "Victory approaches!", + "Victory shall be mine!", + "That was only half of my power!", + "You came to the wrong hood!", + "You messed with the wrong mob!", + "Get ready to get mobbed on!", + "This was your last mistake!", + "Feel the burn!", + "John Cena", + "How are you still standing?", + "Just give up already!", + "Give up!", + "I have the high ground!", + "I will end you!", + "Hope you came prepared for pain!", + "The hunter becomes the hunted!", + "Blood for the blood throne!", + "Skulls for the skull throne!", + "A good player is a dead player!", + "Git gud!", + "Praise the Sun!", + "The end draws near!", + "You are not prepared.", + "Zug zug!", + "Hardly worth my time!", + "I thought this was a challenge?", + "Pro tip: don't get hit", + "Ima firin mah lazer bwooooooooo", + "For the Emperor!", + "Herobrine shall be pleased!", + "This is the end for you!", + "Are you even trying?", + "Weakling!", + "Pathetic.", + "Maybe this will wake you up.", + "This is just the beggining!", + "We're just getting started!", + "That was just a warm-up!", + "You are no match for me!", + "RKO out of nowhere!", + "I can do this all night long!", + "A fine punching bag!", + "I am the night!", + "I wonder what will break first", + "Revenge for Steve! You monster!", + "Join the mob side!", + "Too easy, too easy!", + "Too easy!", + "You can't defeat me!", + "Pikachuuuuuu", + "Avada kedavra!", + "Crucio!", + "Jierda!", + "A critical hit!", + "This is what skills looks like!", + "9001 damage!", + "Still standing?", + "Face your defeat!", + "A taste of pain to come!", + "I'll make you endangered!")); + + onDeath = ConfigurationEngine.setList(fileConfiguration, "onDeath", Arrays.asList( + "Alas, poor Yorick!", + "The rest is silence", + "I shall return", + "Unforgivable", + "I live, I die, I live again!", + "WITNESS ME", + "I ride to valhalla!", + "VALHALLA!", + "VALHALLA! DELIVERANCE", + "You win, this time", + "A blight upon your land!", + "A pox upon thee!", + "You'll join me soon enough!", + "This is not over", + "Death is but a setback", + "Not like this...", + "I just wanted to go into space", + "We could've been friends", + "Your sins crawling on your back", + "See you in a bit", + "See you later", + "I'll be waiting for you", + "I will be avenged!", + "I won't go gently into the night", + "Should've gotten life insurance", + "It was my last day on the job", + "It was my last day here", + "Et tu, Brute?", + "RIP", + "x.x", + "(x.x)", + "xox", + "Fainted", + "GG, WP", + "GG", + "WP", + "GG no RE", + "HAX", + "Hacker", + "Not fair I was lagging", + "You win, this time", + "You monster...", + "Mediocre...")); + + onTarget = ConfigurationEngine.setList(fileConfiguration, "onTarget", Arrays.asList( + "OI! Get over here!", + "What's that I see? A coward?", + "Sir, prepare your fisticuffs!", + "Let's settle this like cavemen!", + "En garde!", + "Look out! A creeper, behind you!", + "Aren't you a right ugly mug!", + "You look delicious.", + "Prepare for trouble!", + "Let the best click spammer win!", + "SPARTAAAAAA", + "I am actually level 9001", + "Not an Elite Mob", + "Poorly disguised Elite Mob", + "Ah, fresh prey!", + "The hunter becomes the hunted!", + "Killing me crashes the server", + "I'm actually a disguised player!", + "I'm not going to drop any loot!", + "Why can't we be friends?", + "Sssssss", + "This is my last day on the job!", + "Stop right there criminal scum!", + "Prepare to die!", + "Praise the Sun!", + "Git gud", + "Alea jacta est!", + "Facta, non verba!", + "Skulls for the skull throne!", + "Blood for the blood throne!", + "A sacrifice for Herobrine!", + "I shall pierce the heavens!", + "Just who do you think I am!?", + "A weakling! He's mine.", + "Dibs on the weakling!", + "Accio player!", + "A duel to the death!", + "I challenge you to a duel!", + "Pika pika!", + "Did you just call me an infernal", + "What did you just call me?", + "I know what you did you monster!", + "This is how your story ends!", + "Prepare for trouble!", + "I've been preparing for this!", + "I am prepared. Are you?", + "A worthy foe!", + "A worthy opponent!", + "A newbie! It's my lucky day!", + "Your stuff or your life!", + "This is a robbery!", + "It's you! You monster!", + "So hungry, give me your flesh!", + "There he is!", + "Must've been my imagination", + "Hi I'm Mr Meeseeks!", + "I'm Mr Meeseeks, look at me!", + "Your diamonds or your life!", + "For king and country!", + "Hit me with your best shot!", + "Witness me!", + "Witness me blood bag!", + "I go all shiny and chrome!")); + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/ThunderstormConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/ThunderstormConfig.java new file mode 100644 index 000000000..f6e6e0377 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/ThunderstormConfig.java @@ -0,0 +1,12 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; + +public class ThunderstormConfig extends PowersConfigFields { + public ThunderstormConfig() { + super("thunderstorm", + true, + "Thunderstorm", + null); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/TrackingFireballConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/TrackingFireballConfig.java new file mode 100644 index 000000000..a7f1f7547 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/TrackingFireballConfig.java @@ -0,0 +1,21 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Material; + +public class TrackingFireballConfig extends PowersConfigFields { + public static double fireballSpeed; + + public TrackingFireballConfig() { + super("tracking_fireball", + true, + "Tracking Fireball", + Material.FIRE_CHARGE.toString()); + } + + @Override + public void processAdditionalFields() { + fireballSpeed = ConfigurationEngine.setDouble(fileConfiguration, "fireballSpeed", 0.5); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/ZombieBloatConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/ZombieBloatConfig.java new file mode 100644 index 000000000..93ab2e1ac --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/ZombieBloatConfig.java @@ -0,0 +1,13 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Particle; + +public class ZombieBloatConfig extends PowersConfigFields { + public ZombieBloatConfig() { + super("zombie_bloat", + true, + "Bloat", + Particle.TOTEM.toString()); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/ZombieFriendsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/ZombieFriendsConfig.java new file mode 100644 index 000000000..dcf219ea7 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/ZombieFriendsConfig.java @@ -0,0 +1,65 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Material; + +import java.util.Arrays; +import java.util.List; + +public class ZombieFriendsConfig extends PowersConfigFields { + public static String friend1Name, friend2Name; + public static List friendDeathMessage, originalEntityDialog, reinforcementDialog; + + public ZombieFriendsConfig() { + super("zombie_friends", + true, + "Friends", + Material.ZOMBIE_HEAD.toString()); + } + + @Override + public void processAdditionalFields() { + + friend1Name = ConfigurationEngine.setString(fileConfiguration, "friend1Name", "BFF #1"); + friend2Name = ConfigurationEngine.setString(fileConfiguration, "friend2Name", "BFF #2"); + + friendDeathMessage = ConfigurationEngine.setList(fileConfiguration, "friendDeathMessage", Arrays.asList( + "Noooo!", + "Mediocre!", + "Zacharias!", + "He's deader than before!", + "Vengeance!", + "Revenge!", + "I can't believe you've done this.")); + + originalEntityDialog = ConfigurationEngine.setList(fileConfiguration, "originalEntityDialog", Arrays.asList( + "Let's play ZombieCraft later!", + "Feel the power of friendship!", + "El pueblo, unido!", + "I called my friends over!", + "BFF power!", + "One for all!", + "Get him!", + "Screw you guys, I'm going home!")); + + reinforcementDialog = ConfigurationEngine.setList(fileConfiguration, "reinforcementDialog", Arrays.asList( + "Don't mess with our friends!", + "We got your back Zach!", + "Backup has arrived!", + "One for all, one for all!", + "This is going to be easy!", + "Give up we have the high ground!", + "You wanna go bruv?", + "Worldstaaaaaaaaar!", + "What are you doing to our friend", + "Feel the power of friendship!", + "Friendship power at 100%!", + "Zombies, assemble!", + "We got your back mate!", + "Together we are better!", + "The more the merrier!", + "I got you fam!", + "All for one!")); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/ZombieNecronomiconConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/ZombieNecronomiconConfig.java new file mode 100644 index 000000000..bfc405e1c --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/ZombieNecronomiconConfig.java @@ -0,0 +1,43 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import org.bukkit.Material; + +public class ZombieNecronomiconConfig extends PowersConfigFields { + public static String summoningChant; + + public ZombieNecronomiconConfig() { + super("zombie_necronomicon", + true, + "Necronomicon", + Material.ENCHANTED_BOOK.toString()); + } + + @Override + public void processAdditionalFields() { + summoningChant = ConfigurationEngine.setString(fileConfiguration, "summoningChant", "Nor is it to be thought..." + + "that man is either the oldest " + + "or the last of earth's masters, or that the common bulk of life and substance walks alone. The Old Ones" + + " were, the Old Ones are, and the Old Ones shall be. Not in the spaces we know, but between them, they " + + "walk serene and primal, undimensioned and to us unseen. Yog-Sothoth knows the gate. Yog-Sothoth is the " + + "gate. Yog-Sothoth is the key and guardian of the gate. Past, present, future, all are one in Yog-Sothoth. " + + "He knows where the Old Ones broke through of old, and where They shall break through again. He knows " + + "where They had trod earth's fields, and where They still tread them, and why no one can behold Them as " + + "They tread. By Their smell can men sometimes know Them near, but of Their semblance can no man know, " + + "saving only in the features of those They have begotten on mankind; and of those are there many sorts, " + + "differing in likeness from man's truest eidolon to that shape without sight or substance which is Them. " + + "They walk unseen and foul in lonely places where the Words have been spoken and the Rites howled through " + + "at their Seasons. The wind gibbers with Their voices, and the earth mutters with Their consciousness. " + + "They bend the forest and crush the city, yet may not forest or city behold the hand that smites. Kadath " + + "in the cold waste hath known Them, and what man knows Kadath? The ice desert of the South and the sunken " + + "isles of Ocean hold stones whereon Their seal is engraver, but who hath seen the deep frozen city or the " + + "sealed tower long garlanded with seaweed and barnacles? Great Cthulhu is Their cousin, yet can he spy " + + "Them only dimly. Iä! Shub-Niggurath! As a foulness shall ye know Them. Their hand is at your throats, " + + "yet ye see Them not; and Their habitation is even one with your guarded threshold. Yog-Sothoth is the " + + "key to the gate, whereby the spheres meet. Man rules now where They ruled once; They shall soon rule " + + "where man rules now. After summer is winter, after winter summer. They wait patient and potent, for " + + "here shall They reign again."); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/powers/premade/ZombieParentsConfig.java b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/ZombieParentsConfig.java new file mode 100644 index 000000000..36098d77e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/powers/premade/ZombieParentsConfig.java @@ -0,0 +1,77 @@ +package com.magmaguy.elitemobs.config.powers.premade; + +import com.magmaguy.elitemobs.config.ConfigurationEngine; +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import lombok.Getter; +import org.bukkit.Material; + +import java.util.Arrays; +import java.util.List; + +public class ZombieParentsConfig extends PowersConfigFields { + @Getter + private static List deathMessage; + @Getter + private static List bossEntityDialog; + @Getter + private static List zombieDad; + @Getter + private static List zombieMom; + + public ZombieParentsConfig() { + super("zombie_parents", + true, + "Parents", + Material.SKELETON_SKULL.toString()); + } + + @Override + public void processAdditionalFields() { + deathMessage = ConfigurationEngine.setList(fileConfiguration, "deathMessage", Arrays.asList( + "You monster!", + "My baby!", + "What have you done!?", + "Revenge!", + "Nooooo!", + "You will pay for that!", + "Eh, he was adopted", + "He's dead! Again!", + "He's deader than before!", + "You broke him!")); + + bossEntityDialog = ConfigurationEngine.setList(fileConfiguration, "bossEntityDialog", Arrays.asList( + "You're embarrassing me!", + "He's bullying me!", + "He's the one picking on me!", + "I can deal with this alone!", + "Leave me alone, I got this!", + "Stop following me around!", + "God this is so embarrassing!", + "He took my lunch money!", + "He's bullying me!")); + + zombieDad = ConfigurationEngine.setList(fileConfiguration, "zombieDad", Arrays.asList( + "Get away from my son!", + "Stand up for yourself son!", + "I'll deal with him!", + "Stop picking on my son!", + "Why are you doing this?", + "I'll talk to your parents!", + "You go kiddo!", + "Show him who's boss kiddo!", + "Nice punch kiddo!")); + + zombieMom = ConfigurationEngine.setList(fileConfiguration, "zombieMom", Arrays.asList( + "Hands off my child!", + "Are you hurt sweetie?", + "Did he hurt you sweetie?", + "Let me see that booboo sweetie", + "I'll talk to his parents!", + "You forgot your jacket sweetie!", + "Posture, sweetheart", + "Break it up!", + "Stop this!", + "Did you take out the garbage?")); + } + +} \ No newline at end of file diff --git a/src/main/java/com/magmaguy/elitemobs/config/wormholes/WormholeConfig.java b/src/main/java/com/magmaguy/elitemobs/config/wormholes/WormholeConfig.java new file mode 100644 index 000000000..077c2337e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/wormholes/WormholeConfig.java @@ -0,0 +1,24 @@ +package com.magmaguy.elitemobs.config.wormholes; + +import com.magmaguy.elitemobs.config.CustomConfig; +import com.magmaguy.elitemobs.wormhole.Wormhole; +import lombok.Getter; + +import java.util.HashMap; + +public class WormholeConfig extends CustomConfig { + @Getter + private static HashMap wormholes; + + public WormholeConfig() { + super("wormholes", "com.magmaguy.elitemobs.config.wormholes.premade", WormholeConfigFields.class); + wormholes = new HashMap<>(); + for (String key : super.getCustomConfigFieldsHashMap().keySet()) { + if (super.getCustomConfigFieldsHashMap().get(key).isEnabled()) { + wormholes.put(key, (WormholeConfigFields) super.getCustomConfigFieldsHashMap().get(key)); + if (super.getCustomConfigFieldsHashMap().get(key).isEnabled()) + new Wormhole((WormholeConfigFields) super.getCustomConfigFieldsHashMap().get(key)); + } + } + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/wormholes/WormholeConfigFields.java b/src/main/java/com/magmaguy/elitemobs/config/wormholes/WormholeConfigFields.java new file mode 100644 index 000000000..4fc6be063 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/wormholes/WormholeConfigFields.java @@ -0,0 +1,72 @@ +package com.magmaguy.elitemobs.config.wormholes; + +import com.magmaguy.elitemobs.config.CustomConfigFields; +import com.magmaguy.elitemobs.config.CustomConfigFieldsInterface; +import com.magmaguy.elitemobs.wormhole.Wormhole; +import lombok.Getter; +import lombok.Setter; + +public class WormholeConfigFields extends CustomConfigFields implements CustomConfigFieldsInterface { + + @Getter + @Setter + private String location1; + @Getter + @Setter + private String location2; + @Getter + @Setter + private String location1Text; + @Getter + @Setter + private String location2Text; + @Getter + @Setter + private String permission; + @Getter + @Setter + private Wormhole.WormholeStyle style; + @Getter + @Setter + private int particleColor; + @Getter + @Setter + private double coinCost; + @Getter + @Setter + private boolean blindPlayer; + @Getter + @Setter + private double sizeMultiplier = 1D; + + public WormholeConfigFields(String filename, + boolean isEnabled, + String location1, + String location2, + Wormhole.WormholeStyle style) { + super(filename, isEnabled); + this.location1 = location1; + this.location2 = location2; + this.style = style; + } + + public WormholeConfigFields(String filename, boolean isEnabled) { + super(filename, isEnabled); + } + + @Override + public void processConfigFields() { + this.isEnabled = processBoolean("isEnabled", isEnabled, true, true); + this.location1 = processString("location1", location1, null, true); + this.location1Text = processString("location1Text", location1Text, null, false); + this.location2 = processString("location2", location2, null, true); + this.location2Text = processString("location2Text", location2Text, null, false); + this.permission = processString("permission", permission, null, false); + this.coinCost = processDouble("coinCost", coinCost, 0, false); + this.style = processEnum("style", style, Wormhole.WormholeStyle.CUBE, Wormhole.WormholeStyle.class, false); + this.particleColor = processInt("particleColor", particleColor, 0x800080, false); + this.blindPlayer = processBoolean("blindPlayer", blindPlayer, false, false); + this.sizeMultiplier = processDouble("sizeMultiplier", sizeMultiplier, 1D, false); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGAirshipWormholeConfig.java b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGAirshipWormholeConfig.java new file mode 100644 index 000000000..909b51308 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGAirshipWormholeConfig.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.wormholes.premade; + +import com.magmaguy.elitemobs.config.wormholes.WormholeConfigFields; +import com.magmaguy.elitemobs.wormhole.Wormhole; + +public class AGAirshipWormholeConfig extends WormholeConfigFields { + public AGAirshipWormholeConfig() { + super("ag_airship_wormhole", + true, + "em_adventurers_guild,296.5,102,296.5,-90,0", + "airship_minidungeon.yml", + Wormhole.WormholeStyle.CUBE); + setBlindPlayer(true); + setLocation1Text("&f『Airship Minidungeon』 &aLvls 45-55"); + setParticleColor(0xFFFFFF); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGBinderOfWorldsLairWormholeConfig.java b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGBinderOfWorldsLairWormholeConfig.java new file mode 100644 index 000000000..97f990c7f --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGBinderOfWorldsLairWormholeConfig.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.wormholes.premade; + +import com.magmaguy.elitemobs.config.wormholes.WormholeConfigFields; +import com.magmaguy.elitemobs.wormhole.Wormhole; + +public class AGBinderOfWorldsLairWormholeConfig extends WormholeConfigFields { + public AGBinderOfWorldsLairWormholeConfig() { + super("ag_binder_of_worlds_wormhole", + true, + "em_adventurers_guild,290.5,123,302.5,90,0", + "binder_of_worlds_lair.yml", + Wormhole.WormholeStyle.CRYSTAL); + setBlindPlayer(true); + setLocation1Text("&5『Binder Of Worlds』 &5Lvl 200"); + setParticleColor(0x9600FF); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGCatacombsWormholeConfig.java b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGCatacombsWormholeConfig.java new file mode 100644 index 000000000..6a0f29a0b --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGCatacombsWormholeConfig.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.wormholes.premade; + +import com.magmaguy.elitemobs.config.wormholes.WormholeConfigFields; +import com.magmaguy.elitemobs.wormhole.Wormhole; + +public class AGCatacombsWormholeConfig extends WormholeConfigFields { + public AGCatacombsWormholeConfig() { + super("ag_catacombs_wormhole", + true, + "em_adventurers_guild,296.5,98,296.5,98,0", + "catacombs_lair.yml", + Wormhole.WormholeStyle.CRYSTAL); + setBlindPlayer(true); + setLocation1Text("&7『Catacombs Lair』 &aLvl 10"); + setParticleColor(0x797979); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGColosseumWormholeConfig.java b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGColosseumWormholeConfig.java new file mode 100644 index 000000000..5789f54c1 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGColosseumWormholeConfig.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.wormholes.premade; + +import com.magmaguy.elitemobs.config.wormholes.WormholeConfigFields; +import com.magmaguy.elitemobs.wormhole.Wormhole; + +public class AGColosseumWormholeConfig extends WormholeConfigFields { + public AGColosseumWormholeConfig() { + super("ag_colosseum_wormhole", + true, + "em_adventurers_guild,296.5,103,308.5,-175,0", + "colosseum_lair.yml", + Wormhole.WormholeStyle.CRYSTAL); + setBlindPlayer(true); + setLocation1Text("&6『Colosseum Minidungeon』 &6Lvl 70"); + setParticleColor(0xFFB000); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGDarkCathedralWormholeConfig.java b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGDarkCathedralWormholeConfig.java new file mode 100644 index 000000000..db71d8838 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGDarkCathedralWormholeConfig.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.wormholes.premade; + +import com.magmaguy.elitemobs.config.wormholes.WormholeConfigFields; +import com.magmaguy.elitemobs.wormhole.Wormhole; + +public class AGDarkCathedralWormholeConfig extends WormholeConfigFields { + public AGDarkCathedralWormholeConfig() { + super("ag_dark_cathedral_wormhole", + true, + "em_adventurers_guild,290.5,101.5,293.5,-40,0", + "dark_cathedral_lair.yml", + Wormhole.WormholeStyle.CUBE); + setBlindPlayer(true); + setLocation1Text("&0『Dark Cathedral Lair』 &6Lvl 40"); + setParticleColor(0x000000); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGDarkSpireWormholeConfig.java b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGDarkSpireWormholeConfig.java new file mode 100644 index 000000000..12a6b673b --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGDarkSpireWormholeConfig.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.wormholes.premade; + +import com.magmaguy.elitemobs.config.wormholes.WormholeConfigFields; +import com.magmaguy.elitemobs.wormhole.Wormhole; + +public class AGDarkSpireWormholeConfig extends WormholeConfigFields { + public AGDarkSpireWormholeConfig() { + super("ag_dark_spire_wormhole", + true, + "em_adventurers_guild,284.5,105,296.5,0,0", + "dark_spire_minidungeon.yml", + Wormhole.WormholeStyle.CUBE); + setBlindPlayer(true); + setLocation1Text("&0『Dark Spire Minidungeon』 &cLvls 100-120"); + setParticleColor(0x000000); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGFireworksWormholeConfig.java b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGFireworksWormholeConfig.java new file mode 100644 index 000000000..712f65478 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGFireworksWormholeConfig.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.wormholes.premade; + +import com.magmaguy.elitemobs.config.wormholes.WormholeConfigFields; +import com.magmaguy.elitemobs.wormhole.Wormhole; + +public class AGFireworksWormholeConfig extends WormholeConfigFields { + public AGFireworksWormholeConfig() { + super("ag_fireworks_wormhole", + true, + "em_adventurers_guild,296.5,99,308.5,-174,0", + "fireworks_lair.yml", + Wormhole.WormholeStyle.CRYSTAL); + setBlindPlayer(true); + setLocation1Text("&6『Fireworks Lair』 &aLvl 20"); + setParticleColor(0xFFE100); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGHallosseumWormholeConfig.java b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGHallosseumWormholeConfig.java new file mode 100644 index 000000000..9b11d68a8 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGHallosseumWormholeConfig.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.wormholes.premade; + +import com.magmaguy.elitemobs.config.wormholes.WormholeConfigFields; +import com.magmaguy.elitemobs.wormhole.Wormhole; + +public class AGHallosseumWormholeConfig extends WormholeConfigFields { + public AGHallosseumWormholeConfig() { + super("ag_hallosseum_wormhole", + true, + "em_adventurers_guild,281.5,100.5,302.5,-46,0", + "hallosseum_lair.yml", + Wormhole.WormholeStyle.CRYSTAL); + setBlindPlayer(true); + setLocation1Text("&4『Hallosseum Lair』 &aLvl 30"); + setParticleColor(0x680000); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGInvasionWormholeConfig.java b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGInvasionWormholeConfig.java new file mode 100644 index 000000000..0a2d8ae28 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGInvasionWormholeConfig.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.wormholes.premade; + +import com.magmaguy.elitemobs.config.wormholes.WormholeConfigFields; +import com.magmaguy.elitemobs.wormhole.Wormhole; + +public class AGInvasionWormholeConfig extends WormholeConfigFields { + public AGInvasionWormholeConfig() { + super("ag_invasion_wormhole", + true, + "em_adventurers_guild,284.5,101,296.5,0,0", + "invasion_minidungeon.yml", + Wormhole.WormholeStyle.CUBE); + setBlindPlayer(true); + setLocation1Text("&8『Invasion Minidungeon』 &aLvls 35-45"); + setParticleColor(0x005600); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGNorthPoleWormholeConfig.java b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGNorthPoleWormholeConfig.java new file mode 100644 index 000000000..d56e1aef7 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGNorthPoleWormholeConfig.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.wormholes.premade; + +import com.magmaguy.elitemobs.config.wormholes.WormholeConfigFields; +import com.magmaguy.elitemobs.wormhole.Wormhole; + +public class AGNorthPoleWormholeConfig extends WormholeConfigFields { + public AGNorthPoleWormholeConfig() { + super("ag_north_pole_wormhole", + true, + "em_adventurers_guild,299.5,102.5,302.5,-133,0", + "north_pole_minidungeon.yml", + Wormhole.WormholeStyle.CUBE); + setBlindPlayer(true); + setLocation1Text("&f『North Pole Minidungeon』 &6Lvls 55-60"); + setParticleColor(0xFFFFFF); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGOasisWormholeConfig.java b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGOasisWormholeConfig.java new file mode 100644 index 000000000..2c5af8fbe --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGOasisWormholeConfig.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.wormholes.premade; + +import com.magmaguy.elitemobs.config.wormholes.WormholeConfigFields; +import com.magmaguy.elitemobs.wormhole.Wormhole; + +public class AGOasisWormholeConfig extends WormholeConfigFields { + public AGOasisWormholeConfig() { + super("ag_oasis_wormhole", + true, + "em_adventurers_guild,290.5,99.5,311.5,-133,0", + "oasis_adventure.yml", + Wormhole.WormholeStyle.ICOSAHEDRON); + setBlindPlayer(true); + setLocation1Text("&2『Oasis Adventure』 &aLvls 20-55"); + setParticleColor(0xFFFF00); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGPirateShipWormholeConfig.java b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGPirateShipWormholeConfig.java new file mode 100644 index 000000000..72306f2e6 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGPirateShipWormholeConfig.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.wormholes.premade; + +import com.magmaguy.elitemobs.config.wormholes.WormholeConfigFields; +import com.magmaguy.elitemobs.wormhole.Wormhole; + +public class AGPirateShipWormholeConfig extends WormholeConfigFields { + public AGPirateShipWormholeConfig() { + super("ag_pirate_ship_wormhole", + true, + "em_adventurers_guild,299.5,98.5,302.5,133,0", + "pirate_ship_minidungeon.yml", + Wormhole.WormholeStyle.CUBE); + setBlindPlayer(true); + setLocation1Text("&9『Pirate Ship Minidungeon』 &aLvls 10-20"); + setParticleColor(0x000077); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGPrimisWormholeConfig.java b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGPrimisWormholeConfig.java new file mode 100644 index 000000000..110411925 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGPrimisWormholeConfig.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.config.wormholes.premade; + +import com.magmaguy.elitemobs.config.wormholes.WormholeConfigFields; +import com.magmaguy.elitemobs.wormhole.Wormhole; + +public class AGPrimisWormholeConfig extends WormholeConfigFields { + public AGPrimisWormholeConfig() { + super("ag_primis_wormhole", + true, + "em_adventurers_guild,290.5,98,302.5,109,0", + "primis_adventure.yml", + Wormhole.WormholeStyle.ICOSAHEDRON); + setBlindPlayer(true); + setLocation1Text("&2『Primis Adventure』 &aLvls 0-20"); + setParticleColor(0x008000); + setSizeMultiplier(2); + } +} + diff --git a/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGRuinsWormholeConfig.java b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGRuinsWormholeConfig.java new file mode 100644 index 000000000..ea4fa6e5e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGRuinsWormholeConfig.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.wormholes.premade; + +import com.magmaguy.elitemobs.config.wormholes.WormholeConfigFields; +import com.magmaguy.elitemobs.wormhole.Wormhole; + +public class AGRuinsWormholeConfig extends WormholeConfigFields { + public AGRuinsWormholeConfig() { + super("ag_ruins_wormhole", + true, + "em_adventurers_guild,290.5,107.5,311.5,-135,0", + "the_ruins.yml", + Wormhole.WormholeStyle.CRYSTAL); + setBlindPlayer(true); + setLocation1Text("&8『Ruins Lair』 &cLvl 150"); + setParticleColor(0x141414); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGSewersWormholeConfig.java b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGSewersWormholeConfig.java new file mode 100644 index 000000000..f46e4f684 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGSewersWormholeConfig.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.wormholes.premade; + +import com.magmaguy.elitemobs.config.wormholes.WormholeConfigFields; +import com.magmaguy.elitemobs.wormhole.Wormhole; + +public class AGSewersWormholeConfig extends WormholeConfigFields { + public AGSewersWormholeConfig() { + super("ag_sewers_wormhole", + true, + "em_adventurers_guild,284.5,100,308.5,-90,0", + "sewers_minidungeon.yml", + Wormhole.WormholeStyle.CUBE); + setBlindPlayer(true); + setLocation1Text("&1『Sewers Minidungeon』 &aLvls 20-35"); + setParticleColor(0xCACBC); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGVampireManorWormholeConfig.java b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGVampireManorWormholeConfig.java new file mode 100644 index 000000000..dcd185766 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AGVampireManorWormholeConfig.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.config.wormholes.premade; + +import com.magmaguy.elitemobs.config.wormholes.WormholeConfigFields; +import com.magmaguy.elitemobs.wormhole.Wormhole; + +public class AGVampireManorWormholeConfig extends WormholeConfigFields { + public AGVampireManorWormholeConfig() { + super("ag_vampire_manor_wormhole", + true, + "em_adventurers_guild,290.5,105.5,293.5,45,0", + "vampire_manor.yml", + Wormhole.WormholeStyle.CUBE); + setBlindPlayer(true); + setLocation1Text("&4『Vampire Manor Lair』 &5Lvls 120-140"); + setParticleColor(0x6A0000); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AdventurersGuildWormholeConfig.java b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AdventurersGuildWormholeConfig.java new file mode 100644 index 000000000..cad85ed0e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/AdventurersGuildWormholeConfig.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.config.wormholes.premade; + +import com.magmaguy.elitemobs.config.wormholes.WormholeConfigFields; +import com.magmaguy.elitemobs.wormhole.Wormhole; + +public class AdventurersGuildWormholeConfig extends WormholeConfigFields { + public AdventurersGuildWormholeConfig() { + super("adventurers_guild_wormhole", + true, + "em_adventurers_guild,204.5,89,235.5,-89,0", + "your_world_here,0.5,64,0.5,0,0", + Wormhole.WormholeStyle.ICOSAHEDRON); + setBlindPlayer(true); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/TestWormholeConfig.java b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/TestWormholeConfig.java new file mode 100644 index 000000000..7ef00a0a0 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/config/wormholes/premade/TestWormholeConfig.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.config.wormholes.premade; + +import com.magmaguy.elitemobs.config.wormholes.WormholeConfigFields; +import com.magmaguy.elitemobs.wormhole.Wormhole; + +public class TestWormholeConfig extends WormholeConfigFields { + public TestWormholeConfig() { + super("test_wormhole", + false, + "em_adventurers_guild,213.5,88,239.5,0,0", + "em_adventurers_guild,276.5,92,232.5,0,0", + Wormhole.WormholeStyle.CUBE); + setBlindPlayer(true); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/dungeons/Minidungeon.java b/src/main/java/com/magmaguy/elitemobs/dungeons/Minidungeon.java new file mode 100644 index 000000000..b8bb27ad1 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/dungeons/Minidungeon.java @@ -0,0 +1,599 @@ +package com.magmaguy.elitemobs.dungeons; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.internal.NewMinidungeonRelativeBossLocationEvent; +import com.magmaguy.elitemobs.api.internal.RemovalReason; +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfig; +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import com.magmaguy.elitemobs.config.customtreasurechests.CustomTreasureChestConfigFields; +import com.magmaguy.elitemobs.config.customtreasurechests.CustomTreasureChestsConfig; +import com.magmaguy.elitemobs.config.dungeonpackager.DungeonPackagerConfigFields; +import com.magmaguy.elitemobs.dungeons.worlds.MinidungeonWorldLoader; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import com.magmaguy.elitemobs.mobconstructor.custombosses.RegionalBossEntity; +import com.magmaguy.elitemobs.powerstances.GenericRotationMatrixMath; +import com.magmaguy.elitemobs.thirdparty.worldguard.WorldGuardCompatibility; +import com.magmaguy.elitemobs.treasurechest.TreasureChest; +import com.magmaguy.elitemobs.utils.EventCaller; +import com.magmaguy.elitemobs.utils.InfoMessage; +import com.magmaguy.elitemobs.utils.SpigotMessage; +import com.magmaguy.elitemobs.utils.WarningMessage; +import lombok.Getter; +import lombok.Setter; +import net.md_5.bungee.api.chat.ClickEvent; +import net.md_5.bungee.api.chat.HoverEvent; +import net.md_5.bungee.api.chat.TextComponent; +import net.md_5.bungee.api.chat.hover.content.Text; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.*; + +public class Minidungeon { + + //Stores the filename and an instance of this object + @Getter + private static final Map minidungeons = new HashMap<>(); + @Getter + private final boolean bossesDownloaded = true; + @Getter + private final DungeonPackagerConfigFields dungeonPackagerConfigFields; + @Getter + @Setter + private boolean isDownloaded; + @Getter + @Setter + private boolean isInstalled; + @Getter + private RelativeDungeonLocations relativeBossLocations; + @Getter + private RelativeDungeonLocations relativeTreasureChestLocations; + @Getter + private RealDungeonLocations realDungeonLocations; + @Getter + private World world; + @Getter + private World wormholeWorld = null; + @Getter + private Location teleportLocation; + @Getter + private Integer lowestTier; + @Getter + private Integer highestTier; + @Getter + private Integer regionalBossCount = 0; + @Getter + @Setter + private boolean outOfDate = false; + + public Minidungeon(DungeonPackagerConfigFields dungeonPackagerConfigFields) { + minidungeons.put(dungeonPackagerConfigFields.getFilename(), this); + this.dungeonPackagerConfigFields = dungeonPackagerConfigFields; + regionalBossCount = 0; + if (dungeonPackagerConfigFields.getDungeonLocationType() == null) { + new WarningMessage("Dungeon " + dungeonPackagerConfigFields.getFilename() + " has an invalid location type! It will not boot."); + return; + } + switch (dungeonPackagerConfigFields.getDungeonLocationType()) { + case WORLD: + initializeWorldBasedMinidungeon(); + break; + case SCHEMATIC: + initializeSchematicBasedMinidungeon(); + break; + default: + new WarningMessage("Minidungeon " + dungeonPackagerConfigFields.getFilename() + " does not have a valid dungeonLocationType! Valid types: schematic, world"); + this.isDownloaded = this.isInstalled = false; + break; + } + + } + + private void initializeWormholeWorld() { + if (dungeonPackagerConfigFields.getWormholeWorldName() != null && + !dungeonPackagerConfigFields.getWormholeWorldName().isEmpty() && + Bukkit.getWorld(dungeonPackagerConfigFields.getWormholeWorldName()) == null) { + wormholeWorld = MinidungeonWorldLoader.loadWorld(this, dungeonPackagerConfigFields.getWormholeWorldName(), dungeonPackagerConfigFields.getEnvironment()); + if (wormholeWorld != null) + WorldGuardCompatibility.protectWorldMinidugeonArea(Objects.requireNonNull(wormholeWorld).getSpawnLocation(), this); + } + } + + private void initializeWorldBasedMinidungeon() { + if (dungeonPackagerConfigFields.getWorldName() == null || dungeonPackagerConfigFields.getWorldName().isEmpty()) { + this.isDownloaded = this.isInstalled = false; + new WarningMessage("Minidungeon " + dungeonPackagerConfigFields.getFilename() + " does not have a valid world name in the dungeon packager!"); + return; + } + + //Check if the world's been loaded + if (Bukkit.getWorld(dungeonPackagerConfigFields.getWorldName()) != null) { + this.isDownloaded = this.isInstalled = true; + world = Bukkit.getWorld(dungeonPackagerConfigFields.getWorldName()); + setWorldSpawn(); + quantifyWorldBosses(); + return; + } + + //Since the world isn't loaded, check if it should be + this.isInstalled = dungeonPackagerConfigFields.isEnabled(); + + //Check if the world's been downloaded + isDownloaded = Files.exists(Paths.get(Bukkit.getWorldContainer() + File.separator + dungeonPackagerConfigFields.getWorldName())); + + if (isDownloaded && isInstalled) { + world = MinidungeonWorldLoader.loadWorld(this); + initializeWormholeWorld(); + } + + if (world != null) + setWorldSpawn(); + } + + private void setWorldSpawn() { + teleportLocation = world.getSpawnLocation().clone().add(dungeonPackagerConfigFields.getTeleportPoint()); + if (dungeonPackagerConfigFields.getTeleportPoint() != null) + teleportLocation.add(dungeonPackagerConfigFields.getTeleportPoint()); + teleportLocation.setYaw((float) dungeonPackagerConfigFields.getTeleportPointPitch()); + teleportLocation.setPitch((float) dungeonPackagerConfigFields.getTeleportPointYaw()); + } + + private void initializeSchematicBasedMinidungeon() { + //If the configuration of the package is wrong + if (this.dungeonPackagerConfigFields.getSchematicName() == null || this.dungeonPackagerConfigFields.getSchematicName().isEmpty()) { + this.isDownloaded = false; + new WarningMessage("The minidungeon package " + this.dungeonPackagerConfigFields.getFilename() + " does not have a valid schematic file name!"); + } + + //If worldedit isn't installed, the checks can't be continued + if (!Bukkit.getPluginManager().isPluginEnabled("WorldEdit")) { + this.isDownloaded = false; + return; + } + + try { + if (Bukkit.getPluginManager().isPluginEnabled("FastAsyncWorldEdit")) + this.isDownloaded = Files.exists(Paths.get(MetadataHandler.PLUGIN.getDataFolder().getParentFile().getAbsolutePath() + + File.separator + "FastAsyncWorldEdit" + File.separator + "schematics" + File.separator + dungeonPackagerConfigFields.getSchematicName())); + else + this.isDownloaded = Files.exists(Paths.get(MetadataHandler.PLUGIN.getDataFolder().getParentFile().getAbsolutePath() + + File.separator + "WorldEdit" + File.separator + "schematics" + File.separator + dungeonPackagerConfigFields.getSchematicName())); + + } catch (Exception ex) { + this.isDownloaded = false; + } + + if (dungeonPackagerConfigFields.getAnchorPoint() != null) { + this.isInstalled = true; + initializeWormholeWorld(); + } + + } + + /** + * Used to rotate any relative coordinates for a dungeon - transitive blocks / custom reinforcements + */ + public Location getRotatedFinalLocation(Location localAnchorPoint, Vector relativeCoordinate) { + return GenericRotationMatrixMath.rotateVectorYAxis( + dungeonPackagerConfigFields.getRotation(), + localAnchorPoint, + relativeCoordinate).toLocation(localAnchorPoint.getWorld()); + } + + public void commitLocations() { + this.realDungeonLocations.commitLocations(); + } + + public void uncommitLocations() { + this.realDungeonLocations.uncommitLocations(this); + } + + public boolean initializeRelativeLocationAddition(CustomBossesConfigFields customBossesConfigFields, Location location) { + Location relativeLocation = addRelativeLocation(customBossesConfigFields, location); + NewMinidungeonRelativeBossLocationEvent event = new NewMinidungeonRelativeBossLocationEvent( + this, + relativeLocation, + dungeonPackagerConfigFields.getAnchorPoint().clone().add(Objects.requireNonNull(relativeLocation)), + customBossesConfigFields); + new EventCaller(event); + if (event.isCancelled()) return false; + + + RegionalBossEntity.createPermanentRegionalBossEntity(customBossesConfigFields, location); + + return true; + } + + private Location addRelativeLocation(CustomBossesConfigFields customBossesConfigFields, Location location) { + if (dungeonPackagerConfigFields.getAnchorPoint() == null) + return null; + Location relativeLocation = location.clone().subtract(dungeonPackagerConfigFields.getAnchorPoint()); + if (dungeonPackagerConfigFields.addRelativeBossLocation(customBossesConfigFields, relativeLocation)) + return relativeLocation; + else + return null; + } + + public void removeRelativeLocation(RegionalBossEntity regionalBossEntity) { + RealDungeonLocations.RealDungeonLocation realDungeonLocation = null; + for (RealDungeonLocations.RealDungeonLocation iterated : realDungeonLocations.locations) { + if (iterated.regionalBossEntity != null && iterated.regionalBossEntity.equals(regionalBossEntity)) { + realDungeonLocation = iterated; + break; + } + } + + if (realDungeonLocation == null) { + new WarningMessage("Failed to unregister Regional Boss location from the dungeon packager!"); + return; + } + + dungeonPackagerConfigFields.removeRelativeBossLocation(regionalBossEntity.getCustomBossesConfigFields(), realDungeonLocation.relativeLocation); + RealDungeonLocations.RealDungeonLocation finalRealDungeonLocation = realDungeonLocation; + relativeBossLocations.locations.removeIf(relativeDungeonLocation -> relativeDungeonLocation.location.equals(finalRealDungeonLocation.relativeLocation) && + relativeDungeonLocation.customBossesConfigFields.equals(regionalBossEntity.getCustomBossesConfigFields())); + realDungeonLocations.locations.remove(realDungeonLocation); + new InfoMessage("Correctly unregistered entry from dungeon packager!"); + + } + + public Location addRelativeTreasureChest(String customTreasureChestConfigString, Location location, Player player) { + if (dungeonPackagerConfigFields.getAnchorPoint() == null) + return null; + CustomTreasureChestConfigFields customTreasureChestConfigFields = CustomTreasureChestsConfig.getCustomTreasureChestConfigFields().get(customTreasureChestConfigString); + + if (customTreasureChestConfigFields == null) return null; + + Location relativeLocation = location.clone().subtract(dungeonPackagerConfigFields.getAnchorPoint()); + CustomTreasureChestsConfig.addTreasureChestEntry(player, customTreasureChestConfigString); + + if (dungeonPackagerConfigFields.addRelativeTreasureChests(customTreasureChestConfigFields, relativeLocation)) + return relativeLocation; + else + return null; + } + + public void buttonToggleBehavior(Player player) { + //Cases where the map was not downloaded is already handled in SetupMenu since all it needs to do is post a download link + switch (this.dungeonPackagerConfigFields.getDungeonLocationType()) { + case WORLD: + worldButtonToggleBehavior(player); + break; + case SCHEMATIC: + schematicButtonToggleBehavior(player); + break; + default: + new WarningMessage("Invalid dungeon location type for Minidungeon " + dungeonPackagerConfigFields.getFilename() + " !"); + } + } + + private void worldButtonToggleBehavior(Player player) { + world = Bukkit.getWorld(dungeonPackagerConfigFields.getWorldName()); + if (world == null) { + loadWorld(player); + initializeWormholeWorld(); + if (world != null) + dungeonPackagerConfigFields.setEnabled(true); + } else { + unloadWorld(player); + dungeonPackagerConfigFields.setEnabled(false); + } + } + + private void loadWorld(Player player) { + try { + world = MinidungeonWorldLoader.loadWorld(this); + if (world == null) { + player.sendMessage("Failed to get world " + this.dungeonPackagerConfigFields.getWorldName() + " . Can not complete installation correctly."); + return; + } + WorldGuardCompatibility.protectWorldMinidugeonArea(world.getSpawnLocation(), this); + player.teleport(world.getSpawnLocation()); + player.sendMessage("Minidungeon " + dungeonPackagerConfigFields.getWorldName() + + " has been loaded! The world is now loaded and the regional bosses are up."); + player.sendMessage(ChatColorConverter.convert("&cYou might want to do &a/em reload &cto fix the initial spawns, skins and wormholes!")); + if (dungeonPackagerConfigFields.isHasCustomModels()) + if (!Bukkit.getPluginManager().isPluginEnabled("ModelEngine")) { + player.sendMessage(ChatColorConverter.convert("&c[EliteMobs] The dungeon you just installed has custom models, but you do not have Model Engine! Download it here if you want to use Custom Models: https://www.spigotmc.org/resources/conxeptworks-model-engine%E2%80%94ultimate-custom-entity-model-manager-1-14-1-18-1.79477/")); + player.sendMessage(ChatColorConverter.convert("&c[EliteMobs] Please note that currently only version 2.4.0 is supported!")); + } else + player.spigot().sendMessage(SpigotMessage.commandHoverMessage( + ChatColorConverter.convert("&8[EliteMobs] &2The dungeon you just installed has Custom Models! " + + "&2Click here to generate the EliteMobs resource pack for those models!"), + "Clicking will run the command /em generateresourcepack", + "/em generateresourcepack")); + isInstalled = true; + setWorldSpawn(); + } catch (Exception exception) { + new WarningMessage("Warning: Failed to load the " + dungeonPackagerConfigFields.getWorldName() + " world!"); + player.sendMessage("Warning: Failed to load the " + dungeonPackagerConfigFields.getWorldName() + " world!"); + exception.printStackTrace(); + } + if (isInstalled) + quantifyWorldBosses(); + } + + private void unloadWorld(Player player) { + try { + for (Player iteratedPlayer : Bukkit.getOnlinePlayers()) + if (iteratedPlayer.getWorld().getName().equals(dungeonPackagerConfigFields.getWorldName())) { + player.sendMessage("[EliteMobs] Failed to unload Minidungeon because at least one player is in the world " + + dungeonPackagerConfigFields.getWorldName()); + return; + } + for (RegionalBossEntity regionalBossEntity : RegionalBossEntity.getRegionalBossEntitySet()) + if (regionalBossEntity.getSpawnLocation().getWorld() == world) + regionalBossEntity.worldUnload(); + MinidungeonWorldLoader.unloadWorld(this); + player.sendMessage("Minidugeon " + dungeonPackagerConfigFields.getWorldName() + + " has been unloaded! The world is now unloaded. The world is now unloaded and the regional bosses are down."); + isInstalled = false; + if (wormholeWorld != null) Bukkit.unloadWorld(wormholeWorld, true); + } catch (Exception exception) { + player.sendMessage("Warning: Failed to unload the " + dungeonPackagerConfigFields.getWorldName() + " world!"); + } + regionalBossCount = 0; + } + + private void schematicButtonToggleBehavior(Player player) { + if (!isInstalled) { + installSchematicMinidungeon(player); + } else { + uninstallSchematicMinidungeon(player); + } + } + + private void installSchematicMinidungeon(Player player) { + player.performCommand("schematic load " + dungeonPackagerConfigFields.getSchematicName()); + new BukkitRunnable() { + @Override + public void run() { + for (int i = 0; i < 20; i++) + player.sendMessage(""); + player.sendMessage(ChatColorConverter.convert("&2-------------------------------------------------")); + player.sendMessage(ChatColorConverter.convert("&7[EliteMobs] &2Ready to install " + dungeonPackagerConfigFields.getDungeonSizeCategory().toString().toLowerCase() + "!")); + TextComponent pasteString = new TextComponent(ChatColorConverter.convert("&aClick here to place the &lbuilding and bosses &awhere you're standing!")); + pasteString.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/em setup minidungeon " + dungeonPackagerConfigFields.getFilename())); + pasteString.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text(ChatColorConverter.convert("&2Click me!")))); + TextComponent noPasteString = new TextComponent(ChatColorConverter.convert("&4&lOr &4click here to &lonly set the bosses with no building&4!")); + noPasteString.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/em setup minidungeonNoPaste " + dungeonPackagerConfigFields.getFilename())); + noPasteString.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text(ChatColorConverter.convert("&cOnly click if you're already standing at the bulding's anchor point!")))); + player.spigot().sendMessage(pasteString); + player.spigot().sendMessage(noPasteString); + player.sendMessage(ChatColorConverter.convert("&2-------------------------------------------------")); + } + }.runTaskLater(MetadataHandler.PLUGIN, 20); + initializeWormholeWorld(); + } + + public void finalizeMinidungeonInstallation(Player player, boolean pastedSchematic) { + dungeonPackagerConfigFields.setEnabled(true, player.getLocation()); + this.relativeBossLocations = new RelativeDungeonLocations(dungeonPackagerConfigFields.getRelativeBossLocations(), true); + this.relativeTreasureChestLocations = new RelativeDungeonLocations(dungeonPackagerConfigFields.getRelativeTreasureChestLocations(), false); + this.realDungeonLocations = new RealDungeonLocations(); + commitLocations(); + this.isInstalled = true; + + if (dungeonPackagerConfigFields.isProtect()) { + Location realCorner1 = getRotatedFinalLocation(dungeonPackagerConfigFields.getAnchorPoint(), dungeonPackagerConfigFields.getCorner1()); + Location realCorner2 = getRotatedFinalLocation(dungeonPackagerConfigFields.getAnchorPoint(), dungeonPackagerConfigFields.getCorner2()); + WorldGuardCompatibility.defineMinidungeon(realCorner1, realCorner2, dungeonPackagerConfigFields.getAnchorPoint(), dungeonPackagerConfigFields.getSchematicName(), this); + } + + teleportLocation = getRotatedFinalLocation(dungeonPackagerConfigFields.getAnchorPoint(), dungeonPackagerConfigFields.getTeleportPoint()); + + for (int i = 0; i < 20; i++) + player.sendMessage(""); + + player.sendMessage(ChatColorConverter.convert("&2" + dungeonPackagerConfigFields.getName() + " installed!")); + TextComponent setupOptions = new TextComponent(ChatColorConverter.convert("&4Click here to uninstall!")); + if (pastedSchematic) + setupOptions.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/em setup unminidungeon " + dungeonPackagerConfigFields.getFilename())); + else + setupOptions.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/em setup unminidungeonNoPaste " + dungeonPackagerConfigFields.getFilename())); + player.spigot().sendMessage(setupOptions); + quantifySchematicBosses(true); + } + + public void uninstallSchematicMinidungeon(Player player) { + if (dungeonPackagerConfigFields.isProtect() && Bukkit.getPluginManager().isPluginEnabled("WorldGuard")) + WorldGuardCompatibility.removeMinidungeon( + dungeonPackagerConfigFields.getSchematicName(), + dungeonPackagerConfigFields.getAnchorPoint()); + uncommitLocations(); + dungeonPackagerConfigFields.setEnabled(false, player.getLocation()); + this.isInstalled = false; + this.regionalBossCount = 0; + if (wormholeWorld != null) Bukkit.unloadWorld(wormholeWorld, true); + player.sendMessage("[EliteMobs] EliteMobs attempted to uninstall a minidungeon. Further WorldEdit commands might be required to remove the physical structure of the minidungeon."); + } + + public void quantifySchematicBosses(boolean freshInstall) { + if (!isInstalled) return; + if (!freshInstall) { + this.relativeBossLocations = new RelativeDungeonLocations(dungeonPackagerConfigFields.getRelativeBossLocations(), true); + this.relativeTreasureChestLocations = new RelativeDungeonLocations(dungeonPackagerConfigFields.getRelativeTreasureChestLocations(), false); + this.realDungeonLocations = new RealDungeonLocations(); + } + this.teleportLocation = getRotatedFinalLocation(dungeonPackagerConfigFields.getAnchorPoint(), dungeonPackagerConfigFields.getTeleportPoint()); + for (String regionalBossLocations : dungeonPackagerConfigFields.getRelativeBossLocations()) { + String bossFileName = regionalBossLocations.split(":")[0]; + CustomBossesConfigFields customBossesConfigFields = CustomBossesConfig.getCustomBoss(bossFileName); + quantificationFilter(customBossesConfigFields); + RegionalBossEntity.getRegionalBossEntities(customBossesConfigFields).forEach((regionalBossEntity -> regionalBossEntity.setMinidungeon(this))); + if (customBossesConfigFields != null && customBossesConfigFields.isRegionalBoss()) + regionalBossCount++; + } + } + + public void quantifyWorldBosses() { + if (!isInstalled) return; + if (world == null) return; + for (RegionalBossEntity regionalBossEntity : RegionalBossEntity.getRegionalBossEntitySet()) + if (Objects.equals(regionalBossEntity.getWorldName(), world.getName())) { + regionalBossEntity.setMinidungeon(this); + regionalBossCount++; + quantificationFilter(regionalBossEntity.getCustomBossesConfigFields()); + } + } + + private void quantificationFilter(CustomBossesConfigFields customBossesConfigFields) { + try { + int level = customBossesConfigFields.getLevel(); + lowestTier = lowestTier == null ? level : lowestTier < level ? lowestTier : level; + highestTier = highestTier == null ? level : highestTier > level ? highestTier : level; + } catch (Exception ex) { + } + } + + /** + * This can only exist if the anchor point actually exists + */ + public class RealDungeonLocations { + ArrayList locations = new ArrayList<>(); + + public RealDungeonLocations() { + for (RelativeDungeonLocations.RelativeDungeonLocation relativeDungeonLocation : relativeBossLocations.locations) + if (dungeonPackagerConfigFields.getRotation() == 0F) + locations.add( + new RealDungeonLocation(relativeDungeonLocation.location, + dungeonPackagerConfigFields.getAnchorPoint().clone().add(relativeDungeonLocation.location), + relativeDungeonLocation.customBossesConfigFields)); + else { + locations.add( + new RealDungeonLocation(relativeDungeonLocation.location, + getRotatedFinalLocation(dungeonPackagerConfigFields.getAnchorPoint(), relativeDungeonLocation.location), + relativeDungeonLocation.customBossesConfigFields)); + } + + for (RelativeDungeonLocations.RelativeDungeonLocation relativeDungeonLocation : relativeTreasureChestLocations.locations) + if (dungeonPackagerConfigFields.getRotation() == 0F) + locations.add( + new RealDungeonLocation(relativeDungeonLocation.location, + dungeonPackagerConfigFields.getAnchorPoint().clone().add(relativeDungeonLocation.location), + relativeDungeonLocation.customTreasureChestConfigFields)); + else + locations.add( + new RealDungeonLocation(relativeDungeonLocation.location, + getRotatedFinalLocation(dungeonPackagerConfigFields.getAnchorPoint(), relativeDungeonLocation.location.add(new Vector(0.5, 0.5, 0.5))), + relativeDungeonLocation.customTreasureChestConfigFields)); + } + + /** + * This runs when an admin tries to install a dungeon + */ + public void commitLocations() { + for (RealDungeonLocation realDungeonLocation : locations) + if (realDungeonLocation.customBossesConfigFields != null) + realDungeonLocation.regionalBossEntity = RegionalBossEntity.createPermanentRegionalBossEntity(realDungeonLocation.customBossesConfigFields, realDungeonLocation.location); + else if (realDungeonLocation.customTreasureChestConfigFields != null) + realDungeonLocation.treasureChest = CustomTreasureChestsConfig.addTreasureChestEntry(realDungeonLocation.location, realDungeonLocation.customTreasureChestConfigFields.getFilename()); + } + + public void uncommitLocations(Minidungeon minidungeon) { + Collection eliteEntities = new ArrayList<>(EntityTracker.getEliteMobEntities().values()); + for (EliteEntity eliteEntity : eliteEntities) + if (eliteEntity instanceof CustomBossEntity && ((CustomBossEntity) eliteEntity).getMinidungeon() == minidungeon) { + new InfoMessage("Removed " + eliteEntity.getName()); + eliteEntity.remove(RemovalReason.REMOVE_COMMAND); + } + Collection treasureChests = new ArrayList<>(TreasureChest.getTreasureChestHashMap().values()); + for (TreasureChest treasureChest : treasureChests) { + treasureChest.removeTreasureChest(); + } + } + + public class RealDungeonLocation { + private final Location location; + private final Vector relativeLocation; + private CustomBossesConfigFields customBossesConfigFields; + private CustomTreasureChestConfigFields customTreasureChestConfigFields; + private RegionalBossEntity regionalBossEntity; + private TreasureChest treasureChest; + + public RealDungeonLocation(Vector relativeLocation, Location location, CustomBossesConfigFields customBossesConfigFields) { + this.relativeLocation = relativeLocation; + this.location = location; + this.customBossesConfigFields = customBossesConfigFields; + if (isInstalled) + this.regionalBossEntity = RegionalBossEntity.getRegionalBoss(customBossesConfigFields, location); + } + + public RealDungeonLocation(Vector relativeLocation, Location location, CustomTreasureChestConfigFields customTreasureChestConfigFields) { + this.relativeLocation = relativeLocation; + this.location = location; + this.customTreasureChestConfigFields = customTreasureChestConfigFields; + if (isInstalled) + this.treasureChest = TreasureChest.getTreasureChest(location); + } + } + } + + /** + * This stores the relative locations of the dungeon, meaning the locations relative to an anchor point. The locations + * do not take the rotation into account, that is done when converting for the real locations + */ + public class RelativeDungeonLocations { + private final ArrayList locations = new ArrayList<>(); + @Getter + private int bossCount = 0; + + public RelativeDungeonLocations(List rawStrings, boolean boss) { + for (String rawString : rawStrings) { + if (rawString.isEmpty()) continue; + locations.add(new RelativeDungeonLocation(rawString, boss)); + bossCount++; + } + } + + public class RelativeDungeonLocation { + CustomBossesConfigFields customBossesConfigFields; + CustomTreasureChestConfigFields customTreasureChestConfigFields; + Vector location; + + public RelativeDungeonLocation(String rawLocationString, boolean boss) { + try { + if (boss) + customBossesConfigFields = CustomBossesConfig.getCustomBoss(rawLocationString.split(":")[0]); + else + customTreasureChestConfigFields = CustomTreasureChestsConfig.getCustomTreasureChestConfigFields().get(rawLocationString.split(":")[0]); + this.location = new Vector( + //no world location for relative positioning + //x + vectorGetter(rawLocationString, 0), + //y + vectorGetter(rawLocationString, 1), + //z + vectorGetter(rawLocationString, 2)); + if (customBossesConfigFields == null && customTreasureChestConfigFields == null) { + //todo: figure this issue out, not sure if misfiring + //new WarningMessage("Failed to correctly parse line " + rawLocationString + " for minidungeon " + dungeonPackagerConfigFields.getFilename()); + } + } catch (Exception ex) { + new WarningMessage("Failed to generate dungeon from raw " + rawLocationString); + ex.printStackTrace(); + } + } + + private double vectorGetter(String rawLocationString, int position) { + try { + return Double.parseDouble(rawLocationString.split(":")[1].split(",")[position]); + } catch (Exception e) { + new WarningMessage("Failed to parse relative location " + rawLocationString + " for minidungeon " + dungeonPackagerConfigFields.getFilename()); + return 0; + } + } + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/dungeons/worlds/MinidungeonWorldLoader.java b/src/main/java/com/magmaguy/elitemobs/dungeons/worlds/MinidungeonWorldLoader.java new file mode 100644 index 000000000..58d48e445 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/dungeons/worlds/MinidungeonWorldLoader.java @@ -0,0 +1,49 @@ +package com.magmaguy.elitemobs.dungeons.worlds; + +import com.magmaguy.elitemobs.dungeons.Minidungeon; +import com.magmaguy.elitemobs.utils.InfoMessage; +import com.magmaguy.elitemobs.utils.WarningMessage; +import org.bukkit.Bukkit; +import org.bukkit.Difficulty; +import org.bukkit.World; +import org.bukkit.WorldCreator; + +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Paths; + +public class MinidungeonWorldLoader { + public static World loadWorld(Minidungeon minidungeon) { + return loadWorld(minidungeon, minidungeon.getDungeonPackagerConfigFields().getWorldName(), minidungeon.getDungeonPackagerConfigFields().getEnvironment()); + } + + public static World loadWorld(Minidungeon minidungeon, String worldName, World.Environment environment) { + File folder = new File(Bukkit.getWorldContainer().getAbsolutePath()); + + new InfoMessage("Trying to load Minidungeon world " + worldName); + if (!Files.exists(Paths.get(folder.getAbsolutePath() + "/" + worldName))) + return null; + new InfoMessage("Detected Minidungeon world " + worldName); + try { + WorldCreator worldCreator = new WorldCreator(worldName); + worldCreator.environment(environment); + World world = Bukkit.createWorld(worldCreator); + if (world != null) + world.setKeepSpawnInMemory(false); + new InfoMessage("Minidungeons world " + worldName + " was loaded successfully!"); + minidungeon.setInstalled(true); + world.setDifficulty(Difficulty.HARD); + return world; + } catch (Exception exception) { + new WarningMessage("Failed to load Minidungeon world " + worldName + " !"); + exception.printStackTrace(); + } + + return null; + } + + public static void unloadWorld(Minidungeon minidungeon) { + Bukkit.unloadWorld(minidungeon.getWorld(), true); + if (minidungeon.getWormholeWorld() != null) Bukkit.unloadWorld(minidungeon.getWormholeWorld(), true); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/economy/EconomyHandler.java b/src/main/java/com/magmaguy/elitemobs/economy/EconomyHandler.java index 20d81626e..d0a127f1f 100644 --- a/src/main/java/com/magmaguy/elitemobs/economy/EconomyHandler.java +++ b/src/main/java/com/magmaguy/elitemobs/economy/EconomyHandler.java @@ -1,24 +1,7 @@ -/* - * 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 . - */ - package com.magmaguy.elitemobs.economy; -import com.magmaguy.elitemobs.config.PlayerMoneyData; -import com.magmaguy.elitemobs.playerdata.PlayerData; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; +import com.magmaguy.elitemobs.playerdata.database.PlayerData; +import com.magmaguy.elitemobs.utils.Round; import java.util.UUID; @@ -27,84 +10,46 @@ */ public class EconomyHandler { - private static PlayerMoneyData playerMoneyData = new PlayerMoneyData(); - public static void addCurrency(UUID user, double amount) { - - if (!checkUserExists(user)) createUser(user); - - PlayerData.playerCurrency.put(user, roundDecimals(checkCurrency(user) + amount)); - PlayerData.playerCurrencyChanged = true; - + if (VaultCompatibility.VAULT_ENABLED) { + VaultCompatibility.addVaultCurrency(user, amount); + return; + } + PlayerData.setCurrency(user, Round.twoDecimalPlaces(checkCurrency(user) + amount)); } public static void subtractCurrency(UUID user, double amount) { - - if (!checkUserExists(user)) createUser(user); - - PlayerData.playerCurrency.put(user, roundDecimals(checkCurrency(user) - amount)); - PlayerData.playerCurrencyChanged = true; - + if (VaultCompatibility.VAULT_ENABLED) { + VaultCompatibility.subtractCurrency(user, amount); + return; + } + PlayerData.setCurrency(user, Round.twoDecimalPlaces(checkCurrency(user) - amount)); } public static void setCurrency(UUID user, double amount) { - if (!checkUserExists(user)) createUser(user); + if (VaultCompatibility.VAULT_ENABLED) { + VaultCompatibility.setCurrency(user, amount); + return; + } - PlayerData.playerCurrency.put(user, roundDecimals(amount)); - PlayerData.playerCurrencyChanged = true; + PlayerData.setCurrency(user, Round.twoDecimalPlaces(amount)); } public static double checkCurrency(UUID user) { + if (VaultCompatibility.VAULT_ENABLED) + return VaultCompatibility.checkCurrency(user); - if (!checkUserExists(user)) - createUser(user); - - return PlayerData.playerCurrency.get(user); - + return PlayerData.getCurrency(user); } - private static void createUser(UUID uuid) { - - PlayerData.playerCurrency.put(uuid, 0.0); - PlayerData.playerCurrencyChanged = true; - - } - - private static boolean checkUserExists(UUID uuid) { - - checkUserIsCached(uuid); - return PlayerData.playerCurrency.containsKey(uuid); - - } - - private static void checkUserIsCached(UUID uuid) { - - boolean playerIsOnline = false; - - for (Player player : Bukkit.getOnlinePlayers()) - if(player.getUniqueId().equals(uuid)){ - playerIsOnline = true; - break; - } - - - if (!PlayerData.playerDisplayName.containsKey(uuid) || playerIsOnline && - !PlayerData.playerDisplayName.get(uuid).equals(Bukkit.getPlayer(uuid).getDisplayName())) { - - PlayerData.playerDisplayName.put(uuid, Bukkit.getPlayer(uuid).getDisplayName()); - PlayerData.playerCacheChanged = true; - - } - - } - - private static double roundDecimals(double rawValue) { - - return (double) Math.round(rawValue * 100) / 100; + public static double checkCurrency(UUID user, boolean databaseAccess) { + if (VaultCompatibility.VAULT_ENABLED) + return VaultCompatibility.checkCurrency(user); + return PlayerData.getCurrency(user, databaseAccess); } } diff --git a/src/main/java/com/magmaguy/elitemobs/economy/UUIDFilter.java b/src/main/java/com/magmaguy/elitemobs/economy/UUIDFilter.java deleted file mode 100644 index bbe1da6c2..000000000 --- a/src/main/java/com/magmaguy/elitemobs/economy/UUIDFilter.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.economy; - -import com.magmaguy.elitemobs.playerdata.PlayerData; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; - -import java.util.UUID; - -/** - * Created by MagmaGuy on 20/06/2017. - */ -public class UUIDFilter { - - public static UUID guessUUI(String string) { - - for (Player player : Bukkit.getOnlinePlayers()) { - - if (player.getName().equalsIgnoreCase(string) || player.getDisplayName().equalsIgnoreCase(string)) { - - return player.getUniqueId(); - - } - - } - - for (UUID uuid : PlayerData.playerDisplayName.keySet()) { - - if (ChatColor.stripColor(PlayerData.playerDisplayName.get(uuid)).equalsIgnoreCase(string)) - return uuid; - - } - - return null; - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/economy/VaultCompatibility.java b/src/main/java/com/magmaguy/elitemobs/economy/VaultCompatibility.java new file mode 100644 index 000000000..54bfe15eb --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/economy/VaultCompatibility.java @@ -0,0 +1,68 @@ +package com.magmaguy.elitemobs.economy; + +import com.magmaguy.elitemobs.config.EconomySettingsConfig; +import net.milkbowl.vault.economy.Economy; +import org.bukkit.Bukkit; +import org.bukkit.plugin.RegisteredServiceProvider; + +import java.util.UUID; + +public class VaultCompatibility { + + public static boolean VAULT_ENABLED = false; + private static Economy econ = null; + + public static void vaultSetup() { + if (Bukkit.getServer().getPluginManager().isPluginEnabled("Vault")) { + Bukkit.getLogger().info("[(EliteMobs] Vault detected."); + if (EconomySettingsConfig.isUseVault()) { + Bukkit.getLogger().warning("[EliteMobs] Vault preference detected. This is not the recommended setting. " + + "Ask the dev or check the wiki as to why."); + VAULT_ENABLED = true; + VaultCompatibility.setupEconomy(); + } + + } + } + + public static void setupEconomy() { + if (Bukkit.getServer().getPluginManager().getPlugin("Vault") == null) { + return; + } + RegisteredServiceProvider rsp = Bukkit.getServer().getServicesManager().getRegistration(Economy.class); + if (rsp == null) { + return; + } + econ = rsp.getProvider(); + } + + public static void addVaultCurrency(UUID user, double amount) { + econ.depositPlayer(Bukkit.getOfflinePlayer(user), amount); + } + + public static void subtractCurrency(UUID user, double amount) { + econ.withdrawPlayer(Bukkit.getOfflinePlayer(user), amount); + } + + public static void setCurrency(UUID user, double amount) { + Bukkit.getLogger().warning("[EliteMobs] Someone just attempted to set the Vault currency through EliteMobs." + + " For safety reasons, this command is off. Please use your dedicated economy plugin for this."); + } + + public static double checkCurrency(UUID user) { + double currency = 0; + try { + currency = econ.getBalance(Bukkit.getOfflinePlayer(user)); + } catch (NullPointerException e) { + Bukkit.getLogger().warning("[EliteMobs] Player tried to check currency when they had no economy entry" + + "associated to them. This is an issue with your Vault/economy implementation, not EliteMobs."); + } + return currency; + + } + + public static Economy getEconomy() { + return econ; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/entitytracker/EntityTracker.java b/src/main/java/com/magmaguy/elitemobs/entitytracker/EntityTracker.java new file mode 100644 index 000000000..ca24992e2 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/entitytracker/EntityTracker.java @@ -0,0 +1,224 @@ +package com.magmaguy.elitemobs.entitytracker; + +import com.magmaguy.elitemobs.CrashFix; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobSpawnEvent; +import com.magmaguy.elitemobs.api.NPCEntitySpawnEvent; +import com.magmaguy.elitemobs.api.SuperMobSpawnEvent; +import com.magmaguy.elitemobs.api.internal.RemovalReason; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.mobconstructor.SimplePersistentEntity; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import com.magmaguy.elitemobs.npcs.NPCEntity; +import com.magmaguy.elitemobs.tagger.PersistentTagger; +import com.magmaguy.elitemobs.utils.EventCaller; +import lombok.Getter; +import org.bukkit.Bukkit; +import org.bukkit.Chunk; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.block.Block; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Projectile; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.world.ChunkUnloadEvent; +import org.bukkit.event.world.WorldUnloadEvent; +import org.bukkit.scheduler.BukkitRunnable; + +import javax.annotation.Nullable; +import java.util.*; + +public class EntityTracker implements Listener { + + @Getter + private static final HashMap eliteMobEntities = new HashMap<>(); + @Getter + private static final HashMap npcEntities = new HashMap<>(); + @Getter + private static final HashSet temporaryBlocks = new HashSet<>(); + + public static void registerEliteMob(EliteEntity eliteEntity) { + EliteMobSpawnEvent eliteMobSpawnEvent = new EliteMobSpawnEvent(eliteEntity); + new EventCaller(eliteMobSpawnEvent); + if (eliteMobSpawnEvent.isCancelled()) return; + PersistentTagger.tagElite(eliteEntity.getLivingEntity(), eliteEntity.getEliteUUID()); + eliteMobEntities.put(eliteEntity.getEliteUUID(), eliteEntity); + } + + public static boolean isEliteMob(Entity entity) { + return PersistentTagger.isEliteEntity(entity); + } + + @Nullable + public static EliteEntity getEliteMobEntity(Entity entity) { + return PersistentTagger.getEliteEntity(entity); + } + + public static void unregisterEliteEntity(Entity entity, RemovalReason removalReason) { + EliteEntity eliteEntity = getEliteMobEntity(entity); + if (eliteEntity == null) return; + //Removal from the hashmap is not guaranteed here as some forms of removal don't completely wipe the elite entity out + eliteEntity.remove(removalReason); + } + + //Super Mobs + public static void registerSuperMob(LivingEntity livingEntity) { + SuperMobSpawnEvent superMobSpawnEvent = new SuperMobSpawnEvent(livingEntity); + new EventCaller(superMobSpawnEvent); + if (superMobSpawnEvent.isCancelled()) return; + PersistentTagger.tagSuperMob(livingEntity); + } + + public static boolean isSuperMob(Entity entity) { + return PersistentTagger.isSuperMob(entity); + } + + public static List getSuperMobs() { + List superMobs = new ArrayList<>(); + for (World world : Bukkit.getWorlds()) + for (Entity entity : world.getEntities()) + if (isSuperMob(entity)) + superMobs.add((LivingEntity) entity); + return superMobs; + } + + //Visual effects - usually trails around elites + public static List getItemVisualEffects() { + List visualEffects = new ArrayList<>(); + for (World world : Bukkit.getWorlds()) + for (Entity entity : world.getEntities()) + if (isSuperMob(entity)) + visualEffects.add(entity); + return visualEffects; + } + + public static void registerVisualEffects(Entity entity) { + PersistentTagger.tagVisualEffect(entity); + } + + public static boolean isVisualEffect(Entity entity) { + return PersistentTagger.isVisualEffect(entity); + } + + public static void unregisterVisualEffect(Entity entity) { + if (isVisualEffect(entity)) entity.remove(); + } + + public static void registerNPCEntity(NPCEntity npc) { + NPCEntitySpawnEvent npcEntitySpawnEvent = new NPCEntitySpawnEvent(npc.getVillager(), npc); + new EventCaller(npcEntitySpawnEvent); + if (npcEntitySpawnEvent.isCancelled()) return; + npcEntities.put(npc.getUuid(), npc); + PersistentTagger.tagNPC(npc.getVillager(), npc.getUuid()); + } + + public static boolean isNPCEntity(Entity entity) { + return PersistentTagger.isNPC(entity); + } + + public static NPCEntity getNPCEntity(Entity entity) { + return PersistentTagger.getNPC(entity); + } + + public static void unregisterNPCEntity(Entity entity, RemovalReason removalReason) { + NPCEntity npcEntity = getNPCEntity(entity); + if (npcEntity == null) return; + //Removal from the hashmap is not guaranteed here as some forms of removal don't completely wipe the elite entity out + npcEntity.remove(removalReason); + } + + //Temporary blocks - blocks in powers + public static void addTemporaryBlock(Block block, int ticks, Material replacementMaterial) { + temporaryBlocks.add(block); + block.setType(replacementMaterial); + new BukkitRunnable() { + @Override + public void run() { + if (block.getType().equals(replacementMaterial)) + block.setType(Material.AIR); + temporaryBlocks.remove(block); + } + }.runTaskLater(MetadataHandler.PLUGIN, ticks); + } + + public static boolean isTemporaryBlock(Block block) { + return temporaryBlocks.contains(block); + } + + public static void removeTemporaryBlock(Block block) { + temporaryBlocks.remove(block); + } + + //Projectile entities - Minecraft already stores data about who fired them, so just simple entities. + //NOTE: there are no events for firing elitemobs projectiles, does not seem like it would serve a good function as of right now + public static void registerProjectileEntity(Projectile projectile) { + PersistentTagger.tagEliteProjectile(projectile); + } + + public static boolean isProjectileEntity(Entity entity) { + return PersistentTagger.isEliteProjectile(entity); + } + + public static void unregisterProjectileEntity(Entity entity) { + if (isProjectileEntity(entity)) entity.remove(); + } + + public static void unregister(Entity entity, RemovalReason removalReason) { + unregisterEliteEntity(entity, removalReason); + unregisterVisualEffect(entity); + unregisterProjectileEntity(entity); + unregisterNPCEntity(entity, removalReason); + } + + public static void wipeChunk(Chunk chunk, RemovalReason removalReason) { + for (Entity entity : chunk.getEntities()) + unregister(entity, removalReason); + } + + public static void wipeWorld(World world, RemovalReason removalReason) { + for (Chunk chunk : world.getLoadedChunks()) + wipeChunk(chunk, removalReason); + } + + public static void wipeShutdown() { + for (EliteEntity eliteEntity : ((HashMap) eliteMobEntities.clone()).values()) + eliteEntity.remove(RemovalReason.SHUTDOWN); + getEliteMobEntities().clear(); + for (NPCEntity npcEntity : ((HashMap) npcEntities.clone()).values()) + npcEntity.remove(RemovalReason.SHUTDOWN); + getNpcEntities().clear(); + for (Block block : temporaryBlocks) + block.setType(Material.AIR); + temporaryBlocks.clear(); + //Necessary for things such as visual effects which are not stored in memory, only tagged + for (World world : Bukkit.getWorlds()) + for (Entity entity : world.getEntities()) + unregister(entity, RemovalReason.SHUTDOWN); + SimplePersistentEntity.getPersistentEntities().clear(); + CustomBossEntity.getTrackableCustomBosses().clear(); + CrashFix.knownSessionChunks.clear(); + } + + + //Events + @EventHandler(ignoreCancelled = true) + public void onUnload(ChunkUnloadEvent event) { + EntityTracker.wipeChunk(event.getChunk(), RemovalReason.CHUNK_UNLOAD); + } + + @EventHandler(ignoreCancelled = true) + public void onWorldUnload(WorldUnloadEvent event) { + EntityTracker.wipeWorld(event.getWorld(), RemovalReason.WORLD_UNLOAD); + } + + @EventHandler(ignoreCancelled = true) + public void onMine(BlockBreakEvent event) { + if (!isTemporaryBlock(event.getBlock())) return; + event.setDropItems(false); + removeTemporaryBlock(event.getBlock()); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/events/ActionEvent.java b/src/main/java/com/magmaguy/elitemobs/events/ActionEvent.java new file mode 100644 index 000000000..8c3802b01 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/events/ActionEvent.java @@ -0,0 +1,162 @@ +package com.magmaguy.elitemobs.events; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.CustomEventStartEvent; +import com.magmaguy.elitemobs.config.EventsConfig; +import com.magmaguy.elitemobs.config.customevents.CustomEventsConfig; +import com.magmaguy.elitemobs.config.customevents.CustomEventsConfigFields; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import com.magmaguy.elitemobs.utils.VersionChecker; +import com.magmaguy.elitemobs.utils.WarningMessage; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.player.PlayerFishEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +public class ActionEvent extends CustomEvent { + + private static final List blueprintEvents = new ArrayList<>(); + private static final HashSet playerCooldowns = new HashSet<>(); + private final double chance; + private final List breakableMaterials; + private Player player; + public ActionEvent(CustomEventsConfigFields customEventsConfigFields) { + super(customEventsConfigFields); + this.chance = customEventsConfigFields.getChance(); + this.breakableMaterials = customEventsConfigFields.getBreakableMaterials(); + setPrimaryCustomBossFilenames(primaryCustomBossFilenames); + } + + public static void shutdown() { + blueprintEvents.clear(); + playerCooldowns.clear(); + } + + /** + * Initializes events directly from the configuration files, and keeps a copy to run checks over in order to instantiate + * events for the server to run + */ + public static void initializeBlueprintEvents() { + if (!EventsConfig.isActionEventsEnabled()) return; + for (CustomEventsConfigFields customEventsConfigFields : CustomEventsConfig.getCustomEvents().values()) { + if (customEventsConfigFields.isEnabled()) + switch (customEventsConfigFields.getEventType()) { + case BREAK_BLOCK: + case FISH: + case TILL_SOIL: + blueprintEvents.add(new ActionEvent(customEventsConfigFields)); + break; + default: + break; + } + } + } + + public boolean checkBlockBreakStartConditions(Material material) { + if (ThreadLocalRandom.current().nextDouble() >= chance) return false; + return breakableMaterials.contains(material); + } + + public boolean checkFishStartConditions() { + return ThreadLocalRandom.current().nextDouble() < chance; + } + + public boolean checkTillSoilStartConditions() { + return ThreadLocalRandom.current().nextDouble() < chance; + } + + public void instantiateEvent(Location location, Player player) { + this.player = player; + ActionEvent actionEvent = new ActionEvent(customEventsConfigFields); + actionEvent.setEventStartLocation(location); + CustomEventStartEvent customEventStartEvent = new CustomEventStartEvent(actionEvent); + if (customEventStartEvent.isCancelled()) return; + if (!actionEvent.startConditions.areValid()) return; + + for (String filename : primaryCustomBossFilenames) { + CustomBossEntity customBossEntity = CustomBossEntity.createCustomBossEntity(filename); + if (customBossEntity == null) { + new WarningMessage("Failed to generate custom boss " + filename + " ! This has cancelled action event " + customEventsConfigFields.getFilename() + " !"); + return; + } + customBossEntity.spawn(actionEvent.getEventStartLocation(), false); + actionEvent.primaryEliteMobs.add(customBossEntity); + } + + actionEvent.start(); + } + + @Override + public void startModifiers() { + playerCooldowns.add(player); + Bukkit.getScheduler().runTaskLater(MetadataHandler.PLUGIN, () -> playerCooldowns.remove(player), 20L * 60L * EventsConfig.getActionEventMinimumCooldown()); + } + + @Override + public void eventWatchdog() { + //Nothing really for the duration here + } + + @Override + public void endModifiers() { + //No need to track action events + } + + public static class ActionEventEvents implements Listener { + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH) + public void onBlockBreakEvent(BlockBreakEvent event) { + if (playerCooldowns.contains(event.getPlayer())) return; + if (!CustomEvent.isLocationValid(event.getBlock().getLocation())) return; + for (ActionEvent actionEvent : blueprintEvents) + if (actionEvent.eventType.equals(EventType.BREAK_BLOCK) && + actionEvent.checkBlockBreakStartConditions(event.getBlock().getType())) + actionEvent.instantiateEvent(event.getBlock().getLocation().clone().add(new Vector(0.5, 0, 0.5)), event.getPlayer()); + } + + + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH) + public void onFishEvent(PlayerFishEvent event) { + if (event.getCaught() == null) return; + if (playerCooldowns.contains(event.getPlayer())) return; + if (!CustomEvent.isLocationValid(event.getCaught().getLocation())) return; + for (ActionEvent actionEvent : blueprintEvents) + if (actionEvent.eventType.equals(EventType.FISH) && actionEvent.checkFishStartConditions()) + actionEvent.instantiateEvent(event.getCaught().getLocation(), event.getPlayer()); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH) + public void onTillSoil(PlayerInteractEvent event) { + if (!event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) return; + if (event.getClickedBlock() == null) return; + if (playerCooldowns.contains(event.getPlayer())) return; + Location location = event.getClickedBlock().getLocation().clone().add(new Vector(0.5, 1, 0.5)); + if (!CustomEvent.isLocationValid(location)) return; + if (!(event.getPlayer().getInventory().getItemInMainHand().getType().equals(Material.DIAMOND_HOE) || + event.getPlayer().getInventory().getItemInMainHand().getType().equals(Material.IRON_HOE) || + event.getPlayer().getInventory().getItemInMainHand().getType().equals(Material.GOLDEN_HOE) || + event.getPlayer().getInventory().getItemInMainHand().getType().equals(Material.STONE_HOE) || + event.getPlayer().getInventory().getItemInMainHand().getType().equals(Material.WOODEN_HOE) || + !VersionChecker.serverVersionOlderThan(16, 0) && + event.getPlayer().getInventory().getItemInMainHand().getType().equals(Material.NETHERITE_HOE))) + return; + if (!(event.getClickedBlock().getType().equals(Material.DIRT) || + event.getClickedBlock().getType().equals(Material.GRASS_BLOCK))) return; + for (ActionEvent actionEvent : blueprintEvents) + if (actionEvent.eventType.equals(EventType.TILL_SOIL) && actionEvent.checkTillSoilStartConditions()) + actionEvent.instantiateEvent(location, event.getPlayer()); + } + } +} \ No newline at end of file diff --git a/src/main/java/com/magmaguy/elitemobs/events/BossCustomAttackDamage.java b/src/main/java/com/magmaguy/elitemobs/events/BossCustomAttackDamage.java new file mode 100644 index 000000000..61d8c5871 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/events/BossCustomAttackDamage.java @@ -0,0 +1,27 @@ +package com.magmaguy.elitemobs.events; + +import com.magmaguy.elitemobs.combatsystem.PlayerDamagedByEliteMobHandler; +import org.bukkit.GameMode; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; + +public class BossCustomAttackDamage { + + public static double dealCustomDamage(LivingEntity damager, LivingEntity damagee, double damage) { + + if (damager == null || damagee == null) return 0; + if (damager.equals(damagee)) return 0; + if (damagee.isInvulnerable() || damagee.getHealth() <= 0) return 0; + + if (damagee instanceof Player) + if (!(((Player) damagee).getGameMode().equals(GameMode.SURVIVAL) || + ((Player) damagee).getGameMode().equals(GameMode.ADVENTURE))) return 0; + + PlayerDamagedByEliteMobHandler.bypass = true; + damagee.damage(damage, damager); + damagee.setNoDamageTicks(0); + + return damage; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/events/BossSpecialAttackDamage.java b/src/main/java/com/magmaguy/elitemobs/events/BossSpecialAttackDamage.java deleted file mode 100644 index 3b129a6c7..000000000 --- a/src/main/java/com/magmaguy/elitemobs/events/BossSpecialAttackDamage.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.events; - -import com.magmaguy.elitemobs.collateralminecraftchanges.PlayerDeathMessageByEliteMob; -import org.bukkit.GameMode; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; - -public class BossSpecialAttackDamage { - - public static boolean dealSpecialDamage(LivingEntity damager, LivingEntity damagee, double damage) { - - if (damagee.isInvulnerable() || damagee.getHealth() <= 0) return false; - - if (damagee instanceof Player) { - - if (!(((Player) damagee).getGameMode().equals(GameMode.SURVIVAL) || - ((Player) damagee).getGameMode().equals(GameMode.ADVENTURE))) return false; - - } - - damagee.damage(damage); - damagee.setNoDamageTicks(0); - - if (damagee instanceof Player && damagee.getHealth() <= 0) { - - PlayerDeathMessageByEliteMob.intializeDeathMessage((Player) damagee, damager); - - } - - return true; - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/events/CustomEvent.java b/src/main/java/com/magmaguy/elitemobs/events/CustomEvent.java new file mode 100644 index 000000000..a9c29d053 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/events/CustomEvent.java @@ -0,0 +1,186 @@ +package com.magmaguy.elitemobs.events; + +import com.magmaguy.elitemobs.EliteMobs; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.announcements.AnnouncementPriority; +import com.magmaguy.elitemobs.api.internal.RemovalReason; +import com.magmaguy.elitemobs.config.ValidWorldsConfig; +import com.magmaguy.elitemobs.config.customevents.CustomEventsConfigFields; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import com.magmaguy.elitemobs.thirdparty.worldguard.WorldGuardCompatibility; +import com.magmaguy.elitemobs.thirdparty.worldguard.WorldGuardFlagChecker; +import com.magmaguy.elitemobs.utils.CommandRunner; +import com.magmaguy.elitemobs.utils.InfoMessage; +import com.magmaguy.elitemobs.utils.WarningMessage; +import org.bukkit.Location; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scheduler.BukkitTask; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicBoolean; + +public abstract class CustomEvent { + + //Start Conditions + public StartConditions startConditions; + //Common fields + public EventType eventType; + public ArrayList primaryEliteMobs = new ArrayList<>(); + public BukkitTask eventWatchdog; + public int announcementPriority; + public CustomEventsConfigFields customEventsConfigFields; + public String startMessage, endMessage; + public List startEventCommands, endEventCommands; + public List primaryCustomBossFilenames; + public Location eventStartLocation; + public float eventStartTime; + public int currentDay; + + /** + * Instantiates a Custom Event, does not necessarily start one but starts scanning for whether one should happen + */ + public CustomEvent(CustomEventsConfigFields customEventsConfigFields) { + this.startConditions = new StartConditions(customEventsConfigFields); + + this.customEventsConfigFields = customEventsConfigFields; + this.eventType = customEventsConfigFields.getEventType(); + this.startMessage = customEventsConfigFields.getStartMessage(); + this.endMessage = customEventsConfigFields.getEndMessage(); + this.startEventCommands = customEventsConfigFields.getEventStartCommands(); + this.endEventCommands = customEventsConfigFields.getEventEndCommands(); + this.announcementPriority = customEventsConfigFields.getAnnouncementPriority(); + this.primaryCustomBossFilenames = customEventsConfigFields.getBossFilenames(); + } + + public static boolean isLocationValid(Location location) { + if (!ValidWorldsConfig.getValidWorlds().contains(Objects.requireNonNull(location.getWorld()).getName())) + return false; + return !(EliteMobs.worldGuardIsEnabled && + !WorldGuardFlagChecker.checkFlag(location, WorldGuardCompatibility.getEliteMobsEventsFlag())); + } + + public CustomEventsConfigFields getCustomEventsConfigFields() { + return customEventsConfigFields; + } + + public List getPrimaryCustomBossFilenames() { + return primaryCustomBossFilenames; + } + + public void setPrimaryCustomBossFilenames(List primaryCustomBossFilenames) { + this.primaryCustomBossFilenames = primaryCustomBossFilenames; + } + + public Location getEventStartLocation() { + return eventStartLocation; + } + + public void setEventStartLocation(Location eventStartLocation) { + this.eventStartLocation = eventStartLocation; + } + + /** + * Starts a Custom Event watchdog, which will scan whether the event is still ongoing or if it has ended every second + */ + public void start() { + startModifiers(); + if (primaryEliteMobs.isEmpty()) { + new WarningMessage("Event " + customEventsConfigFields.getFilename() + " has failed to start because the bosses failed to spawn correctly!" + + "This could be due to an issue with the configuration of the bosses in the event, with the configuration" + + " of the event or due to a protection in the target location!"); + new WarningMessage("Target location: " + getEventStartLocation().toString()); + } + if (this.startMessage != null) + AnnouncementPriority.announce(this.startMessage, eventStartLocation.getWorld(), this.announcementPriority); + if (this.startEventCommands != null) + CommandRunner.runCommandFromList(this.startEventCommands, new ArrayList<>()); + eventStartTime = System.currentTimeMillis(); + currentDay = dayCalculator(); + eventWatchdog = new BukkitRunnable() { + @Override + public void run() { + commonWatchdogBehavior(); + eventWatchdog(); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 20, 20); + } + + private int dayCalculator() { + return (int) Math.floor(eventStartLocation.getWorld().getFullTime() / 24000f); + } + + //START CHECKS - currently in each class + + //ACTIVE + + public abstract void startModifiers(); + + /** + * Runs checks that are common to all event types + */ + public void commonWatchdogBehavior() { + if (customEventsConfigFields.getEventEndTime() != -1) + if (currentDay != dayCalculator() || + eventStartLocation.getWorld().getTime() > customEventsConfigFields.getEventEndTime()) { + end(); + return; + } + if (customEventsConfigFields.getEventDuration() > 0) + if (System.currentTimeMillis() - eventStartTime > customEventsConfigFields.getEventDuration() * 60 * 1000) { + end(); + return; + } + if (customEventsConfigFields.isEndEventWithBossDeath()) { + AtomicBoolean allBossesAreDead = new AtomicBoolean(true); + primaryEliteMobs.forEach((primaryEliteMob) -> { + if (primaryEliteMob.exists()) + allBossesAreDead.set(false); + }); + if (allBossesAreDead.get()) { + end(); + return; + } + } + } + + /** + * Checks whether the conditions for the event to end have been met + */ + public abstract void eventWatchdog(); + + /** + * Starts the end of the event, deletes all EliteMobEntities spawned by the event and queues further event completion requirements + */ + public void end() { + new InfoMessage("Event " + customEventsConfigFields.getFilename() + " ended!"); + if (eventWatchdog != null) + eventWatchdog.cancel(); + primaryEliteMobs.forEach(eliteMobEntity -> { + if (eliteMobEntity.exists()) eliteMobEntity.remove(RemovalReason.BOSS_TIMEOUT); + }); + if (this.endMessage != null) + AnnouncementPriority.announce(this.endMessage, eventStartLocation.getWorld(), this.announcementPriority); + if (this.endEventCommands != null) + CommandRunner.runCommandFromList(this.endEventCommands, new ArrayList<>()); + endModifiers(); + } + + //END + + /** + * Gets called by the end() method, completes any extension-specific behavior for the end of the event, such as + * implementing cooldowns or doing announcements. + */ + public abstract void endModifiers(); + + public enum EventType { + //Action Events + DEFAULT, + BREAK_BLOCK, + FISH, + TILL_SOIL, + TIMED + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/events/DeadMoon.java b/src/main/java/com/magmaguy/elitemobs/events/DeadMoon.java deleted file mode 100644 index 75f15291f..000000000 --- a/src/main/java/com/magmaguy/elitemobs/events/DeadMoon.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.events; - -import com.magmaguy.elitemobs.EliteMobs; -import com.magmaguy.elitemobs.EntityTracker; -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.EventsConfig; -import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; -import com.magmaguy.elitemobs.config.ValidMobsConfig; -import com.magmaguy.elitemobs.events.mobs.TheReturned; -import com.magmaguy.elitemobs.events.mobs.ZombieKing; -import com.magmaguy.elitemobs.mobspawning.NaturalEliteMobSpawnEventHandler; -import org.bukkit.World; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Zombie; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.CreatureSpawnEvent; -import org.bukkit.scheduler.BukkitRunnable; - -import static org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.CUSTOM; -import static org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.NATURAL; - -public class DeadMoon implements Listener { - - public static boolean entityQueued = false; - public static boolean eventOngoing = false; - - public static void initializeEvent() { - entityQueued = true; - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onSpawn(CreatureSpawnEvent event) { - - if (event.isCancelled()) return; - - if (event.getEntity().getWorld().getTime() < 13184 || event.getEntity().getWorld().getTime() > 22800) return; - if (!event.getSpawnReason().equals(CreatureSpawnEvent.SpawnReason.NATURAL)) return; - if (!(event.getEntity() instanceof Zombie)) return; - if (!EventLauncher.verifyPlayerCount()) return; - - if (!EliteMobs.validWorldList.contains(event.getEntity().getWorld())) return; - - if (event.getEntity().getWorld().getEnvironment().equals(World.Environment.NETHER) || - event.getEntity().getWorld().getEnvironment().equals(World.Environment.THE_END)) return; - - if (MoonPhaseDetector.detectMoonPhase(event.getEntity().getWorld()) != MoonPhaseDetector.moonPhase.NEW_MOON) - return; - - if (!ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.NATURAL_MOB_SPAWNING) || - !ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.ALLOW_AGGRESSIVE_ELITEMOBS)) - return; - - - if (event.getSpawnReason().equals(CreatureSpawnEvent.SpawnReason.SPAWNER) && !ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.SPAWNERS_SPAWN_ELITE_MOBS)) - return; - - if (!(event.getSpawnReason() == NATURAL || event.getSpawnReason() == CUSTOM)) return; - - if (!EntityTracker.isEliteMob(event.getEntity())) - NaturalEliteMobSpawnEventHandler.naturalMobProcessor(event.getEntity()); - - //add entityQueued - if (entityQueued && !TheReturned.isTheReturned(event.getEntity()) - && (event.getSpawnReason().equals(CreatureSpawnEvent.SpawnReason.NATURAL) || - event.getSpawnReason().equals(CreatureSpawnEvent.SpawnReason.CUSTOM))) { - - eventOngoing = true; - entityQueued = false; - - EventMessage.sendEventMessage(event.getEntity(), ConfigValues.eventsConfig.getString(EventsConfig.DEADMOON_ANNOUNCEMENT_MESSAGE)); - - ZombieKing.spawnZombieKing(event.getLocation()); - terminateEvent(event.getEntity()); - - } - - } - - private void terminateEvent(LivingEntity livingEntity) { - - World world = livingEntity.getWorld(); - - new BukkitRunnable() { - - @Override - public void run() { - - if (world.getTime() > 22800 || world.getTime() < 13184 || MoonPhaseDetector.detectMoonPhase(world) != MoonPhaseDetector.moonPhase.NEW_MOON) { - - eventOngoing = false; - - EventMessage.sendEventMessage(livingEntity, ConfigValues.eventsConfig.getString(EventsConfig.DEADMOON_END_MESSAGE)); - - cancel(); - - } - - } - - }.runTaskTimer(MetadataHandler.PLUGIN, 1, 1); - - } - - -} diff --git a/src/main/java/com/magmaguy/elitemobs/events/EventLauncher.java b/src/main/java/com/magmaguy/elitemobs/events/EventLauncher.java deleted file mode 100644 index 674561a1c..000000000 --- a/src/main/java/com/magmaguy/elitemobs/events/EventLauncher.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.events; - -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.EventsConfig; -import org.bukkit.Bukkit; -import org.bukkit.plugin.Plugin; -import org.bukkit.scheduler.BukkitRunnable; - -import java.util.HashMap; - -import static com.magmaguy.elitemobs.utils.WeightedProbablity.pickWeighedProbability; - -public class EventLauncher { - - Plugin plugin = Bukkit.getPluginManager().getPlugin(MetadataHandler.ELITE_MOBS); - - public void eventRepeatingTask() { - - if (!ConfigValues.eventsConfig.getBoolean(EventsConfig.ENABLE_EVENTS)) return; - - new BukkitRunnable() { - - int counter = 0; - - @Override - public void run() { - - if (verifyPlayerCount()) { - - //if enough time has passed, run the event and reset the counter - if (timeCheck(counter)) { - - eventSelector(); - counter = 0; - return; - - } - - counter++; - - } - - } - - }.runTaskTimer(plugin, 20 * 60, 20 * 60); - - } - - public static boolean verifyPlayerCount() { - - return ConfigValues.eventsConfig.getInt(EventsConfig.MINIMUM_ONLINE_PLAYERS) <= Bukkit.getOnlinePlayers().size(); - - } - - private boolean timeCheck(int counter) { - - if (ConfigValues.eventsConfig.getInt(EventsConfig.MAXIMUM_ONLINE_PLAYERS) <= Bukkit.getOnlinePlayers().size()) { - - return counter >= ConfigValues.eventsConfig.getInt(EventsConfig.MAXIMUM_EVENT_FREQUENCY); - - } - - if (ConfigValues.eventsConfig.getInt(EventsConfig.MINIMUM_ONLINE_PLAYERS) == Bukkit.getOnlinePlayers().size()) { - - return counter >= ConfigValues.eventsConfig.getInt(EventsConfig.MINIMUM_EVENT_FREQUENCY); - - } - - int minPlayers = ConfigValues.eventsConfig.getInt(EventsConfig.MINIMUM_ONLINE_PLAYERS); - int maxPlayers = ConfigValues.eventsConfig.getInt(EventsConfig.MAXIMUM_ONLINE_PLAYERS); - double minFrequency = ConfigValues.eventsConfig.getInt(EventsConfig.MINIMUM_EVENT_FREQUENCY); - double maxFrequency = ConfigValues.eventsConfig.getInt(EventsConfig.MAXIMUM_EVENT_FREQUENCY); - - //y=mx slope = m - double slope = ((maxFrequency - minFrequency) / (maxPlayers - minPlayers)); - - double newTimerValue = slope * Bukkit.getOnlinePlayers().size() + minFrequency; - - return counter >= newTimerValue; - - - } - - private void eventSelector() { - - //todo: once more events are added, randomize which one gets picked in a weighed fashion - HashMap weighedConfigValues = new HashMap<>(); - if (ConfigValues.eventsConfig.getBoolean(EventsConfig.TREASURE_GOBLIN_SMALL_ENABLED)) { - - weighedConfigValues.put(EventsConfig.SMALL_TREASURE_GOBLIN_EVENT_WEIGHT, ConfigValues.eventsConfig.getDouble(EventsConfig.SMALL_TREASURE_GOBLIN_EVENT_WEIGHT)); - - } - - if (ConfigValues.eventsConfig.getBoolean(EventsConfig.DEAD_MOON_ENABLED)) { - - weighedConfigValues.put(EventsConfig.DEAD_MOON_EVENT_WEIGHT, ConfigValues.eventsConfig.getDouble(EventsConfig.DEAD_MOON_EVENT_WEIGHT)); - - } - - if (weighedConfigValues.isEmpty()) return; - - switch (pickWeighedProbability(weighedConfigValues)) { - - case EventsConfig.SMALL_TREASURE_GOBLIN_EVENT_WEIGHT: - SmallTreasureGoblin.initializeEvent(); - return; - case EventsConfig.DEAD_MOON_EVENT_WEIGHT: - DeadMoon.initializeEvent(); - return; - - } - - } - - -} diff --git a/src/main/java/com/magmaguy/elitemobs/events/EventMessage.java b/src/main/java/com/magmaguy/elitemobs/events/EventMessage.java deleted file mode 100644 index c2fb39cef..000000000 --- a/src/main/java/com/magmaguy/elitemobs/events/EventMessage.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.events; - -import com.magmaguy.elitemobs.ChatColorConverter; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.EventsConfig; -import org.bukkit.Bukkit; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; - -public class EventMessage { - - public static void sendEventMessage(LivingEntity livingEntity, String configMessage) { - - String coordinates = livingEntity.getLocation().getBlockX() + ", " + livingEntity.getLocation().getBlockY() + ", " + livingEntity.getLocation().getBlockZ(); - String sendString = configMessage.replace("$location", coordinates); - String worldName = ""; - - if (livingEntity.getWorld().getName().contains("_")) { - - for (String string : livingEntity.getWorld().getName().split("_")) { - - worldName += string.substring(0, 1).toUpperCase() + string.substring(1).toLowerCase() + " "; - - } - - } else { - - worldName = livingEntity.getWorld().getName().substring(0, 1).toUpperCase() + livingEntity.getWorld().getName().substring(1).toLowerCase(); - - } - - sendString = ChatColorConverter.convert(sendString.replace("$world", worldName)); - - if (ConfigValues.eventsConfig.getBoolean(EventsConfig.ANNOUNCEMENT_BROADCAST_WORLD_ONLY)) { - for (Player player : Bukkit.getServer().getOnlinePlayers()) - if (player.getWorld().equals(livingEntity.getWorld())) - player.sendMessage(sendString); - } else - Bukkit.getServer().broadcastMessage(sendString); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/events/MoonPhaseDetector.java b/src/main/java/com/magmaguy/elitemobs/events/MoonPhaseDetector.java index 1f6e3f9c3..4b33aae5e 100644 --- a/src/main/java/com/magmaguy/elitemobs/events/MoonPhaseDetector.java +++ b/src/main/java/com/magmaguy/elitemobs/events/MoonPhaseDetector.java @@ -1,18 +1,3 @@ -/* - * 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 . - */ - package com.magmaguy.elitemobs.events; import org.bukkit.Bukkit; @@ -20,39 +5,38 @@ public class MoonPhaseDetector { - public static moonPhase detectMoonPhase(World eventWorld) { + public static MoonPhase detectMoonPhase(World eventWorld) { int days = (int) eventWorld.getFullTime() / 24000; - int phase = days % 8; + int phase = Math.abs(days % 8); switch (phase) { case 0: - return moonPhase.FULL_MOON; + return MoonPhase.FULL_MOON; case 1: - return moonPhase.WANING_GIBBOUS; + return MoonPhase.WANING_GIBBOUS; case 2: - return moonPhase.LAST_QUARTER; + return MoonPhase.LAST_QUARTER; case 3: - return moonPhase.WANING_CRESCENT; + return MoonPhase.WANING_CRESCENT; case 4: - return moonPhase.NEW_MOON; + return MoonPhase.NEW_MOON; case 5: - return moonPhase.WAXING_CRESCENT; + return MoonPhase.WAXING_CRESCENT; case 6: - return moonPhase.FIRST_QUARTER; + return MoonPhase.FIRST_QUARTER; case 7: - return moonPhase.WAXING_GIBBOUS; + return MoonPhase.WAXING_GIBBOUS; default: - Bukkit.getLogger().info("Unhandled moon phase."); - return null; + Bukkit.getLogger().info("Unhandled moon phase. Phase " + phase + " was " + days + ". Defaulting to full moon..."); + return MoonPhase.FULL_MOON; } } - public enum moonPhase { - + public enum MoonPhase { FULL_MOON, WANING_GIBBOUS, LAST_QUARTER, @@ -61,7 +45,6 @@ public enum moonPhase { WAXING_CRESCENT, FIRST_QUARTER, WAXING_GIBBOUS - } } diff --git a/src/main/java/com/magmaguy/elitemobs/events/SmallTreasureGoblin.java b/src/main/java/com/magmaguy/elitemobs/events/SmallTreasureGoblin.java deleted file mode 100644 index 746a69b60..000000000 --- a/src/main/java/com/magmaguy/elitemobs/events/SmallTreasureGoblin.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.events; - -import com.magmaguy.elitemobs.EliteMobs; -import com.magmaguy.elitemobs.events.mobs.TreasureGoblin; -import org.bukkit.Location; -import org.bukkit.entity.Zombie; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.CreatureSpawnEvent; - -public class SmallTreasureGoblin implements Listener { - - public static boolean entityQueued = false; - - public static void initializeEvent() { - entityQueued = true; - } - - public static void initalizeEvent(Location location) { - - TreasureGoblin.createGoblin(location); - - entityQueued = false; - - } - - - @EventHandler (priority = EventPriority.HIGHEST) - public void onSpawn(CreatureSpawnEvent event) { - - if (event.isCancelled()) return; - if (!EventLauncher.verifyPlayerCount()) return; - - if (EliteMobs.validWorldList.contains(event.getEntity().getWorld())) { - - if (entityQueued && (event.getSpawnReason().equals(CreatureSpawnEvent.SpawnReason.NATURAL) || - event.getSpawnReason().equals(CreatureSpawnEvent.SpawnReason.CUSTOM)) && - event.getEntity() instanceof Zombie) { - - initalizeEvent(event.getLocation()); - - } - - } - - } - - -} diff --git a/src/main/java/com/magmaguy/elitemobs/events/StartConditions.java b/src/main/java/com/magmaguy/elitemobs/events/StartConditions.java new file mode 100644 index 000000000..0c2f3ec0e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/events/StartConditions.java @@ -0,0 +1,18 @@ +package com.magmaguy.elitemobs.events; + +import com.magmaguy.elitemobs.config.customevents.CustomEventsConfigFields; +import org.bukkit.Bukkit; + +public class StartConditions { + + private final int minimumPlayerCount; + + public StartConditions(CustomEventsConfigFields customEventsConfigFields) { + this.minimumPlayerCount = customEventsConfigFields.getMinimumPlayerCount(); + } + + public boolean areValid() { + return Bukkit.getServer().getOnlinePlayers().size() >= minimumPlayerCount; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/events/TimedEvent.java b/src/main/java/com/magmaguy/elitemobs/events/TimedEvent.java new file mode 100644 index 000000000..2a88eb90a --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/events/TimedEvent.java @@ -0,0 +1,166 @@ +package com.magmaguy.elitemobs.events; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.CustomEventStartEvent; +import com.magmaguy.elitemobs.config.EventsConfig; +import com.magmaguy.elitemobs.config.customevents.CustomEventsConfig; +import com.magmaguy.elitemobs.config.customevents.CustomEventsConfigFields; +import com.magmaguy.elitemobs.mobconstructor.CustomSpawn; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import com.magmaguy.elitemobs.utils.InfoMessage; +import com.magmaguy.elitemobs.utils.WeightedProbability; +import lombok.Getter; +import org.bukkit.Bukkit; +import org.bukkit.event.Listener; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class TimedEvent extends CustomEvent implements Listener { + + @Getter + protected static List blueprintEvents = new ArrayList<>(); + protected static List timedEvents = new ArrayList<>(); + //stores the time of the last global trigger + private static double nextEventTrigger = System.currentTimeMillis() + 5D * 60D * 1000D; + private final double localCooldown; + private final double globalCooldown; + private final double weight; + private final String filename; + private double nextLocalEventTrigger = 0; + private CustomSpawn customSpawn; + private boolean silentRetry = false; + public TimedEvent(CustomEventsConfigFields customEventsConfigFields) { + super(customEventsConfigFields); + this.localCooldown = customEventsConfigFields.getLocalCooldown(); + this.globalCooldown = customEventsConfigFields.getGlobalCooldown(); + this.weight = customEventsConfigFields.getWeight(); + this.filename = customEventsConfigFields.getFilename(); + } + + public static void shutdown() { + blueprintEvents.clear(); + timedEvents.clear(); + } + + public static void initializeBlueprintEvents() { + if (!EventsConfig.isTimedEventsEnabled()) return; + for (CustomEventsConfigFields customEventsConfigFields : CustomEventsConfig.getCustomEvents().values()) + if (customEventsConfigFields.isEnabled() && customEventsConfigFields.getEventType() == EventType.TIMED) + blueprintEvents.add(new TimedEvent(customEventsConfigFields)); + startEventPicker(); + } + + private static void startEventPicker() { + new BukkitRunnable() { + @Override + public void run() { + if (Bukkit.getServer().getOnlinePlayers().isEmpty()) return; + if (System.currentTimeMillis() < nextEventTrigger) return; + pickEvent(); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 20L * 60L * 5L, 20L * 60L); + } + + private static void pickEvent() { + HashMap weighedProbabilities = new HashMap<>(); + for (TimedEvent timedEvent : blueprintEvents) { + boolean isRunning = false; + for (TimedEvent activeTimedEvent : timedEvents) + if (activeTimedEvent != null && + activeTimedEvent.getCustomEventsConfigFields().getFilename().equals(timedEvent.getCustomEventsConfigFields().getFilename())) { + isRunning = true; + break; + } + if (isRunning) + continue; + if (timedEvent.nextLocalEventTrigger < System.currentTimeMillis()) + weighedProbabilities.put(timedEvent.filename, timedEvent.weight); + } + String pickedEvent = WeightedProbability.pickWeighedProbability(weighedProbabilities); + for (TimedEvent timedEvent : blueprintEvents) + if (timedEvent.filename.equals(pickedEvent)) { + timedEvent.nextLocalEventTrigger = System.currentTimeMillis() + timedEvent.localCooldown * 60 * 1000; + timedEvent.instantiateEvent(); + return; + } + } + + /** + * Just because the event is instantiated, does not necessarily mean it started. If the spawn isn't instant, then + * it needs to be queued for a later date. If the spawn is instant but no valid location can be found, it should retry + * on a delay. + */ + public void instantiateEvent() { + new InfoMessage("Event " + getCustomEventsConfigFields().getFilename() + " has been queued!"); + TimedEvent timedEvent = new TimedEvent(customEventsConfigFields); + CustomEventStartEvent customEventStartEvent = new CustomEventStartEvent(timedEvent); + if (customEventStartEvent.isCancelled()) return; + + timedEvent.customSpawn = new CustomSpawn(customEventsConfigFields.getCustomSpawn(), + customEventsConfigFields.getBossFilenames(), + timedEvent); + + //Failed to initialize event + if (timedEvent.customSpawn.getCustomSpawnConfigFields() == null) + return; + + //This handles the elitemobs-events flag + timedEvent.customSpawn.setEvent(true); + + //Note: this will finish running at an arbitrary time in the future + timedEvent.customSpawn.queueSpawn(); + + //global cooldown - 60 seconds right now + nextEventTrigger = System.currentTimeMillis() + globalCooldown * 60 * 1000; + + timedEvents.add(timedEvent); + } + + /** + * Queues an event to start when the start conditions are met + */ + public void queueEvent() { + this.primaryEliteMobs = customSpawn.getCustomBossEntities(); + setEventStartLocation(customSpawn.getSpawnLocation()); + + for (CustomBossEntity customBossEntity : primaryEliteMobs) + if (!customBossEntity.exists()) { + if (!silentRetry) { + new InfoMessage("Boss " + customBossEntity.getCustomBossesConfigFields().getFilename() + " for event " + + getCustomEventsConfigFields().getFilename() + " wasn't considered to be valid. Trying spawn again ."); + new InfoMessage("Note: further failures will be silent. EliteMobs can only predict WorldGuard protections," + + " so it will keep trying to spawn things until plugins preventing spawning allow it to do so. This might take a while."); + silentRetry = true; + } + + Bukkit.getScheduler().runTaskLater(MetadataHandler.PLUGIN, () -> { + customSpawn.setSpawnLocation(null); + customSpawn.queueSpawn(); + }, 1); + return; + } + + primaryEliteMobs.forEach(CustomBossEntity::announceSpawn); + + start(); + } + + @Override + public void startModifiers() { + //Start cooldown for the blueprints, not the instantiated event because that one will be deleted at the end of its runtime + this.nextLocalEventTrigger = System.currentTimeMillis() + localCooldown * 60000; + } + + @Override + public void eventWatchdog() { + //No specific checks are currently required while the timed event occurs + } + + @Override + public void endModifiers() { + timedEvents.remove(this); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/events/actionevents/BalrogEvent.java b/src/main/java/com/magmaguy/elitemobs/events/actionevents/BalrogEvent.java deleted file mode 100644 index c22500f36..000000000 --- a/src/main/java/com/magmaguy/elitemobs/events/actionevents/BalrogEvent.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.magmaguy.elitemobs.events.actionevents; - -import com.magmaguy.elitemobs.EliteMobs; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.EventsConfig; -import com.magmaguy.elitemobs.events.mobs.Balrog; -import org.bukkit.GameMode; -import org.bukkit.Material; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.block.BlockBreakEvent; - -import java.util.concurrent.ThreadLocalRandom; - -public class BalrogEvent implements Listener { - - @EventHandler - public void onMine(BlockBreakEvent event) { - - if (event.isCancelled()) return; - if (!EliteMobs.validWorldList.contains(event.getPlayer().getWorld())) return; - if (event.getPlayer().getGameMode() == GameMode.CREATIVE || event.getPlayer().getGameMode() == GameMode.SPECTATOR) return; -// if (!event.getPlayer().hasPermission("elitemobs.events.balrog")) return; - if (event.getPlayer().getInventory().getItemInMainHand().hasItemMeta() && - event.getPlayer().getInventory().getItemInMainHand().getEnchantments().containsKey(Enchantment.SILK_TOUCH)) - return; - if (!(event.getBlock().getType().equals(Material.DIAMOND_ORE) || event.getBlock().getType().equals(Material.IRON_ORE) || - event.getBlock().getType().equals(Material.COAL_ORE) || event.getBlock().getType().equals(Material.REDSTONE_ORE) || - event.getBlock().getType().equals(Material.LAPIS_ORE) || event.getBlock().getType().equals(Material.GOLD_ORE))) return; - if (ThreadLocalRandom.current().nextDouble() > ConfigValues.eventsConfig.getDouble(EventsConfig.BALROG_CHANCE_ON_MINE)) return; - - Balrog.spawnBalrog(event.getBlock().getLocation()); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/events/actionevents/FaeEvent.java b/src/main/java/com/magmaguy/elitemobs/events/actionevents/FaeEvent.java deleted file mode 100644 index 14c51f71d..000000000 --- a/src/main/java/com/magmaguy/elitemobs/events/actionevents/FaeEvent.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.magmaguy.elitemobs.events.actionevents; - -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.EventsConfig; -import com.magmaguy.elitemobs.events.mobs.Fae; -import org.bukkit.GameMode; -import org.bukkit.Material; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.block.BlockBreakEvent; - -import java.util.concurrent.ThreadLocalRandom; - -public class FaeEvent implements Listener { - - @EventHandler - public void onTreeFell(BlockBreakEvent event) { - - if (event.isCancelled()) return; - if (event.getPlayer().getGameMode() == GameMode.CREATIVE || event.getPlayer().getGameMode() == GameMode.SPECTATOR) return; - if (!(event.getBlock().getType().equals(Material.LOG) || event.getBlock().getType().equals(Material.LOG_2))) - return; -// if (!event.getPlayer().hasPermission("elitemobs.events.fae")) return; - if (ThreadLocalRandom.current().nextDouble() > ConfigValues.eventsConfig.getDouble(EventsConfig.FAE_CHANCE_ON_CHOP)) - return; - - Fae.spawnFae(event.getBlock().getLocation()); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/events/actionevents/KrakenEvent.java b/src/main/java/com/magmaguy/elitemobs/events/actionevents/KrakenEvent.java deleted file mode 100644 index 2feca9d41..000000000 --- a/src/main/java/com/magmaguy/elitemobs/events/actionevents/KrakenEvent.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.magmaguy.elitemobs.events.actionevents; - -import com.magmaguy.elitemobs.EliteMobs; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.EventsConfig; -import com.magmaguy.elitemobs.events.mobs.Kraken; -import org.bukkit.GameMode; -import org.bukkit.Material; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerFishEvent; - -import java.util.concurrent.ThreadLocalRandom; - -import static com.magmaguy.elitemobs.utils.VersionChecker.currentVersionIsUnder; - -public class KrakenEvent implements Listener { - - @EventHandler - public void onFishingStart(PlayerFishEvent event) { - - if (event.isCancelled()) return; - if (!currentVersionIsUnder(13, 0)) return; - if (!EliteMobs.validWorldList.contains(event.getPlayer().getWorld())) return; -// if (!event.getPlayer().hasPermission("elitemobs.events.kraken")) return; - if (event.getPlayer().getGameMode() == GameMode.CREATIVE || event.getPlayer().getGameMode() == GameMode.SPECTATOR) - return; - if (event.getHook().getLocation().getBlock().isEmpty() || !event.getHook().getLocation().getBlock().isEmpty() && - !event.getHook().getLocation().getBlock().getType().equals(Material.WATER)) return; - if (ThreadLocalRandom.current().nextDouble() > ConfigValues.eventsConfig.getDouble(EventsConfig.KRAKEN_CHANCE_ON_FISH)) - return; - - Kraken.spawnKraken(event.getHook().getLocation()); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/events/mobs/Balrog.java b/src/main/java/com/magmaguy/elitemobs/events/mobs/Balrog.java deleted file mode 100644 index 4b6a0a710..000000000 --- a/src/main/java/com/magmaguy/elitemobs/events/mobs/Balrog.java +++ /dev/null @@ -1,156 +0,0 @@ -package com.magmaguy.elitemobs.events.mobs; - -import com.magmaguy.elitemobs.ChatColorConverter; -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.EventsConfig; -import com.magmaguy.elitemobs.events.mobs.sharedeventproperties.ActionDynamicBossLevelConstructor; -import com.magmaguy.elitemobs.events.mobs.sharedeventproperties.BossMobDeathCountdown; -import com.magmaguy.elitemobs.items.uniqueitems.DwarvenGreed; -import com.magmaguy.elitemobs.mobconstructor.ActionBossMobEntity; -import com.magmaguy.elitemobs.mobconstructor.TrashMobEntity; -import org.bukkit.Location; -import org.bukkit.Particle; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Silverfish; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageEvent; -import org.bukkit.event.entity.EntityDeathEvent; -import org.bukkit.inventory.ItemStack; -import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.util.Vector; - -import java.util.HashSet; - -public class Balrog implements Listener { - - public static void spawnBalrog(Location location) { - balrogSpawnEffect(location.add(new Vector(0.5, 0.5, 0.5))); - } - - private static void balrogSpawnEffect(Location location) { - - new BukkitRunnable() { - - int i = 0; - - @Override - public void run() { - - if (i > 20 * 3) { - - intializeBalrog(location); - cancel(); - return; - - } - - location.getWorld().spawnParticle(Particle.SMOKE_LARGE, location, 4, 0.1, 0.1, 0.1, 0.05); - location.getWorld().spawnParticle(Particle.FLAME, location, 2, 0.1, 0.1, 0.1, 0.05); - - i++; - - } - - }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); - - } - - private static void intializeBalrog(Location location) { - - int eliteLevel = ActionDynamicBossLevelConstructor.determineDynamicBossLevel(location); - ActionBossMobEntity bossMobEntity = new ActionBossMobEntity(EntityType.SILVERFISH, location, eliteLevel, ConfigValues.eventsConfig.getString(EventsConfig.BALROG_NAME)); - balrogList.add(bossMobEntity.getLivingEntity()); - - balrogVisualEffectLoop((Silverfish) bossMobEntity.getLivingEntity()); - - BossMobDeathCountdown.startDeathCountdown(bossMobEntity.getLivingEntity()); - - } - - private static void balrogVisualEffectLoop(Silverfish balrog) { - - new BukkitRunnable() { - @Override - public void run() { - - if (!balrog.isValid()) { - - cancel(); - return; - - } - - balrog.getWorld().spawnParticle(Particle.FLAME, balrog.getLocation(), 2, 0.1, 0.1, 0.1, 0.05); - balrog.getWorld().spawnParticle(Particle.SMOKE_LARGE, balrog.getLocation(), 4, 0.1, 0.1, 0.1, 0.05); - - } - - }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); - - } - - private static HashSet balrogList = new HashSet<>(); - - @EventHandler - public void onDeath(EntityDeathEvent event) { - - if (!balrogList.contains(event.getEntity())) return; - - balrogList.remove(event.getEntity()); - - DwarvenGreed dwarvenGreed = new DwarvenGreed(); - ItemStack dwarvenGreedItemStack = dwarvenGreed.constructItemStack(); - - event.getEntity().getWorld().dropItem(event.getEntity().getLocation(), dwarvenGreedItemStack); - - } - - @EventHandler(priority = EventPriority.HIGHEST) - public void onHit(EntityDamageEvent event) { - - if (event.isCancelled()) return; - if (!balrogList.contains(event.getEntity())) return; - if (event.getFinalDamage() < 2) return; - - spawnTrashMobs((Silverfish) event.getEntity()); - spawnTrashMobs((Silverfish) event.getEntity()); - - } - - private static void spawnTrashMobs(Silverfish balrog) { - - TrashMobEntity trashMobEntity = new TrashMobEntity(EntityType.SILVERFISH, balrog.getLocation(), - ChatColorConverter.convert(ConfigValues.eventsConfig.getString(EventsConfig.BALROG_TRASH_MOB_NAME))); - - trashMobVisualEffect((Silverfish) trashMobEntity.getLivingEntity()); - - } - - private static void trashMobVisualEffect(Silverfish raug) { - - new BukkitRunnable() { - - @Override - public void run() { - - if (!raug.isValid() || raug.isDead()) { - - cancel(); - return; - - } - - raug.getWorld().spawnParticle(Particle.FLAME, raug.getLocation(), 1, 0.1, 0.1, 0.1, 0.05); - raug.getWorld().spawnParticle(Particle.SMOKE_LARGE, raug.getLocation(), 1, 0.1, 0.1, 0.1, 0.05); - - } - - }.runTaskTimer(MetadataHandler.PLUGIN, 1, 1); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/events/mobs/Fae.java b/src/main/java/com/magmaguy/elitemobs/events/mobs/Fae.java deleted file mode 100644 index 60f7c7fba..000000000 --- a/src/main/java/com/magmaguy/elitemobs/events/mobs/Fae.java +++ /dev/null @@ -1,226 +0,0 @@ -package com.magmaguy.elitemobs.events.mobs; - -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.EventsConfig; -import com.magmaguy.elitemobs.events.mobs.sharedeventproperties.ActionDynamicBossLevelConstructor; -import com.magmaguy.elitemobs.items.uniqueitems.TheFeller; -import com.magmaguy.elitemobs.mobconstructor.ActionBossMobEntity; -import com.magmaguy.elitemobs.mobpowers.offensivepowers.AttackFire; -import com.magmaguy.elitemobs.mobpowers.offensivepowers.AttackFreeze; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Particle; -import org.bukkit.entity.*; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDeathEvent; -import org.bukkit.inventory.ItemStack; -import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.util.Vector; - -import java.util.Arrays; -import java.util.HashSet; -import java.util.UUID; -import java.util.concurrent.ThreadLocalRandom; - -public class Fae implements Listener { - - public static void spawnFae(Location location) { - - vexSpawnEffect(location); - - } - - private static void vexSpawnEffect(Location location) { - - new BukkitRunnable() { - - int counter = 0; - - @Override - public void run() { - - if (counter > 20 * 3) { - - initializeVex(location); - cancel(); - return; - - } - - location.getWorld().spawnParticle(Particle.WATER_DROP, location, 5, 0.1, 0.1, 0.1, 1); - location.getWorld().spawnParticle(Particle.FLAME, location, 3, 0.1, 0.1, 0.1, 0.01); - location.getWorld().spawnParticle(Particle.SPELL, location, 3, 0.1, 0.1, 0.1, 0.02); - - counter++; - - } - - }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); - - } - - private static void initializeVex(Location location) { - - /* - Good for all fae - */ - int level = ActionDynamicBossLevelConstructor.determineDynamicBossLevel(location) / 3; - - /* - Construct specific fae - */ - ActionBossMobEntity fireFaeBoss = new ActionBossMobEntity( - EntityType.VEX, - location, - level, - ConfigValues.eventsConfig.getString(EventsConfig.FAE_NAME)); - - ActionBossMobEntity lightningFaeBoss = new ActionBossMobEntity( - EntityType.VEX, - location, - level, - ConfigValues.eventsConfig.getString(EventsConfig.FAE_NAME), - new HashSet<>(Arrays.asList(new AttackFire()))); - - ActionBossMobEntity frostFaeBoss = new ActionBossMobEntity( - EntityType.VEX, - location, - level, - ConfigValues.eventsConfig.getString(EventsConfig.FAE_NAME), - new HashSet<>(Arrays.asList(new AttackFreeze()))); - - faeList.addAll(Arrays.asList(lightningFaeBoss.getLivingEntity(), fireFaeBoss.getLivingEntity(), frostFaeBoss.getLivingEntity())); - - faeVisualEffect((Vex) lightningFaeBoss.getLivingEntity(), faeType.LIGHTING_FAE); - faeVisualEffect((Vex) fireFaeBoss.getLivingEntity(), faeType.FIRE_FAE); - faeVisualEffect((Vex) frostFaeBoss.getLivingEntity(), faeType.FROST_FAE); - - initializeSmiteAttack((Vex) lightningFaeBoss.getLivingEntity()); - - } - - private enum faeType { - - LIGHTING_FAE, - FIRE_FAE, - FROST_FAE - - } - - private static void faeVisualEffect(Vex fae, faeType faeType) { - - Particle particle = Particle.SMOKE_LARGE; - - switch (faeType) { - - case LIGHTING_FAE: - particle = Particle.SPELL; - break; - case FIRE_FAE: - particle = Particle.FLAME; - break; - case FROST_FAE: - particle = Particle.WATER_DROP; - break; - - } - - final Particle finalParticle = particle; - - new BukkitRunnable() { - - UUID uuid = fae.getUniqueId(); - - @Override - public void run() { - - Vex localFae = fae; - - if (!localFae.isValid()) - if (Bukkit.getEntity(uuid) != null && Bukkit.getEntity(uuid).isValid()) - localFae = (Vex) Bukkit.getEntity(uuid); - - if (localFae.isDead()) { - - cancel(); - return; - - } - - switch (finalParticle) { - - case SPELL: - localFae.getWorld().spawnParticle(finalParticle, localFae.getLocation().add(new Vector(0, 0.25, 0)), 3, 0.1, 0.1, 0.1, 0.02); - break; - case FLAME: - localFae.getWorld().spawnParticle(finalParticle, localFae.getLocation().add(new Vector(0, 0.25, 0)), 3, 0.1, 0.1, 0.1, 0.01); - break; - case WATER_DROP: - localFae.getWorld().spawnParticle(finalParticle, localFae.getLocation().add(new Vector(0, 0.25, 0)), 5, 0.1, 0.1, 0.1, 1); - break; - - } - - - } - - }.runTaskTimer(MetadataHandler.PLUGIN, 1, 1); - - } - - private static void initializeSmiteAttack(Vex lightingFae) { - - new BukkitRunnable() { - - UUID uuid = lightingFae.getUniqueId(); - - @Override - public void run() { - - Vex localFae = lightingFae; - - if (!lightingFae.isValid()) - if (Bukkit.getEntity(uuid) != null && Bukkit.getEntity(uuid).isValid()) - localFae = (Vex) Bukkit.getEntity(uuid); - - if (localFae.isDead()) { - - cancel(); - return; - - } - - for (Entity entity : localFae.getNearbyEntities(16, 16, 16)) { - - if (entity instanceof Player) { - - entity.getWorld().strikeLightning(entity.getLocation()); - - } - - } - - } - - }.runTaskTimer(MetadataHandler.PLUGIN, 20 * 20, 20 * 20); - - } - - private static HashSet faeList = new HashSet<>(); - - @EventHandler - public void onFaeDeath(EntityDeathEvent event) { - - if (!faeList.contains(event.getEntity())) return; - if (ThreadLocalRandom.current().nextDouble() > 0.33) return; - - TheFeller theFeller = new TheFeller(); - ItemStack theFellerItemStack = theFeller.constructItemStack(); - - event.getEntity().getWorld().dropItem(event.getEntity().getLocation(), theFellerItemStack); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/events/mobs/Kraken.java b/src/main/java/com/magmaguy/elitemobs/events/mobs/Kraken.java deleted file mode 100644 index c5bd902e7..000000000 --- a/src/main/java/com/magmaguy/elitemobs/events/mobs/Kraken.java +++ /dev/null @@ -1,227 +0,0 @@ -package com.magmaguy.elitemobs.events.mobs; - -import com.magmaguy.elitemobs.ChatColorConverter; -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.EventsConfig; -import com.magmaguy.elitemobs.events.mobs.sharedeventproperties.BossMobDeathCountdown; -import com.magmaguy.elitemobs.items.uniqueitems.DepthsSeeker; -import com.magmaguy.elitemobs.mobpowers.ProjectileLocationGenerator; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Particle; -import org.bukkit.entity.*; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.event.entity.EntityDamageEvent; -import org.bukkit.event.entity.EntityDeathEvent; -import org.bukkit.inventory.ItemStack; -import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.util.Vector; - -import java.util.HashSet; -import java.util.UUID; - -public class Kraken implements Listener { - - private static HashSet krakens = new HashSet<>(); - - public static boolean isKraken(Squid kraken) { - return krakens.contains(kraken); - } - - public static void removeKraken(Squid kraken) { - krakens.remove(kraken); - } - - private static HashSet fireballs = new HashSet<>(); - - public static boolean isFireball(Fireball fireball) { - return fireballs.contains(fireball); - } - - public static void removeFireball(Fireball fireball) { - fireballs.remove(fireball); - } - - public static void spawnKraken(Location location) { - krakenSpawnEffect(location); - } - - private static void krakenSpawnEffect(Location location) { - - new BukkitRunnable() { - - int counter = 0; - - @Override - public void run() { - - if (counter > 20 * 3) { - - initializeKraken(location); - cancel(); - return; - - } - - location.getWorld().spawnParticle(Particle.PORTAL, location, 20, 1, 1, 1, 0.1); - - counter++; - - } - - - }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); - - } - - private static void initializeKraken(Location location) { - - Squid kraken = (Squid) location.getWorld().spawnEntity(location, EntityType.SQUID); - - krakens.add(kraken); - - /* - This boss is not fully integrated into the plugin yet, might not really make the cut - */ - - kraken.setMaxHealth(100); - kraken.setHealth(100); - - kraken.setCustomName(ChatColorConverter.convert(ConfigValues.eventsConfig.getString(EventsConfig.KRAKEN_NAME))); - kraken.setCustomNameVisible(true); - - krakenDamageLoop(kraken); - krakenVisualEffectLoop(kraken); - - BossMobDeathCountdown.startDeathCountdown(kraken); - - } - - private static void krakenDamageLoop(Squid kraken) { - - new BukkitRunnable() { - - @Override - public void run() { - - if (kraken.isDead()) { - cancel(); - return; - } - - for (Entity entity : kraken.getNearbyEntities(16, 16, 16)) - if (entity instanceof Player) - fireballInitializer(kraken, (Player) entity); - - } - - }.runTaskTimer(MetadataHandler.PLUGIN, 20 * 3, 20 * 3); - - } - - private static void fireballInitializer(Squid kraken, Player target) { - - Location offsetLocation = ProjectileLocationGenerator.generateLocation(kraken, target); - Fireball repeatingFireball = (Fireball) kraken.getWorld().spawnEntity(offsetLocation, EntityType.FIREBALL); - Vector targetterToTargetted = target.getEyeLocation().subtract(repeatingFireball.getLocation()).toVector() - .normalize().multiply(1); - - repeatingFireball.setDirection(targetterToTargetted); - repeatingFireball.setIsIncendiary(true); - repeatingFireball.setYield(2F); - - fireballs.add(repeatingFireball); - - } - - private static void krakenVisualEffectLoop(Squid kraken) { - - new BukkitRunnable() { - - UUID uuid = kraken.getUniqueId(); - - @Override - public void run() { - - Squid localKraken = kraken; - - if (!kraken.isValid()) - if (Bukkit.getEntity(uuid) != null) - localKraken = (Squid) Bukkit.getEntity(uuid); - - if (kraken.isDead()) { - - cancel(); - return; - - } - - localKraken.getWorld().spawnParticle(Particle.FLAME, localKraken.getLocation(), 10, 0.1, 0.1, 0.1, 0.05); - - } - - }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); - - } - - @EventHandler - public void onSuffocate(EntityDamageEvent event) { - - if (event.isCancelled()) return; - if (!event.getEntity().getType().equals(EntityType.SQUID)) return; - if (!isKraken((Squid) event.getEntity())) return; - if (!event.getCause().equals(EntityDamageEvent.DamageCause.DROWNING) && - !event.getCause().equals(EntityDamageEvent.DamageCause.FIRE)) return; - - event.setCancelled(true); - - } - - @EventHandler - public void onSelfDamage(EntityDamageByEntityEvent event) { - - if (event.getDamager() instanceof Fireball && ((Fireball) event.getDamager()).getShooter() != null && - ((Fireball) event.getDamager()).getShooter() instanceof Squid) { - event.setCancelled(true); - removeFireball((Fireball) event.getDamager()); - } - - } - - @EventHandler - public void fireballDamage(EntityDamageByEntityEvent event) { - - if (event.isCancelled()) return; - if (!event.getEntity().getType().equals(EntityType.PLAYER)) return; - if (!event.getDamager().getType().equals(EntityType.FIREBALL)) return; - if (!isFireball((Fireball) event.getDamager())) return; - - for (EntityDamageByEntityEvent.DamageModifier modifier : EntityDamageByEntityEvent.DamageModifier.values()) - if (event.isApplicable(modifier)) - event.setDamage(modifier, 0); - - event.setDamage(EntityDamageEvent.DamageModifier.BASE, 2); - - removeFireball((Fireball) event.getDamager()); - - } - - @EventHandler - public void onDeath(EntityDeathEvent event) { - - if (!event.getEntity().getType().equals(EntityType.SQUID)) return; - if (!isKraken((Squid) event.getEntity())) return; - - DepthsSeeker depthsSeeker = new DepthsSeeker(); - ItemStack depthSeekerItemStack = depthsSeeker.constructItemStack(); - event.getEntity().getWorld().dropItem(event.getEntity().getLocation(), depthSeekerItemStack); - removeKraken((Squid) event.getEntity()); - - } - -} - - diff --git a/src/main/java/com/magmaguy/elitemobs/events/mobs/TheReturned.java b/src/main/java/com/magmaguy/elitemobs/events/mobs/TheReturned.java deleted file mode 100644 index c71a3aa13..000000000 --- a/src/main/java/com/magmaguy/elitemobs/events/mobs/TheReturned.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.events.mobs; - -import com.magmaguy.elitemobs.ChatColorConverter; -import com.magmaguy.elitemobs.EntityTracker; -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.EventsConfig; -import com.magmaguy.elitemobs.events.DeadMoon; -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Husk; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Zombie; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDeathEvent; -import org.bukkit.event.entity.EntitySpawnEvent; -import org.bukkit.inventory.ItemStack; -import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.util.Vector; - -import java.util.HashSet; -import java.util.concurrent.ThreadLocalRandom; - -public class TheReturned implements Listener { - - private static HashSet theReturnedList = new HashSet<>(); - - public static boolean isTheReturned(LivingEntity livingEntity) { - return theReturnedList.contains(livingEntity); - } - - @EventHandler - public void onSpawn(EntitySpawnEvent event) { - - if (!DeadMoon.eventOngoing) return; - - if (event.getEntity() instanceof LivingEntity && theReturnedList.contains(event.getEntity())) - spawnTheReturned((Zombie) event.getEntity()); - - } - - private void spawnTheReturned(Zombie zombie) { - - /* - Wait a tick before spawning as third party compatibility can get messy with spawn events - */ - new BukkitRunnable() { - - @Override - public void run() { - - if (!zombie.isValid()) return; - - if (theReturnedList.contains(zombie)) return; - - int mobLevel; - - if (EntityTracker.isEliteMob(zombie)) - mobLevel = (int) Math.ceil(EntityTracker.getEliteMobEntity(zombie).getLevel() / 2); - else mobLevel = 1; - - theReturnedConstructor(mobLevel, zombie); - theReturnedConstructor(mobLevel, zombie); - - } - - }.runTaskLater(MetadataHandler.PLUGIN, 1); - - } - - public static void theReturnedConstructor(int mobLevel, Zombie zombie) { - - Location spawnLocation = zombie.getLocation(); - - Husk theReturned = (Husk) spawnLocation.getWorld().spawnEntity(spawnLocation, EntityType.HUSK); - - EliteMobEntity eliteMobEntity = new EliteMobEntity(theReturned, mobLevel); - eliteMobEntity.setHasCustomArmor(true); - eliteMobEntity.setHasCustomPowers(true); - eliteMobEntity.setHasStacking(false); - eliteMobEntity.setName(ChatColorConverter.convert(ConfigValues.eventsConfig.getString(EventsConfig.DEAD_MOON_THE_RETURNED_NAME))); - - double x = ThreadLocalRandom.current().nextDouble() - 0.5; - double z = ThreadLocalRandom.current().nextDouble() - 0.5; - - theReturned.setVelocity(new Vector(x, 0.5, z)); - - new BukkitRunnable() { - - @Override - public void run() { - - theReturned.getEquipment().setBoots(new ItemStack(Material.AIR)); - theReturned.getEquipment().setLeggings(new ItemStack(Material.AIR)); - theReturned.getEquipment().setChestplate(new ItemStack(Material.AIR)); - theReturned.getEquipment().setHelmet(new ItemStack(Material.AIR)); - theReturned.getEquipment().setItemInMainHand(new ItemStack(Material.AIR)); - - } - - }.runTaskLater(MetadataHandler.PLUGIN, 1); - - } - - @EventHandler - public void onDeath(EntityDeathEvent event) { - theReturnedList.remove(event.getEntity()); - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/events/mobs/TreasureGoblin.java b/src/main/java/com/magmaguy/elitemobs/events/mobs/TreasureGoblin.java deleted file mode 100644 index c0a940596..000000000 --- a/src/main/java/com/magmaguy/elitemobs/events/mobs/TreasureGoblin.java +++ /dev/null @@ -1,443 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.events.mobs; - -import com.magmaguy.elitemobs.ChatColorConverter; -import com.magmaguy.elitemobs.EntityTracker; -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.EventsConfig; -import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; -import com.magmaguy.elitemobs.events.BossSpecialAttackDamage; -import com.magmaguy.elitemobs.events.EventMessage; -import com.magmaguy.elitemobs.events.mobs.sharedeventproperties.DynamicBossLevelConstructor; -import com.magmaguy.elitemobs.items.LootTables; -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; -import com.magmaguy.elitemobs.mobconstructor.TimedBossMobEntity; -import com.magmaguy.elitemobs.mobpowers.PowerCooldown; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.Particle; -import org.bukkit.entity.*; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.event.entity.EntityDeathEvent; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; -import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.util.Vector; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.concurrent.ThreadLocalRandom; - -public class TreasureGoblin implements Listener { - - private static HashSet treasureGoblinList = new HashSet<>(); - private static HashSet radialGoldExplosionCooldown = new HashSet<>(); - private static HashSet goldShotgunCooldown = new HashSet<>(); - - public static EliteMobEntity getTreasureGoblin(Zombie zombie) { - if (treasureGoblinList.isEmpty()) return null; - for (TimedBossMobEntity bossMobEntity : treasureGoblinList) - if (bossMobEntity.getLivingEntity().equals(zombie)) - return bossMobEntity; - return null; - } - - public static void createGoblin(Location location) { - - int mobLevel = DynamicBossLevelConstructor.findDynamicBossLevel(); - TimedBossMobEntity treasureGoblinPluginEntity = new TimedBossMobEntity(EntityType.ZOMBIE, location, mobLevel, - ConfigValues.eventsConfig.getString(EventsConfig.TREASURE_GOBLIN_NAME)); - - treasureGoblinList.add(treasureGoblinPluginEntity); - - ((Zombie) treasureGoblinPluginEntity.getLivingEntity()).setBaby(true); - - equipTreasureGoblin((Zombie) treasureGoblinPluginEntity.getLivingEntity()); - EventMessage.sendEventMessage(treasureGoblinPluginEntity.getLivingEntity(), ConfigValues.eventsConfig.getString(EventsConfig.SMALL_TREASURE_GOBLIN_EVENT_ANNOUNCEMENT_TEXT)); - - } - - @EventHandler - public void onDeath(EntityDeathEvent event) { - - if (!event.getEntity().getType().equals(EntityType.ZOMBIE)) return; - - EliteMobEntity eliteMobEntity = getTreasureGoblin((Zombie) event.getEntity()); - if (eliteMobEntity == null) return; - - Zombie zombieKing = (Zombie) event.getEntity(); - - for (int i = 0; i < ConfigValues.eventsConfig.getInt(EventsConfig.SMALL_TREASURE_GOBLIN_REWARD); i++) - LootTables.generateLoot(eliteMobEntity); - - - for (Player player : Bukkit.getServer().getOnlinePlayers()) { - - if (zombieKing.getKiller() != null) { - - String newMessage = ConfigValues.eventsConfig.getString(EventsConfig.SMALL_TREASURE_GOBLIN_EVENT_PLAYER_END_TEXT) - .replace("$player", (zombieKing).getKiller().getDisplayName()); - player.sendMessage(ChatColorConverter.convert(newMessage)); - - } else - player.sendMessage(ChatColorConverter.convert(ConfigValues.eventsConfig.getString(EventsConfig.SMALL_TREASURE_GOBLIN_EVENT_OTHER_END_TEXT))); - - } - - } - - @EventHandler - public void onHit(EntityDamageByEntityEvent event) { - - if (!(event.getDamager().getType().equals(EntityType.ZOMBIE) || - event.getDamager() instanceof Projectile && ((Projectile) event.getDamager()).getShooter() instanceof Zombie)) - return; - - if (ThreadLocalRandom.current().nextDouble() > 0.5) return; - - LivingEntity livingEntity; - - if (event.getDamager() instanceof Projectile) - livingEntity = (LivingEntity) ((Projectile) event.getDamager()).getShooter(); - else - livingEntity = (LivingEntity) event.getDamager(); - - EliteMobEntity eliteMobEntity = getTreasureGoblin((Zombie) livingEntity); - if (eliteMobEntity == null) return; - - if (!PowerCooldown.isInCooldown(eliteMobEntity, radialGoldExplosionCooldown)) { - - PowerCooldown.startCooldownTimer(eliteMobEntity, radialGoldExplosionCooldown, - 20 * ConfigValues.eventsConfig.getInt(EventsConfig.TREASURE_GOBLIN_RADIAL_EXPLOSION)); - radialGoldExplosionInitializer((Zombie) event.getDamager()); - - } else if (!PowerCooldown.isInCooldown(eliteMobEntity, goldShotgunCooldown)) { - - PowerCooldown.startCooldownTimer(eliteMobEntity, goldShotgunCooldown, - 20 * ConfigValues.eventsConfig.getInt(EventsConfig.TREASURE_GOBLIN_GOLD_SHOTGUN_INTERVAL)); - goldShotgunInitializer((Zombie) event.getDamager(), livingEntity.getLocation()); - - } - - } - - private void radialGoldExplosionInitializer(Zombie zombie) { - - zombie.setAI(false); - - new BukkitRunnable() { - - int counter = 0; - - @Override - public void run() { - - if (counter == 20 * 1.5) { - - radialGoldExplosion(zombie); - zombie.setAI(true); - cancel(); - - } - - if (ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.ENABLE_WARNING_VISUAL_EFFECTS)) - zombie.getWorld().spawnParticle(Particle.SMOKE_NORMAL, zombie.getLocation(), counter, 1, 1, 1, 0); - - counter++; - - } - - }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); - - } - - private static void radialGoldExplosion(Zombie zombie) { - - int projectileCount = 200; - List itemList = new ArrayList<>(); - - for (int i = 0; i < projectileCount; i++) { - - double x = ThreadLocalRandom.current().nextDouble() - 0.5; - double y = ThreadLocalRandom.current().nextDouble() / 1.5; - double z = ThreadLocalRandom.current().nextDouble() - 0.5; - - Vector locationAdjuster = new Vector(x, 0, z).normalize(); - - Location zombieLocation = zombie.getLocation().add(new Vector(0, 0.5, 0)); - Location projectileLocation = zombieLocation.add(locationAdjuster); - ItemStack visualProjectileItemStack = new ItemStack(Material.GOLD_NUGGET, 1); - - /* - Set custom lore to prevent item stacking - */ - ItemMeta itemMeta = visualProjectileItemStack.getItemMeta(); - List lore = new ArrayList<>(); - lore.add("" + ThreadLocalRandom.current().nextDouble() + "" + ThreadLocalRandom.current().nextDouble()); - itemMeta.setLore(lore); - visualProjectileItemStack.setItemMeta(itemMeta); - - Item visualProjectile = projectileLocation.getWorld().dropItem(projectileLocation, visualProjectileItemStack); - - Vector velocity = new Vector(x, y, z).multiply(2); - visualProjectile.setVelocity(velocity); - visualProjectile.setPickupDelay(Integer.MAX_VALUE); - EntityTracker.registerCullableEntity(visualProjectile); - - itemList.add(visualProjectile); - - } - - new BukkitRunnable() { - - int counter = 0; - - @Override - public void run() { - - if (itemList.size() == 0) cancel(); - - Iterator iterator = itemList.iterator(); - - while (iterator.hasNext()) { - - Item item = iterator.next(); - - if (counter > 20 * 5) { - - if (item != null && item.isValid()) iterator.remove(); - if (item != null && item.isValid()) item.remove(); - continue; - - } - - if (item == null || !item.isValid() || item.isDead()) - iterator.remove(); - - else if (item.isOnGround()) { - iterator.remove(); - item.remove(); - } else if (goldNuggetDamage(item.getNearbyEntities(0, 0, 0), zombie)) { - - iterator.remove(); - item.remove(); - - } - - } - - if (counter > 20 * 5) - cancel(); - - counter++; - - } - - }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); - - } - - private static void goldShotgunInitializer(Zombie zombie, Location targetLocation) { - - zombie.setAI(false); - - List locationList = new ArrayList<>(); - - int projectileCount = 200; - - for (int i = 0; i < projectileCount; i++) { - - double x = ThreadLocalRandom.current().nextDouble() * 2 - 1; - double y = ThreadLocalRandom.current().nextDouble() * 2 - 1; - double z = ThreadLocalRandom.current().nextDouble() * 2 - 1; - - Location tempLocation = targetLocation.clone(); - - Location simulatedLocation = tempLocation.add(new Location(tempLocation.getWorld(), 0.0, 1.0, 0.0)) - .add(new Location(tempLocation.getWorld(), x, y, z)); - - Vector toPlayer = simulatedLocation.subtract(zombie.getLocation()).toVector().normalize(); - - locationList.add(toPlayer); - - } - - new BukkitRunnable() { - - int counter = 0; - - @Override - public void run() { - - if (counter == 20 * 1) { - - goldShotgun(zombie, targetLocation); - zombie.setAI(true); - cancel(); - - } - - if (ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.ENABLE_WARNING_VISUAL_EFFECTS)) { - - - Location zombieLocation = zombie.getLocation().clone(); - - int particleCount = 20; - - for (int i = 0; i < particleCount; i++) { - - double x = ThreadLocalRandom.current().nextDouble() * 2 - 1; - double y = ThreadLocalRandom.current().nextDouble() * 2 - 1; - double z = ThreadLocalRandom.current().nextDouble() * 2 - 1; - - Location tempLocation = targetLocation.clone(); - - Location simulatedLocation = tempLocation.add(new Location(tempLocation.getWorld(), 0.0, 1.0, 0.0)) - .add(new Location(tempLocation.getWorld(), x, y, z)); - - Vector toTarget = simulatedLocation.subtract(zombie.getLocation()).toVector().normalize(); - - zombieLocation.getWorld().spawnParticle(Particle.SMOKE_NORMAL, zombieLocation.clone().add(new Vector(0, 0.5, 0)), 0, toTarget.getX(), toTarget.getY(), toTarget.getZ(), 0.75); - - } - - } - - counter++; - - } - - }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); - - } - - private static void goldShotgun(Zombie zombie, Location livingEntityLocation) { - - int projectileCount = 200; - ItemStack visualProjectileItemStack = new ItemStack(Material.GOLD_NUGGET, 1); - List itemList = new ArrayList<>(); - - for (int i = 0; i < projectileCount; i++) { - - double x = ThreadLocalRandom.current().nextDouble() * 2 - 1; - double y = ThreadLocalRandom.current().nextDouble() * 2 - 1; - double z = ThreadLocalRandom.current().nextDouble() * 2 - 1; - - Location tempLocation = livingEntityLocation.clone(); - - Location simulatedLocation = tempLocation.add(new Location(tempLocation.getWorld(), 0.0, 1.0, 0.0)) - .add(new Location(tempLocation.getWorld(), x, y, z)); - - Vector toPlayer = simulatedLocation.subtract(zombie.getLocation()).toVector().normalize(); - - /* - Set custom lore to prevent item stacking - */ - ItemMeta itemMeta = visualProjectileItemStack.getItemMeta(); - List lore = new ArrayList<>(); - lore.add("" + ThreadLocalRandom.current().nextDouble() + "" + ThreadLocalRandom.current().nextDouble()); - itemMeta.setLore(lore); - visualProjectileItemStack.setItemMeta(itemMeta); - - Item visualProjectile = zombie.getLocation().add(new Location(livingEntityLocation.getWorld(), 0.0, 1.0, 0.0)).getWorld().dropItem(zombie.getLocation(), visualProjectileItemStack); - - visualProjectile.setGravity(false); - visualProjectile.setVelocity(toPlayer.multiply(0.9)); - visualProjectile.setPickupDelay(Integer.MAX_VALUE); - EntityTracker.registerCullableEntity(visualProjectile); - - itemList.add(visualProjectile); - - } - - new BukkitRunnable() { - - int counter = 0; - - @Override - public void run() { - - if (itemList.size() == 0) cancel(); - - Iterator iterator = itemList.iterator(); - - while (iterator.hasNext()) { - - Item item = iterator.next(); - - if (item == null || !item.isValid() || item.isDead()) - iterator.remove(); - - else if (goldNuggetDamage(item.getNearbyEntities(0.5, 0.5, 0.5), zombie)) { - - iterator.remove(); - item.remove(); - - } - - - if (counter > 20 * 3) { - - iterator.remove(); - if (item != null) item.remove(); - - } - - } - - if (counter > 20 * 3) - cancel(); - - counter++; - - } - - }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); - - } - - private static boolean goldNuggetDamage(List entityList, Zombie zombie) { - - for (Entity entity : entityList) { - - if (!(entity instanceof LivingEntity)) continue; - if (entity.getType().equals(EntityType.ZOMBIE)) continue; - return BossSpecialAttackDamage.dealSpecialDamage(zombie, (LivingEntity) entity, 1); - - } - - return false; - - } - - public static void equipTreasureGoblin(Zombie zombie) { - - zombie.getEquipment().setHelmet(new ItemStack(Material.GOLD_HELMET, 1)); - zombie.getEquipment().setChestplate(new ItemStack(Material.GOLD_CHESTPLATE)); - zombie.getEquipment().setLeggings(new ItemStack(Material.GOLD_LEGGINGS)); - zombie.getEquipment().setBoots(new ItemStack(Material.GOLD_BOOTS)); - - } - - -} diff --git a/src/main/java/com/magmaguy/elitemobs/events/mobs/ZombieKing.java b/src/main/java/com/magmaguy/elitemobs/events/mobs/ZombieKing.java deleted file mode 100644 index fb9d64c75..000000000 --- a/src/main/java/com/magmaguy/elitemobs/events/mobs/ZombieKing.java +++ /dev/null @@ -1,529 +0,0 @@ -package com.magmaguy.elitemobs.events.mobs; - -import com.magmaguy.elitemobs.ChatColorConverter; -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.EventsConfig; -import com.magmaguy.elitemobs.events.BossSpecialAttackDamage; -import com.magmaguy.elitemobs.events.DeadMoon; -import com.magmaguy.elitemobs.events.EventMessage; -import com.magmaguy.elitemobs.events.mobs.sharedeventproperties.DynamicBossLevelConstructor; -import com.magmaguy.elitemobs.items.uniqueitems.ZombieKingsAxe; -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; -import com.magmaguy.elitemobs.mobconstructor.TimedBossMobEntity; -import com.magmaguy.elitemobs.mobpowers.PowerCooldown; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.Particle; -import org.bukkit.entity.*; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.event.entity.EntityDeathEvent; -import org.bukkit.inventory.ItemStack; -import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.util.Vector; - -import java.util.HashSet; -import java.util.UUID; -import java.util.concurrent.ThreadLocalRandom; - -public class ZombieKing implements Listener { - - private static HashSet zombieKingList = new HashSet<>(); - - public static EliteMobEntity getZombieKing(Zombie zombie) { - if (zombieKingList.isEmpty()) return null; - for (EliteMobEntity bossMobEntity : zombieKingList) - if (bossMobEntity.getLivingEntity().equals(zombie)) - return bossMobEntity; - return null; - } - - public static void spawnZombieKing(Location location) { - - DeadMoon.entityQueued = false; - - int kingLevel = DynamicBossLevelConstructor.findDynamicBossLevel(); - TimedBossMobEntity zombieKing = new TimedBossMobEntity(EntityType.ZOMBIE, location, kingLevel, - ConfigValues.eventsConfig.getString(EventsConfig.DEAD_MOON_ZOMBIE_KING_NAME)); - - zombieKingList.add(zombieKing); - zombieKingFlair((Zombie) zombieKing.getLivingEntity()); - - ((Zombie) zombieKing.getLivingEntity()).setBaby(false); - - zombieKing.getLivingEntity().getEquipment().setBoots(new ItemStack(Material.DIAMOND_BOOTS)); - zombieKing.getLivingEntity().getEquipment().setLeggings(new ItemStack(Material.DIAMOND_LEGGINGS)); - zombieKing.getLivingEntity().getEquipment().setChestplate(new ItemStack(Material.DIAMOND_CHESTPLATE)); - zombieKing.getLivingEntity().getEquipment().setHelmet(new ItemStack(Material.GOLD_HELMET)); - zombieKing.getLivingEntity().getEquipment().setItemInMainHand(new ItemStack(Material.GOLD_AXE)); - - EventMessage.sendEventMessage(zombieKing.getLivingEntity(), ConfigValues.eventsConfig.getString(EventsConfig.DEAD_MOON_EVENT_ANNOUNCEMENT_TEXT)); - - } - - private static void zombieKingFlair(Zombie zombieKing) { - - new BukkitRunnable() { - - UUID uuid = zombieKing.getUniqueId(); - - @Override - public void run() { - - Zombie localZombieKing = zombieKing; - - if (!zombieKing.isValid()) - if (Bukkit.getEntity(uuid) != null && Bukkit.getEntity(uuid).isValid()) - localZombieKing = (Zombie) Bukkit.getEntity(uuid); - - if (!zombieKing.isDead()) { - - localZombieKing.getWorld().spawnParticle(Particle.FLAME, localZombieKing.getLocation(), 4, 0.05, 0.15, 0.05, 0.03); - localZombieKing.getWorld().spawnParticle(Particle.FLAME, localZombieKing.getLocation().add(new Vector(0, 0.5, 0)), 3, 0.05, 0.15, 0.05, 0.03); - localZombieKing.getWorld().spawnParticle(Particle.FLAME, localZombieKing.getLocation().add(new Vector(0, 1, 0)), 2, 0.05, 0.15, 0.05, 0.03); - - } else - cancel(); - - } - - }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); - - } - - private static HashSet flamethrowerCooldown = new HashSet<>(); - private static HashSet unholySmiteCooldown = new HashSet<>(); - private static HashSet minionsCooldown = new HashSet<>(); - - @EventHandler - public void onHit(EntityDamageByEntityEvent event) { - - if (!event.getEntity().getType().equals(EntityType.ZOMBIE)) return; - EliteMobEntity eliteMobEntity = getZombieKing((Zombie) event.getEntity()); - if (eliteMobEntity == null) return; - - LivingEntity livingEntity; - - if (event.getDamager() instanceof LivingEntity) - livingEntity = (LivingEntity) event.getDamager(); - else if (event.getDamager() instanceof Projectile && - ((Projectile) event.getDamager()).getShooter() instanceof LivingEntity) - livingEntity = (LivingEntity) ((Projectile) event.getDamager()).getShooter(); - else - livingEntity = null; - - if (livingEntity == null) return; - - if (ThreadLocalRandom.current().nextDouble() < 0.20) { - - if (ThreadLocalRandom.current().nextDouble() < 0.33) { - - if (!PowerCooldown.isInCooldown(eliteMobEntity, flamethrowerCooldown)) { - - PowerCooldown.startCooldownTimer(eliteMobEntity, flamethrowerCooldown, - 20 * ConfigValues.eventsConfig.getInt(EventsConfig.ZOMBIE_KING_FLAMETHROWER_INTERVAL)); - initializeFlamethrower(event.getEntity().getLocation().clone(), livingEntity.getLocation().clone(), (LivingEntity) event.getEntity()); - - } - - } else if (ThreadLocalRandom.current().nextDouble() < 0.66) { - - if (PowerCooldown.isInCooldown(eliteMobEntity, unholySmiteCooldown)) { - - PowerCooldown.startCooldownTimer(eliteMobEntity, unholySmiteCooldown, - 20 * ConfigValues.eventsConfig.getInt(EventsConfig.ZOMBIE_KING_UNHOLY_SMITE_INTERVAL)); - initializeUnholySmite((LivingEntity) event.getEntity()); - - } - - } else { - - if (PowerCooldown.isInCooldown(eliteMobEntity, minionsCooldown)) { - - PowerCooldown.startCooldownTimer(eliteMobEntity, minionsCooldown, - 20 * ConfigValues.eventsConfig.getInt(EventsConfig.ZOMBIE_KING_SUMMON_MINIONS_INTERVAL)); - initializeSummonMinions((LivingEntity) event.getEntity()); - - } - - } - - } - - } - - private static void initializeFlamethrower(Location sourceLocation, Location targetLocation, LivingEntity shooter) { - - Vector toTarget = targetLocation.clone().subtract(sourceLocation).toVector().normalize(); - shooter.setAI(false); - - initializeFlamethrower(sourceLocation, toTarget, shooter, false); - - } - - public static void initializeFlamethrower(Location sourceLocation, Vector targetVector, LivingEntity shooter, boolean shotByPlayer) { - - createDamagePath(sourceLocation.add(new Vector(0, 1, 0)), targetVector, shooter, shotByPlayer); - - } - - private static void createDamagePath(Location sourceLocation, Vector toTarget, LivingEntity shooter, boolean shotByPlayer) { - - int flamePoints = 20; - - new BukkitRunnable() { - - int counter = 0; - - @Override - public void run() { - - if (counter > flamePoints) - cancel(); - - Location newLocation = sourceLocation.add(toTarget); - - flamethrowerDamage(newLocation, shooter, toTarget, shotByPlayer); - - counter++; - - } - - }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); - - } - - private static void flamethrowerDamage(Location location, LivingEntity shooter, Vector directionVector, boolean shotByPlayer) { - - new BukkitRunnable() { - - int counter = 0; - - @Override - public void run() { - - if (counter > 3 * 20) { - - if (!(shooter instanceof Player)) shooter.setAI(true); - cancel(); - - } - - /* - Reserve first second to early warning, remaining two seconds for damage - */ - if (counter > 10) { - - if (counter < 2 * 20) { - - for (int i = 0; i < 5; i++) { - - double offsetX = (ThreadLocalRandom.current().nextDouble() - 0.5) * 0.1 + directionVector.getX(); - double offsetY = (ThreadLocalRandom.current().nextDouble() - 0.5) * 0.1 + directionVector.getY(); - double offsetZ = (ThreadLocalRandom.current().nextDouble() - 0.5) * 0.1 + directionVector.getZ(); - double offsetVelocity = ThreadLocalRandom.current().nextDouble() + 0.05; - - if (shooter instanceof Player) - shooter.getLocation().getWorld().spawnParticle(Particle.FLAME, shooter.getEyeLocation().clone().add(directionVector), 0, offsetX, offsetY, offsetZ, offsetVelocity); - else - shooter.getLocation().getWorld().spawnParticle(Particle.FLAME, shooter.getEyeLocation().clone().subtract(new Vector(0, 0.5, 0)).clone().add(directionVector), 0, offsetX, offsetY, offsetZ, offsetVelocity); - - } - - } - - for (Entity entity : location.getWorld().getNearbyEntities(location, 1, 1, 1)) { - - if (!entity.equals(shooter) && entity instanceof LivingEntity) { - - if (shotByPlayer && entity instanceof Player) { - - //TODO: add pvp mechanics here - - } else { - BossSpecialAttackDamage.dealSpecialDamage(shooter, (LivingEntity) entity, 1); - } - - } - - } - - } - - if (counter < 10 || counter > 2 * 20) { - - for (int i = 0; i < 5; i++) { - - double offsetX = (ThreadLocalRandom.current().nextDouble() - 0.5) * 0.1 + directionVector.getX(); - double offsetY = (ThreadLocalRandom.current().nextDouble() - 0.5) * 0.1 + directionVector.getY(); - double offsetZ = (ThreadLocalRandom.current().nextDouble() - 0.5) * 0.1 + directionVector.getZ(); - double offsetVelocity = ThreadLocalRandom.current().nextDouble() + 0.05; - - if (shooter instanceof Player) - shooter.getLocation().getWorld().spawnParticle(Particle.SMOKE_NORMAL, shooter.getEyeLocation().clone().add(directionVector), 0, offsetX, offsetY, offsetZ, offsetVelocity); - else - shooter.getLocation().getWorld().spawnParticle(Particle.SMOKE_NORMAL, shooter.getEyeLocation().subtract(new Vector(0, 0.5, 0)).clone().add(directionVector), 0, offsetX, offsetY, offsetZ, offsetVelocity); - } - - } - - counter++; - - } - - }.runTaskTimer(MetadataHandler.PLUGIN, 1, 1); - - } - - private void initializeUnholySmite(LivingEntity livingEntity) { - - livingEntity.setAI(false); - unholySmitePhaseOne(livingEntity, Particle.SMOKE_NORMAL, false, 10); - - } - - private void unholySmitePhaseOne(LivingEntity zombieKing, Particle particle, boolean doDamage, double duration) { - - new BukkitRunnable() { - - int counter = 0; - - @Override - public void run() { - - if (counter > duration) { - - if (!doDamage) { - - unholySmitePhaseOne(zombieKing, Particle.FLAME, true, 20 * 2 + 1); - unholySmitePhaseTwo(zombieKing, Particle.SMOKE_NORMAL, false, 10); - - } - - cancel(); - - } - - Vector directionVector = new Vector(0, 1, 0); - - if (!doDamage) { - - spawnUnholySmitePhaseOneParticle(directionVector, zombieKing, particle); - - } else { - - spawnUnholySmitePhaseOneParticle(directionVector, zombieKing, particle); - unholySmiteDamage(zombieKing, 0.5, 50, 0.5); - - } - - counter++; - - } - - }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); - - } - - private void unholySmitePhaseTwo(LivingEntity zombieKing, Particle particle, boolean doDamage, double duration) { - - new BukkitRunnable() { - - int counter = 0; - - @Override - public void run() { - - if (counter > duration) { - - if (!doDamage) { - - unholySmitePhaseTwo(zombieKing, Particle.FLAME, true, 20 * 2 + 0.5); - unholySmitePhaseThree(zombieKing, Particle.SMOKE_NORMAL, false, 10); - - } - cancel(); - - } - - Vector directionVector = new Vector(0, 1, 0); - - if (!doDamage) { - - spawnUnholySmitePhaseTwoParticle(directionVector, zombieKing, particle); - - } else { - - spawnUnholySmitePhaseTwoParticle(directionVector, zombieKing, particle); - unholySmiteDamage(zombieKing, 3, 50, 3); - - } - - counter++; - - } - - }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); - - } - - private void unholySmitePhaseThree(LivingEntity zombieKing, Particle particle, boolean doDamage, double duration) { - - new BukkitRunnable() { - - int counter = 0; - - @Override - public void run() { - - if (counter > duration) { - - if (!doDamage) unholySmitePhaseThree(zombieKing, Particle.FLAME, true, 20 * 2); - else zombieKing.setAI(true); - cancel(); - - } - - if (!doDamage) { - - spawnUnholySmitePhaseThreeParticle(zombieKing, particle); - - } else { - - spawnUnholySmitePhaseThreeParticle(zombieKing, particle); - unholySmiteDamage(zombieKing, 5, 4, 5); - - } - - counter++; - - } - - }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); - - } - - - private void spawnUnholySmitePhaseOneParticle(Vector directionVector, LivingEntity livingEntity, Particle particle) { - - for (int i = 0; i < 10; i++) { - - double offsetVelocity = ThreadLocalRandom.current().nextDouble() * 2; - - double offsetLocationX = (ThreadLocalRandom.current().nextDouble() - 0.5) * 0.5 + livingEntity.getLocation().getX(); - double offsetLocationZ = (ThreadLocalRandom.current().nextDouble() - 0.5) * 0.5 + livingEntity.getLocation().getZ(); - - Location offsetLocation = new Location(livingEntity.getWorld(), offsetLocationX, livingEntity.getLocation().getY(), offsetLocationZ); - - livingEntity.getLocation().getWorld().spawnParticle(particle, offsetLocation, 0, directionVector.getX(), directionVector.getY(), directionVector.getZ(), offsetVelocity); - - } - - } - - private void spawnUnholySmitePhaseTwoParticle(Vector directionVector, LivingEntity livingEntity, Particle particle) { - - for (int i = 0; i < 10; i++) { - - double offsetVelocity = ThreadLocalRandom.current().nextDouble() * 2; - - double offsetLocationX = (ThreadLocalRandom.current().nextDouble() - 0.5) * 3 + livingEntity.getLocation().getX(); - double offsetLocationZ = (ThreadLocalRandom.current().nextDouble() - 0.5) * 3 + livingEntity.getLocation().getZ(); - - Location offsetLocation = new Location(livingEntity.getWorld(), offsetLocationX, livingEntity.getLocation().getY(), offsetLocationZ); - - livingEntity.getLocation().getWorld().spawnParticle(particle, offsetLocation, 0, directionVector.getX(), directionVector.getY(), directionVector.getZ(), offsetVelocity); - - } - - } - - private void spawnUnholySmitePhaseThreeParticle(LivingEntity livingEntity, Particle particle) { - - livingEntity.getLocation().getWorld().spawnParticle(particle, livingEntity.getLocation(), 50, 0.01, 0.01, 0.01, 0.1); - - } - - private void unholySmiteDamage(LivingEntity zombieKing, double range1, double range2, double range3) { - - for (Entity entity : zombieKing.getNearbyEntities(range1, range2, range3)) { - - if (entity instanceof LivingEntity && !entity.equals(zombieKing)) { - - BossSpecialAttackDamage.dealSpecialDamage(zombieKing, (LivingEntity) entity, 1); - } - - } - - } - - private void initializeSummonMinions(LivingEntity zombieKing) { - - zombieKing.setAI(false); - summonMinions(zombieKing); - - } - - private void summonMinions(LivingEntity zombieKing) { - - new BukkitRunnable() { - - int counter = 0; - - @Override - public void run() { - - if (counter > 20 * 3) { - - int amountOfSummonedMobs = 10; - - for (int i = 0; i < amountOfSummonedMobs; i++) - TheReturned.theReturnedConstructor(50, (Zombie) zombieKing); - - zombieKing.setAI(true); - cancel(); - - } - - zombieKing.getWorld().spawnParticle(Particle.PORTAL, zombieKing.getLocation().add(new Vector(0, 1, 0)), 50, 0.01, 0.01, 0.01, 1); - - counter++; - - } - - }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); - - } - - @EventHandler - public void onDeath(EntityDeathEvent event) { - - if (!event.getEntity().getType().equals(EntityType.ZOMBIE)) return; - EliteMobEntity eliteMobEntity = getZombieKing((Zombie) event.getEntity()); - if (eliteMobEntity == null) return; - - Zombie zombieKing = (Zombie) event.getEntity(); - - ZombieKingsAxe zombieKingAxe = new ZombieKingsAxe(); - ItemStack zombieKingAxeItemStack = zombieKingAxe.constructItemStack(); - - zombieKing.getWorld().dropItem(zombieKing.getLocation(), zombieKingAxeItemStack); - - if (event.getEntity().getKiller() != null) { - - String newMessage = ConfigValues.eventsConfig.getString(EventsConfig.DEAD_MOON_EVENT_PLAYER_END_TEXT) - .replace("$player", event.getEntity().getKiller().getDisplayName()); - - EventMessage.sendEventMessage(event.getEntity(), newMessage); - - } else - EventMessage.sendEventMessage(event.getEntity(), ConfigValues.eventsConfig.getString( - ChatColorConverter.convert(EventsConfig.DEAD_MOON_EVENT_OTHER_END_TEXT))); - - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/events/mobs/sharedeventpowers/SpiritWalk.java b/src/main/java/com/magmaguy/elitemobs/events/mobs/sharedeventpowers/SpiritWalk.java deleted file mode 100644 index ec20d674d..000000000 --- a/src/main/java/com/magmaguy/elitemobs/events/mobs/sharedeventpowers/SpiritWalk.java +++ /dev/null @@ -1,181 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.events.mobs.sharedeventpowers; - -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.EventsConfig; -import com.magmaguy.elitemobs.events.mobs.TreasureGoblin; -import com.magmaguy.elitemobs.events.mobs.ZombieKing; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Projectile; -import org.bukkit.entity.Zombie; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.event.entity.EntityDamageEvent; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; -import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.util.Vector; - -import java.util.HashMap; -import java.util.concurrent.ThreadLocalRandom; - -public class SpiritWalk implements Listener { - - HashMap entityHitCount = new HashMap<>(); - - @EventHandler - public void onBossMobGotHit(EntityDamageEvent event) { - - if (!(event.getEntity().getType().equals(EntityType.ZOMBIE) && - (ZombieKing.getZombieKing((Zombie) event.getEntity()) != null || - TreasureGoblin.getTreasureGoblin((Zombie) event.getEntity()) != null))) - return; - - if (entityHitCount.containsKey(event.getEntity())) - entityHitCount.put((LivingEntity) event.getEntity(), entityHitCount.get(event.getEntity()) + 1); - else entityHitCount.put((LivingEntity) event.getEntity(), 1); - - if (entityHitCount.get(event.getEntity()) > ConfigValues.eventsConfig.getInt(EventsConfig.SPIRIT_WALK_HIT_INTERVAL)) { - - initializeSpiritWalk((LivingEntity) event.getEntity()); - entityHitCount.put((LivingEntity) event.getEntity(), 0); - } - - } - - @EventHandler - public void onBossMobHit(EntityDamageByEntityEvent event) { - - if (event.getDamager() instanceof Projectile && !(((Projectile) event.getDamager()).getShooter() instanceof LivingEntity)) - return; - if (event.getEntity().getType().equals(EntityType.ZOMBIE) && - (!(ZombieKing.getZombieKing((Zombie) event.getEntity()) != null || - TreasureGoblin.getTreasureGoblin((Zombie) event.getEntity()) != null))) - return; - if (!(event.getDamager() instanceof LivingEntity)) return; - entityHitCount.put((LivingEntity) event.getDamager(), 0); - - } - - private void initializeSpiritWalk(LivingEntity bossMob) { - - new BukkitRunnable() { - - int counter = 1; - - @Override - public void run() { - - if (counter > 3) cancel(); - - Location bossLocation = bossMob.getLocation().clone(); - - for (int i = 0; i < 20; i++) { - - double randomizedX = (ThreadLocalRandom.current().nextDouble() - 0.5) * 5; - double randomizedY = ThreadLocalRandom.current().nextDouble() - 0.5; - double randomizedZ = (ThreadLocalRandom.current().nextDouble() - 0.5) * 5; - - Vector normalizedVector = new Vector(randomizedX, randomizedY, randomizedZ).normalize().multiply(7).multiply(counter); - - Location newSimulatedLocation = bossLocation.add(normalizedVector).clone(); - - Location newValidLocation = checkLocationValidity(newSimulatedLocation); - - if (newValidLocation != null) { - - spiritWalkAnimation(bossMob, bossMob.getLocation(), newValidLocation.add(new Vector(0.5, 1, 0.5))); - cancel(); - break; - } - - } - - counter++; - - } - - }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); - - } - - private void spiritWalkAnimation(LivingEntity bossMob, Location entityLocation, Location finalLocation) { - - bossMob.setAI(false); - bossMob.setInvulnerable(true); - bossMob.addPotionEffect(new PotionEffect(PotionEffectType.GLOWING, 20 * 10, 1)); - Vector toDestination = finalLocation.clone().subtract(entityLocation.clone()).toVector().normalize().divide(new Vector(2, 2, 2)); - - new BukkitRunnable() { - - int counter = 0; - - @Override - public void run() { - - if (bossMob.getLocation().clone().distance(finalLocation) < 2 || counter > 20 * 10) { - - bossMob.teleport(finalLocation); - bossMob.setAI(true); - bossMob.setInvulnerable(false); - bossMob.removePotionEffect(PotionEffectType.GLOWING); - cancel(); - - } - - bossMob.teleport(bossMob.getLocation().clone().add(toDestination.clone())); - - counter++; - - } - - }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); - - } - - private Location checkLocationValidity(Location simulatedLocation) { - - if (simulatedLocation.getBlock().getType().equals(Material.AIR)) { - - int counter = 1; - - while (true) { - - if (simulatedLocation.getY() < 1) return null; - - Location blockUnderCurrentBlock = simulatedLocation.clone().subtract(new Vector(0, counter, 0)); - - if (blockUnderCurrentBlock.getBlock().getType() != Material.AIR) return blockUnderCurrentBlock; - - if (counter > 10) return null; - - counter++; - - } - - } - - return null; - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/events/mobs/sharedeventproperties/ActionDynamicBossLevelConstructor.java b/src/main/java/com/magmaguy/elitemobs/events/mobs/sharedeventproperties/ActionDynamicBossLevelConstructor.java deleted file mode 100644 index aa2962635..000000000 --- a/src/main/java/com/magmaguy/elitemobs/events/mobs/sharedeventproperties/ActionDynamicBossLevelConstructor.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.magmaguy.elitemobs.events.mobs.sharedeventproperties; - -import com.magmaguy.elitemobs.mobspawning.MobLevelCalculator; -import org.bukkit.Location; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; - -public class ActionDynamicBossLevelConstructor { - - public static int determineDynamicBossLevel(Location bossLocation) { - - int bossLevel = 1; - - for (Entity entity : bossLocation.getWorld().getNearbyEntities(bossLocation, 50, 50, 50)) { - - if (entity instanceof Player) { - - bossLevel += MobLevelCalculator.determineMobLevel((Player) entity); - - } - - } - - return bossLevel; - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/events/mobs/sharedeventproperties/BossMobDeathCountdown.java b/src/main/java/com/magmaguy/elitemobs/events/mobs/sharedeventproperties/BossMobDeathCountdown.java deleted file mode 100644 index 3d6dcdb50..000000000 --- a/src/main/java/com/magmaguy/elitemobs/events/mobs/sharedeventproperties/BossMobDeathCountdown.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.events.mobs.sharedeventproperties; - -import com.magmaguy.elitemobs.ChatColorConverter; -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.EventsConfig; -import com.magmaguy.elitemobs.events.EventMessage; -import org.bukkit.entity.LivingEntity; -import org.bukkit.scheduler.BukkitRunnable; - -public class BossMobDeathCountdown { - - public static void startDeathCountdown(LivingEntity entity) { - - new BukkitRunnable() { - - @Override - public void run() { - - if (entity.isDead()) return; - - entity.remove(); - String eventMessage = ChatColorConverter.convert(ConfigValues.eventsConfig.getString(EventsConfig.EVENT_TIMEOUT_MESSAGE) - .replace("$bossmob", entity.getCustomName())); - EventMessage.sendEventMessage(entity, eventMessage); - - } - - }.runTaskLater(MetadataHandler.PLUGIN, (long) (20 * 60 * ConfigValues.eventsConfig.getDouble(EventsConfig.EVENT_TIMEOUT_TIME))); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/events/mobs/sharedeventproperties/DynamicBossLevelConstructor.java b/src/main/java/com/magmaguy/elitemobs/events/mobs/sharedeventproperties/DynamicBossLevelConstructor.java deleted file mode 100644 index 6cf3aef70..000000000 --- a/src/main/java/com/magmaguy/elitemobs/events/mobs/sharedeventproperties/DynamicBossLevelConstructor.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.magmaguy.elitemobs.events.mobs.sharedeventproperties; - -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; -import com.magmaguy.elitemobs.items.ItemTierFinder; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - -public class DynamicBossLevelConstructor { - - public static int findDynamicBossLevel() { - - int mobLevel = 0; - - for (Player player : Bukkit.getServer().getOnlinePlayers()) - if (ItemTierFinder.findPlayerTier(player) * ConfigValues.mobCombatSettingsConfig.getInt(MobCombatSettingsConfig.PER_TIER_LEVEL_INCREASE) > mobLevel) - mobLevel = (int) ((ItemTierFinder.findPlayerTier(player) + 2.5) * ConfigValues.mobCombatSettingsConfig.getInt(MobCombatSettingsConfig.PER_TIER_LEVEL_INCREASE)); - - if (mobLevel == 0) - mobLevel = (int) (2.5 * ConfigValues.mobCombatSettingsConfig.getInt(MobCombatSettingsConfig.PER_TIER_LEVEL_INCREASE)); - - return mobLevel; - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/explosionregen/Explosion.java b/src/main/java/com/magmaguy/elitemobs/explosionregen/Explosion.java new file mode 100644 index 000000000..2108259ff --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/explosionregen/Explosion.java @@ -0,0 +1,333 @@ +package com.magmaguy.elitemobs.explosionregen; + +import com.magmaguy.elitemobs.EliteMobs; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteExplosionEvent; +import com.magmaguy.elitemobs.combatsystem.EliteProjectile; +import com.magmaguy.elitemobs.config.DefaultConfig; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.meta.ElitePower; +import com.magmaguy.elitemobs.thirdparty.worldguard.WorldGuardFlagChecker; +import com.magmaguy.elitemobs.utils.EntityFinder; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.block.*; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Projectile; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityExplodeEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.persistence.PersistentDataType; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.BoundingBox; +import org.bukkit.util.Vector; + +import java.util.*; + +public class Explosion { + + private static final HashSet explosions = new HashSet<>(); + public final List detonatedBlocks = new ArrayList<>(); + private final int delayBeforeRegen = 2; + + public Explosion(List detonatedBlocks) { + if (detonatedBlocks == null || detonatedBlocks.isEmpty()) return; + //sort blocks bottom to top + HashMap unsortedBlocks = new HashMap<>(); + for (BlockState blockState : detonatedBlocks) + unsortedBlocks.put(blockState, blockState.getY()); + + unsortedBlocks.entrySet().stream().sorted(Map.Entry.comparingByValue()) + .forEachOrdered(x -> this.detonatedBlocks.add(x.getKey())); + + explosions.add(this); + regenerate(); + } + + public static void regenerateAllPendingBlocks() { + for (Explosion explosion : explosions) + explosion.resetAllBlocks(); + } + + public static void generateFakeExplosion(List blockList, Entity entity, ElitePower elitePower, Location explosionSourceLocation) { + generateExplosion(blockList, entity, elitePower, explosionSourceLocation); + } + + public static void generateFakeExplosion(List blockList, Entity entity) { + generateExplosion(blockList, entity, null, null); + } + + private static void generateExplosion(EntityExplodeEvent event) { + generateExplosion(event.blockList(), event.getEntity(), null, event.getEntity().getLocation()); + } + + private static void generateExplosion(List blockList, Entity entity, ElitePower elitePower, Location explosionSource) { + if (!DefaultConfig.isDoExplosionRegen()) return; + if (EliteMobs.worldGuardIsEnabled && + explosionSource != null && + !WorldGuardFlagChecker.doExplosionRegenFlag(explosionSource)) + return; + + ArrayList blockStates = new ArrayList<>(); + + for (Block block : blockList) { + if (block.getType().isAir() || + block.getType().equals(Material.FIRE) || + block.isLiquid() || + EntityTracker.isTemporaryBlock(block)) + continue; + nearbyBlockScan(blockStates, block.getState()); + } + + Entity shooter = EntityFinder.filterRangedDamagers(entity); + EliteEntity eliteEntity = null; + if (shooter != null) + eliteEntity = EntityTracker.getEliteMobEntity(shooter); + + EliteExplosionEvent eliteExplosionEvent = null; + + //for projectiles + if (entity instanceof Projectile) { + eliteExplosionEvent = new EliteExplosionEvent( + eliteEntity, + elitePower = ElitePower.getElitePower(EliteProjectile.readExplosivePower((Projectile) entity)), + entity.getLocation(), + blockStates); + } else { + eliteExplosionEvent = new EliteExplosionEvent( + eliteEntity, + elitePower, + entity.getLocation(), + blockStates); + } + if (eliteExplosionEvent.isCancelled()) return; + + if (explosionSource != null) + eliteExplosionEvent.setExplosionSourceLocation(explosionSource); + + eliteExplosionEvent.visualExplosionEffect(elitePower); + + for (BlockState blockState : blockStates) { + blockState.getBlock().setType(Material.AIR); + blockState.getBlock().getState().update(true); + } + + new Explosion(blockStates); + + } + + /** + * This scans the blocks adjacent to the block getting blown up. This is because certain blocks like ladders will break + * when lacking the support of the source block + * + * @param blockState + */ + private static void nearbyBlockScan(ArrayList blockStates, BlockState blockState) { + queueBlock(blockStates, blockState); + for (int x = -1; x < 2; x++) + for (int y = -1; y < 2; y++) + for (int z = -1; z < 2; z++) { + Location blockLocation = blockState.getLocation().clone().add(new Vector(x, y, z)); + BlockState iteratedBlockState = blockLocation.getBlock().getState(); + if (blockStates.contains(iteratedBlockState)) continue; + if (!isCodependentBlock(iteratedBlockState, y)) continue; + nearbyBlockScan(blockStates, iteratedBlockState); + } + } + + private static boolean isCodependentBlock(BlockState blockState, int y) { + //Getter for blocks that will break if the block below breaks + if (y == 1) { + switch (blockState.getType()) { + case SUGAR_CANE: + case STRUCTURE_BLOCK: + case TALL_GRASS: + + case BLACK_CARPET: + case BLUE_CARPET: + case BROWN_CARPET: + case CYAN_CARPET: + case GRAY_CARPET: + case GREEN_CARPET: + case LIGHT_BLUE_CARPET: + case LIGHT_GRAY_CARPET: + case LIME_CARPET: + case MAGENTA_CARPET: + case ORANGE_CARPET: + case CARVED_PUMPKIN: + case PINK_CARPET: + case PURPLE_CARPET: + case RED_CARPET: + case WHITE_CARPET: + case YELLOW_CARPET: + + case DARK_OAK_DOOR: + case ACACIA_DOOR: + case BIRCH_DOOR: + case CRIMSON_DOOR: + case IRON_DOOR: + case JUNGLE_DOOR: + case OAK_DOOR: + case SPRUCE_DOOR: + case WARPED_DOOR: + + + case SUNFLOWER: + case WHEAT: + case BROWN_MUSHROOM: + case RED_MUSHROOM: + case DANDELION: + case NETHER_WART: + + + case REDSTONE: + case COMPARATOR: + case REPEATER: + + case TORCH: + case REDSTONE_TORCH: + + return true; + } + } + + //Getter for blocks that will break if the block above goes away + if (y == -1) { + switch (blockState.getType()) { + case VINE: + return true; + } + } + + //Generic getter for codependent blocks, blocks that would break if the adjacent block breaks + switch (blockState.getType()) { + case PAINTING: + case LADDER: + case LANTERN: + case VINE: + case SOUL_LANTERN: + + case TRIPWIRE: + case TRIPWIRE_HOOK: + + case REDSTONE_WALL_TORCH: + case WALL_TORCH: + + case ACACIA_TRAPDOOR: + case BIRCH_TRAPDOOR: + case CRIMSON_TRAPDOOR: + case DARK_OAK_TRAPDOOR: + case IRON_TRAPDOOR: + case JUNGLE_TRAPDOOR: + case OAK_TRAPDOOR: + case SPRUCE_TRAPDOOR: + case WARPED_TRAPDOOR: + + case COCOA_BEANS: + return true; + + default: + return false; + } + } + + private static void queueBlock(ArrayList blockStates, BlockState blockState) { + if (!DefaultConfig.isDoRegenerateContainers() && blockState instanceof Container) + return; + blockStates.add(blockState.getBlock().getState()); + if (blockState instanceof Container) + if (blockState instanceof Chest) + ((Chest) blockState).getBlockInventory().setContents(new ItemStack[0]); + else + ((Container) blockState).getInventory().setContents(new ItemStack[0]); + } + + public void resetAllBlocks() { + for (BlockState blockState : detonatedBlocks) + fullBlockRestore(blockState, true); + detonatedBlocks.clear(); + } + + public void regenerate() { + + Explosion explosion = this; + + new BukkitRunnable() { + @Override + public void run() { + if (detonatedBlocks.isEmpty()) { + explosions.remove(explosion); + cancel(); + return; + } + + BlockState firstBlock = null; + for (BlockState block : detonatedBlocks) { + firstBlock = block; + break; + } + + fullBlockRestore(firstBlock, false); + + } + }.runTaskTimer(MetadataHandler.PLUGIN, 20 * 60 * delayBeforeRegen, 1); + + } + + private void fullBlockRestore(BlockState blockState, boolean isShutdown) { + + for (Entity entity : blockState.getWorld().getNearbyEntities(new BoundingBox(blockState.getX(), blockState.getY(), blockState.getZ(), + blockState.getX() + 1, blockState.getY() + 1, blockState.getZ() + 1))) + entity.teleport(entity.getLocation().clone().add(new Vector(0, 1, 0))); + + blockState.setBlockData(blockState.getBlockData()); + + if (blockState instanceof Container) { + + Inventory container = null; + + switch (blockState.getType()) { + + case LECTERN: + container = ((Lectern) blockState).getInventory(); + break; + + case JUKEBOX: + //((Jukebox) blockState).setRecord(this.items.get(0)); + blockState.update(true, false); + break; + + default: + container = ((Container) blockState).getInventory(); + } + + if (container != null) container.setContents(((Container) blockState).getInventory().getContents()); + } + + blockState.update(true); + if (!isShutdown) + detonatedBlocks.remove(blockState); + } + + public static class ExplosionEvent implements Listener { + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) + public void entityExplodeEvent(EntityExplodeEvent event) { + EliteEntity eliteEntity = EntityTracker.getEliteMobEntity(event.getEntity()); + if (eliteEntity != null) { + generateExplosion(event); + return; + } + if (EntityTracker.isProjectileEntity(event.getEntity())) + generateExplosion(event); + //binder of worlds fight bypass, set in the custom reinforcements + if (event.getEntity().getPersistentDataContainer().has(new NamespacedKey(MetadataHandler.PLUGIN, "eliteCrystal"), PersistentDataType.STRING)) + generateExplosion(event); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/gamemodes/nightmaremodeworld/DaylightWatchdog.java b/src/main/java/com/magmaguy/elitemobs/gamemodes/nightmaremodeworld/DaylightWatchdog.java new file mode 100644 index 000000000..c7c44fe4a --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/gamemodes/nightmaremodeworld/DaylightWatchdog.java @@ -0,0 +1,35 @@ +package com.magmaguy.elitemobs.gamemodes.nightmaremodeworld; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.EliteMobs; +import com.magmaguy.elitemobs.MetadataHandler; +import org.bukkit.World; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerBedEnterEvent; +import org.bukkit.scheduler.BukkitRunnable; + +public class DaylightWatchdog implements Listener { + + public static void preventDaylight(World world) { + + new BukkitRunnable() { + @Override + public void run() { + long time = world.getTime(); + if (time < 12000) + world.setTime(time + 4); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + + } + + @EventHandler + public void onSleep(PlayerBedEnterEvent event) { + if (EliteMobs.nightmareWorlds.contains(event.getPlayer().getWorld())) { + event.setCancelled(true); + event.getPlayer().sendMessage(ChatColorConverter.convert("&7[EM] &4Sleep can't save you now...")); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/gamemodes/zoneworld/EliteChunk.java b/src/main/java/com/magmaguy/elitemobs/gamemodes/zoneworld/EliteChunk.java new file mode 100644 index 000000000..8abbbd00a --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/gamemodes/zoneworld/EliteChunk.java @@ -0,0 +1,45 @@ +package com.magmaguy.elitemobs.gamemodes.zoneworld; + +import com.magmaguy.elitemobs.utils.ChunkVectorizer; + +import java.util.HashMap; +import java.util.Vector; + +public class EliteChunk { + + private static final int gridSize = 50; + public static HashMap eliteChunks = new HashMap<>(); + private final int xCoord; + private final int zCoord; + + public EliteChunk(int xCoord, int zCoord) { + this.xCoord = xCoord; + this.zCoord = zCoord; + registerChunkLocation(this); + } + + public static EliteChunk getEliteChunk(String hashCode) { + return eliteChunks.get(hashCode); + } + + public static EliteChunk getEliteChunk(int xCoord, int zCoord) { + return eliteChunks.get(ChunkVectorizer.hash(xCoord, zCoord)); + } + + private static void registerChunkLocation(EliteChunk eliteChunk) { + eliteChunks.put(ChunkVectorizer.hash(eliteChunk.getxCoord(), eliteChunk.getzCoord()), eliteChunk); + } + + public static int getGridSize() { + return gridSize; + } + + public int getxCoord() { + return xCoord; + } + + public int getzCoord() { + return zCoord; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/gamemodes/zoneworld/Grid.java b/src/main/java/com/magmaguy/elitemobs/gamemodes/zoneworld/Grid.java new file mode 100644 index 000000000..6e010dac6 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/gamemodes/zoneworld/Grid.java @@ -0,0 +1,62 @@ +package com.magmaguy.elitemobs.gamemodes.zoneworld; + +import org.bukkit.Location; +import org.bukkit.util.Vector; + +import java.util.HashMap; +import java.util.concurrent.ThreadLocalRandom; + +public class Grid { + + private static final HashMap chunkMap = new HashMap<>(); + + public static HashMap getChunkMap() { + return chunkMap; + } + + private static void registerChunk(EliteChunk eliteChunk, int tier) { + chunkMap.put(eliteChunk, tier); + } + + public static void initializeGrid() { + for (int x = -100; x < 101; x++) + for (int z = -100; z < 101; z++) { + EliteChunk eliteChunk = new EliteChunk(x, z); + int value = (Math.abs(x) + Math.abs(z)) / 2; + int tier = 0; + if (value > 1) { + tier = ThreadLocalRandom.current().nextInt(value) + value; + if (ThreadLocalRandom.current().nextInt() < 0.05) + tier = ThreadLocalRandom.current().nextInt(value); + if (ThreadLocalRandom.current().nextInt() < 0.05) + tier = ThreadLocalRandom.current().nextInt(value * 2) + value; + } + registerChunk(eliteChunk, tier); + } + } + + public static double getMobTierFromLocation(Location location) { + return ThreadLocalRandom.current().nextDouble() + chunkMap.get(getEliteChunk(location)); + } + + public static EliteChunk getEliteChunk(Location location) { + Location customSpawnLocation = location.getWorld().getSpawnLocation().clone(); + //Get the 0,0 chunk location + customSpawnLocation = customSpawnLocation.subtract(new Vector(EliteChunk.getGridSize() / 2, 0, EliteChunk.getGridSize() / 2)); + //Assuming the chunks increment in 100 + int chunkX = (int) Math.floor((location.getX() - customSpawnLocation.getX()) / EliteChunk.getGridSize()); + int chunkZ = (int) Math.floor((location.getZ() - customSpawnLocation.getZ()) / EliteChunk.getGridSize()); + + if (chunkX > 100) + chunkX = 100; + if (chunkX < -100) + chunkX = -100; + if (chunkZ > 100) + chunkZ = 100; + if (chunkZ < -100) + chunkZ = -100; + + return EliteChunk.getEliteChunk(chunkX, chunkZ); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/gamemodes/zoneworld/ZoneWarner.java b/src/main/java/com/magmaguy/elitemobs/gamemodes/zoneworld/ZoneWarner.java new file mode 100644 index 000000000..6399bdbc3 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/gamemodes/zoneworld/ZoneWarner.java @@ -0,0 +1,49 @@ +package com.magmaguy.elitemobs.gamemodes.zoneworld; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.config.ValidWorldsConfig; +import com.magmaguy.elitemobs.utils.WarningMessage; +import net.md_5.bungee.api.ChatMessageType; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerMoveEvent; + +import java.util.HashMap; + +public class ZoneWarner implements Listener { + + public static HashMap playerLocations = new HashMap<>(); + + private static void sendMessage(Player player) { + try { + player.spigot().sendMessage(ChatMessageType.ACTION_BAR, + TextComponent.fromLegacyText( + ChatColorConverter.convert("&8[EM] &7You've entered a tier &c" + + Grid.getChunkMap().get(Grid.getEliteChunk(player.getLocation())) + + " &7zone (" + Grid.getEliteChunk(player.getLocation()).getxCoord() + "," + + Grid.getEliteChunk(player.getLocation()).getzCoord() + ")"))); + } catch (Exception ex) { + new WarningMessage("Failed to get the chunk region. This may be normal if you're trying to move around while EliteMobs is still starting up."); + } + } + + @EventHandler + public void onPlayerMove(PlayerMoveEvent event) { + + if (!ValidWorldsConfig.getZoneBasedWorlds().contains(event.getPlayer().getWorld().getName())) + return; + + if (!playerLocations.containsKey(event.getPlayer())) { + playerLocations.put(event.getPlayer(), Grid.getEliteChunk(event.getPlayer().getLocation())); + sendMessage(event.getPlayer()); + } + + if (Grid.getEliteChunk(event.getPlayer().getLocation()).equals(playerLocations.get(event.getPlayer()))) return; + playerLocations.put(event.getPlayer(), Grid.getEliteChunk(event.getPlayer().getLocation())); + sendMessage(event.getPlayer()); + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/initialsetup/FirstTimeSetup.java b/src/main/java/com/magmaguy/elitemobs/initialsetup/FirstTimeSetup.java new file mode 100644 index 000000000..85f0346c6 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/initialsetup/FirstTimeSetup.java @@ -0,0 +1,43 @@ +package com.magmaguy.elitemobs.initialsetup; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.config.DefaultConfig; +import com.magmaguy.elitemobs.utils.DiscordLinks; +import net.md_5.bungee.api.chat.ClickEvent; +import net.md_5.bungee.api.chat.ComponentBuilder; +import net.md_5.bungee.api.chat.HoverEvent; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.scheduler.BukkitRunnable; + +public class FirstTimeSetup implements Listener { + @EventHandler + public void onPlayerLogin(PlayerJoinEvent event) { + if (DefaultConfig.isSetupDone()) return; + if (!event.getPlayer().hasPermission("elitemobs.*")) return; + new BukkitRunnable() { + @Override + public void run() { + if (!event.getPlayer().isOnline()) return; + event.getPlayer().sendMessage("----------------------------------------------------"); + event.getPlayer().sendMessage(ChatColorConverter.convert("&7[EliteMobs] &fFirst time setup message:")); + event.getPlayer().sendMessage(ChatColorConverter.convert("&7Welcome to EliteMobs!" + + " &c&lIt looks like you haven't set up EliteMobs yet! &2To install EliteMobs, do &a/em setup &2!")); + event.getPlayer().sendMessage(ChatColorConverter.convert("&7Need command help? &6&l/em help")); + event.getPlayer().sendMessage(ChatColorConverter.convert("&7You can get support over at &9&n" + DiscordLinks.mainLink)); + TextComponent setupMessage = new TextComponent(ChatColorConverter.convert("&cDon't want to see this message again? ")); + TextComponent setupDone = new TextComponent(ChatColorConverter.convert("&c&nClick here!")); + setupDone.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder("Never show this again!").create())); + setupDone.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/elitemobs setup done")); + setupMessage.addExtra(setupDone); + event.getPlayer().spigot().sendMessage(setupMessage); + event.getPlayer().sendMessage(ChatColorConverter.convert("&8&oThis message will only be sent to admins!")); + + event.getPlayer().sendMessage("----------------------------------------------------"); + } + }.runTaskLater(MetadataHandler.PLUGIN, 20 * 10); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/instanced/ArenaEntity.java b/src/main/java/com/magmaguy/elitemobs/instanced/ArenaEntity.java new file mode 100644 index 000000000..06a453c4b --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/instanced/ArenaEntity.java @@ -0,0 +1,28 @@ +package com.magmaguy.elitemobs.instanced; + +import lombok.Getter; +import lombok.Setter; + +import javax.xml.stream.Location; + +public class ArenaEntity { + @Getter + @Setter + private String spawnPointName; + @Getter + @Setter + private Location spawnLocation; + @Getter + @Setter + private int wave; + @Getter + @Setter + private String bossfile; + + public ArenaEntity(String spawnPointName, int wave, String bossfile) { + this.spawnPointName = spawnPointName; + this.wave = wave; + this.bossfile = bossfile; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/instanced/ArenaInstance.java b/src/main/java/com/magmaguy/elitemobs/instanced/ArenaInstance.java new file mode 100644 index 000000000..b4adb3435 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/instanced/ArenaInstance.java @@ -0,0 +1,206 @@ +package com.magmaguy.elitemobs.instanced; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobDeathEvent; +import com.magmaguy.elitemobs.api.internal.RemovalReason; +import com.magmaguy.elitemobs.config.ArenasConfig; +import com.magmaguy.elitemobs.config.customarenas.CustomArenasConfigFields; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import com.magmaguy.elitemobs.utils.ConfigurationLocation; +import com.magmaguy.elitemobs.utils.WarningMessage; +import lombok.Getter; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Locale; + + +public class ArenaInstance extends MatchInstance { + + @Getter + private static final HashMap arenaInstances = new HashMap<>(); + @Getter + private final CustomArenasConfigFields customArenasConfigFields; + @Getter + private final ArenaWaves arenaWaves; + @Getter + private ArenaState arenaState = ArenaState.IDLE; + @Getter + private int currentWave = 0; + @Getter + private HashSet customBosses = new HashSet<>(); + private HashMap waveMessage = new HashMap<>(); + + public ArenaInstance(CustomArenasConfigFields customArenasConfigFields, Location corner1, Location corner2, Location startLocation, Location exitLocation) { + super(corner1, corner2, startLocation, exitLocation, customArenasConfigFields.getMinimumPlayerCount(), customArenasConfigFields.getMaximumPlayerCount(), customArenasConfigFields.getSpawnPoints()); + this.customArenasConfigFields = customArenasConfigFields; + this.arenaWaves = new ArenaWaves(customArenasConfigFields.getBossList()); + arenaInstances.put(customArenasConfigFields.getFilename(), this); + arenaWatchdog(); + for (String string : customArenasConfigFields.getArenaMessages()) { + String[] splitString = string.split(":"); + String message = ""; + int wave = 0; + for (String subString : splitString) { + String[] finalString = subString.split("="); + switch (finalString[0].toLowerCase(Locale.ROOT)) { + case "wave": + try { + wave = Integer.parseInt(finalString[1]); + } catch (Exception ex) { + new WarningMessage("Failed to parse wave for entry " + subString + " for arena" + customArenasConfigFields.getFilename()); + } + break; + case "message": + message = finalString[1]; + break; + default: + new WarningMessage("Failed to parse arena message entry " + subString + " for arena" + customArenasConfigFields.getFilename()); + } + } + if (!message.isEmpty() && wave > 0) + waveMessage.put(wave, ChatColorConverter.convert(message)); + } + } + + public static void initializeArena(CustomArenasConfigFields customArenasConfigFields) { + Location corner1 = ConfigurationLocation.serialize(customArenasConfigFields.getCorner1()); + Location corner2 = ConfigurationLocation.serialize(customArenasConfigFields.getCorner2()); + Location startLocation = ConfigurationLocation.serialize(customArenasConfigFields.getStartLocation()); + Location exitLocation = ConfigurationLocation.serialize(customArenasConfigFields.getExitLocation()); + if (corner1 == null || corner2 == null || startLocation == null || exitLocation == null) { + new WarningMessage("Failed to correctly initialize arena " + customArenasConfigFields.getFilename() + " due to invalid locations for corner1/corner2/startLocation/exitLocation"); + return; + } + if (corner1.getWorld() == null || corner2.getWorld() == null || startLocation.getWorld() == null || exitLocation.getWorld() == null) { + new WarningMessage("Failed to correctly initialize arena " + customArenasConfigFields.getFilename() + " due to invalid world for corner1/corner2/startLocation/exitLocation"); + return; + } + new ArenaInstance(customArenasConfigFields, corner1, corner2, startLocation, exitLocation); + } + + @Override + protected void startMatch() { + super.startMatch(); + nextWave(); + } + + private void nextWave() { + currentWave++; + arenaState = ArenaState.COOLDOWN; + if (waveMessage.get(currentWave) != null) { + players.forEach(player -> player.sendMessage(waveMessage.get(currentWave))); + spectators.forEach(player -> player.sendMessage(waveMessage.get(currentWave))); + } + + doRewards(); + if (currentWave > customArenasConfigFields.getWaveCount()) { + endMatch(); + return; + } + Bukkit.getScheduler().scheduleSyncDelayedTask(MetadataHandler.PLUGIN, () -> { + if (arenaState == ArenaState.IDLE) return; + players.forEach(player -> player.sendTitle(ArenasConfig.getWaveTitle().replace("$wave", currentWave + ""), + ArenasConfig.getWaveSubtitle().replace("$wave", currentWave + ""), 0, 20, 0)); + spectators.forEach(player -> player.sendTitle(ArenasConfig.getWaveTitle().replace("$wave", currentWave + ""), + ArenasConfig.getWaveSubtitle().replace("$wave", currentWave + ""), 0, 20, 0)); + spawnBosses(); + arenaState = ArenaState.ACTIVE; + }, 20L * customArenasConfigFields.getDelayBetweenWaves()); + } + + + private void arenaWatchdog() { + new BukkitRunnable() { + @Override + public void run() { + if (arenaState != ArenaState.ACTIVE) return; + for (CustomBossEntity customBossEntity : (HashSet) customBosses.clone()) + if (!customBossEntity.exists()) removeBoss(customBossEntity); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0L, 20L); + } + + public void removeBoss(CustomBossEntity customBossEntity) { + customBosses.remove(customBossEntity); + if (customBosses.isEmpty()) nextWave(); + } + + private void spawnBosses() { + + if (arenaWaves.getWaveEntities(currentWave) == null) return; + for (ArenaEntity arenaEntity : arenaWaves.getWaveEntities(currentWave)) { + CustomBossEntity customBossEntity = CustomBossEntity.createCustomBossEntity(arenaEntity.getBossfile()); + if (customBossEntity == null) { + new WarningMessage("Failed to generate custom boss " + arenaEntity.getBossfile() + " because the filename was not valid!"); + continue; + } + customBossEntity.setNormalizedCombat(); + customBossEntity.setEliteLoot(false); + customBossEntity.setVanillaLoot(false); + customBossEntity.setRandomLoot(false); + customBossEntity.spawn(super.spawnPoints.get(arenaEntity.getSpawnPointName()), true); + if (!customBossEntity.exists()) { + new WarningMessage("Arena " + getCustomArenasConfigFields().getArenaName() + " failed to spawn boss " + customBossEntity.getCustomBossesConfigFields().getFilename()); + continue; + } else customBosses.add(customBossEntity); + } + } + + private void doRewards() { + //Note: here current wave is decreased by 1 because the reward runs at the top of the next wave method. + //So basically it runs at the start of the wave, hence it should reward whatever the previous wave had. + super.players.forEach(player -> customArenasConfigFields.getArenaRewards().arenaReward(player, currentWave - 1)); + } + + @Override + protected void endMatch() { + super.endMatch(); + arenaState = ArenaState.IDLE; + //victory state + if (currentWave > getCustomArenasConfigFields().getWaveCount()) { + participants.forEach(player -> player.sendTitle(ArenasConfig.getVictoryTitle().replace("$wave", customArenasConfigFields.getWaveCount() + ""), + ArenasConfig.getVictorySubtitle().replace("$wave", customArenasConfigFields.getWaveCount() + ""), 20, 20 * 10, 20)); + StringBuilder playerNames = new StringBuilder(); + for (Player player : participants) + playerNames.append(player.getName()).append(" "); + Bukkit.getServer().broadcastMessage(ArenasConfig.getVictoryBroadcast().replace("$players", playerNames.toString()).replace("$arenaName", customArenasConfigFields.getArenaName())); + } else + participants.forEach(player -> player.sendTitle(ArenasConfig.getDefeatTitle().replace("$wave", currentWave + ""), + ArenasConfig.getDefeatSubtitle().replace("$wave", currentWave + ""), 20, 20 * 10, 20)); + + Bukkit.getScheduler().scheduleSyncDelayedTask(MetadataHandler.PLUGIN, this::resetMatch, customArenasConfigFields.getDelayBetweenWaves()); + } + + @Override + protected void resetMatch() { + super.resetMatch(); + arenaState = ArenaState.IDLE; + currentWave = 0; + customBosses.forEach(customBoss -> customBoss.remove(RemovalReason.ARENA_RESET)); + customBosses.clear(); + } + + private enum ArenaState { + IDLE, COOLDOWN, ACTIVE + } + + public static class ArenaInstanceEvents implements Listener { + @EventHandler + public void onEliteDeath(EliteMobDeathEvent event) { + if (!(event.getEliteEntity() instanceof CustomBossEntity)) return; + for (ArenaInstance arenaInstance : arenaInstances.values()) + if (arenaInstance.getCustomBosses().contains((CustomBossEntity) event.getEliteEntity())) { + arenaInstance.removeBoss((CustomBossEntity) event.getEliteEntity()); + return; + } + } + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/instanced/ArenaWaves.java b/src/main/java/com/magmaguy/elitemobs/instanced/ArenaWaves.java new file mode 100644 index 000000000..4a1a23e5f --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/instanced/ArenaWaves.java @@ -0,0 +1,50 @@ +package com.magmaguy.elitemobs.instanced; + +import com.magmaguy.elitemobs.utils.WarningMessage; + +import java.util.*; + +public class ArenaWaves { + + private HashMap> arenaEntities = new HashMap(); + + //wave=X:spawnPoint=Y:boss=Z.yml + public ArenaWaves(List rawBosses) { + for (String iteratedBoss : rawBosses) { + String[] subString = iteratedBoss.split(":"); + String waveString = ""; + String spawnpointString = ""; + String boss = ""; + for (String iteratedString : subString) { + String[] valuesString = iteratedString.split("="); + switch (valuesString[0].toLowerCase(Locale.ROOT)) { + case "wave": + waveString = valuesString[1]; + break; + case "spawnpoint": + spawnpointString = valuesString[1]; + break; + case "boss": + boss = valuesString[1]; + break; + } + } + int wave; + try { + wave = Integer.valueOf(waveString); + } catch (Exception exception) { + new WarningMessage("Invalid value for wave in arena wave: " + waveString); + continue; + } + ArenaEntity arenaEntity = new ArenaEntity(spawnpointString, wave, boss); + if (arenaEntities.get(wave) == null) + arenaEntities.put(wave, new ArrayList<>(Arrays.asList(arenaEntity))); + else + arenaEntities.get(wave).add(arenaEntity); + } + } + + public List getWaveEntities(int wave) { + return arenaEntities.get(wave); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/instanced/MatchInstance.java b/src/main/java/com/magmaguy/elitemobs/instanced/MatchInstance.java new file mode 100644 index 000000000..8da7a552a --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/instanced/MatchInstance.java @@ -0,0 +1,431 @@ +package com.magmaguy.elitemobs.instanced; + + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.internal.RemovalReason; +import com.magmaguy.elitemobs.config.ArenasConfig; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.playerdata.database.PlayerData; +import com.magmaguy.elitemobs.utils.ConfigurationLocation; +import com.magmaguy.elitemobs.utils.VisualArmorStand; +import com.magmaguy.elitemobs.utils.WarningMessage; +import lombok.Getter; +import org.bukkit.*; +import org.bukkit.attribute.Attribute; +import org.bukkit.block.Block; +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; + +public class MatchInstance { + + private static HashSet instances = new HashSet<>(); + protected HashSet players = new HashSet<>(); + protected HashMap playerLives = new HashMap(); + protected HashSet participants = new HashSet<>(); + protected HashSet spectators = new HashSet<>(); + protected InstancedRegionState state; + protected Location startLocation; + protected Location exitLocation; + protected HashMap spawnPoints = new HashMap<>(); + private Location corner1; + private Location corner2; + private int minPlayers; + private int maxPlayers; + private int minX; + private int maxX; + private int minY; + private int maxY; + private int minZ; + private int maxZ; + private World world; + @Getter + private HashMap deathBanners = new HashMap<>(); + + public MatchInstance(Location corner1, Location corner2, Location startLocation, Location exitLocation, int minPlayers, int maxPlayers, List spawnPoints) { + this.corner1 = corner1; + this.corner2 = corner2; + this.startLocation = startLocation; + this.exitLocation = exitLocation; + this.minPlayers = minPlayers; + this.maxPlayers = maxPlayers; + if (corner1.getX() < corner2.getX()) { + minX = (int) corner1.getX(); + maxX = (int) corner2.getX(); + } else { + minX = (int) corner2.getX(); + maxX = (int) corner1.getX(); + } + + if (corner1.getY() < corner2.getY()) { + minY = (int) corner1.getY(); + maxY = (int) corner2.getY(); + } else { + minY = (int) corner2.getY(); + maxY = (int) corner1.getY(); + } + + if (corner1.getZ() < corner2.getZ()) { + minZ = (int) corner1.getZ(); + maxZ = (int) corner2.getZ(); + } else { + minZ = (int) corner2.getZ(); + maxZ = (int) corner1.getZ(); + } + this.world = corner1.getWorld(); + this.state = InstancedRegionState.IDLE; + + startWatchdogs(); + + addSpawnPoints(spawnPoints); + instanceMessages(); + + instances.add(this); + } + + public static void shutdown() { + instances.forEach(MatchInstance::resetMatch); + instances.clear(); + } + + public static MatchInstance getPlayerInstance(Player player) { + for (MatchInstance matchInstance : instances) + for (Player iteratedPlayer : matchInstance.players) + if (iteratedPlayer.equals(player)) return matchInstance; + return null; + } + + public static MatchInstance getSpectatorInstance(Player player) { + for (MatchInstance matchInstance : instances) + for (Player iteratedPlayer : matchInstance.spectators) + if (iteratedPlayer.equals(player)) return matchInstance; + return null; + } + + public static MatchInstance getAnyPlayerInstance(Player player) { + for (MatchInstance matchInstance : instances) { + for (Player iteratedPlayer : matchInstance.players) + if (iteratedPlayer.equals(player)) return matchInstance; + for (Player iteratedPlayer : matchInstance.spectators) + if (iteratedPlayer.equals(player)) return matchInstance; + } + return null; + } + + public void addSpawnPoints(List rawSpawnPoints) { + for (String string : rawSpawnPoints) { + String[] splitEntry = string.split(":"); + String name = ""; + String location = ""; + for (String subString : splitEntry) { + String[] splitSubEntry = subString.split("="); + switch (splitSubEntry[0].toLowerCase()) { + case "name": + name = splitSubEntry[1]; + break; + case "location": + location = splitSubEntry[1]; + break; + default: + new WarningMessage("Invalid entry for the spawn points of instanced content: " + splitSubEntry[0]); + break; + } + } + spawnPoints.put(name, ConfigurationLocation.serialize(location)); + } + } + + public void addPlayer(Player player) { + if (state.equals(InstancedRegionState.ONGOING)) { + player.sendMessage(ArenasConfig.getArenasOngoingMessage()); + return; + } + if (players.size() + 1 > maxPlayers) { + player.sendMessage(ArenasConfig.getArenaFullMessage()); + return; + } + player.sendMessage(ArenasConfig.getArenaJoinPlayerMessage().replace("$count", minPlayers + "")); + player.sendTitle(ArenasConfig.getJoinPlayerTitle(), ArenasConfig.getJoinPlayerSubtitle(), 60, 60 * 3, 60); + players.add(player); + player.teleport(startLocation); + PlayerData.setMatchInstance(player, this); + playerLives.put(player, 3); + } + + public void removePlayer(Player player) { + PlayerData.setMatchInstance(player, null); + players.remove(player); + if (player.isOnline()) player.teleport(exitLocation); + else if (getDeathLocationByPlayer(player) != null) + getDeathLocationByPlayer(player).clear(false); + if (players.isEmpty()) + endMatch(); + playerLives.remove(player); + + } + + public void playerDeath(Player player) { + if (!players.contains(player)) return; + player.setHealth(player.getAttribute(Attribute.GENERIC_MAX_HEALTH).getBaseValue()); + players.remove(player); + if (players.isEmpty()) { + endMatch(); + player.teleport(exitLocation); + return; + } + new DeathLocation(player); + addSpectator(player); + } + + public void revivePlayer(Player player, DeathLocation deathLocation) { + playerLives.put(player, playerLives.get(player) - 1); + players.add(player); + player.setGameMode(GameMode.SURVIVAL); + spectators.remove(player); + player.teleport(deathLocation.bannerBlock.getLocation()); + PlayerData.setMatchInstance(player, this); + } + + public void addSpectator(Player player) { + player.sendMessage(ArenasConfig.getArenaJoinSpectatorMessage()); + player.sendTitle(ArenasConfig.getJoinSpectatorTitle(), ArenasConfig.getJoinSpectatorSubtitle(), 60, 60 * 3, 60); + spectators.add(player); + player.setGameMode(GameMode.SPECTATOR); + player.teleport(startLocation); + PlayerData.setMatchInstance(player, this); + } + + public void removeSpectator(Player player) { + spectators.remove(player); + player.setGameMode(GameMode.SURVIVAL); + player.teleport(exitLocation); + PlayerData.setMatchInstance(player, null); + playerLives.remove(player); + if (getDeathLocationByPlayer(player) != null) + getDeathLocationByPlayer(player).clear(false); + } + + public void removeAnyKind(Player player) { + if (players.contains(player)) removePlayer(player); + if (spectators.contains(player)) removeSpectator(player); + } + + private void startWatchdogs() { + new BukkitRunnable() { + @Override + public void run() { + playerWatchdog(); + spectatorWatchdog(); + intruderWatchdog(); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + } + + private void playerWatchdog() { + ((HashSet) players.clone()).forEach(player -> { + if (!player.isOnline()) removePlayer(player); + if (!isInRegion(player.getLocation())) player.teleport(startLocation); + }); + } + + private void spectatorWatchdog() { + ((HashSet) spectators.clone()).forEach(player -> { + if (!player.isOnline()) removeSpectator(player); + if (!isInRegion(player.getLocation())) player.teleport(startLocation); + }); + } + + private void intruderWatchdog() { + if (state != InstancedRegionState.ONGOING) return; + for (Player player : Bukkit.getOnlinePlayers()) + if (!players.contains(player) && !spectators.contains(player) && isInRegion(player.getLocation())) + player.teleport(exitLocation); + } + + private void instanceMessages() { + Bukkit.getScheduler().scheduleSyncRepeatingTask(MetadataHandler.PLUGIN, () -> { + switch (state) { + case IDLE: + players.forEach(player -> player.sendMessage(ArenasConfig.getArenaStartHintMessage().replace("$count", minPlayers + ""))); + break; + } + }, 0L, 20 * 60L); + } + + private boolean isInRegion(Location location) { + return location.getWorld().equals(world) && + minX <= location.getX() && + maxX >= location.getX() && + minY <= location.getY() && + maxY >= location.getY() && + minZ <= location.getZ() && + maxZ >= location.getZ(); + } + + public void countdownMatch() { + if (state != InstancedRegionState.IDLE) return; + if (players.size() < minPlayers) { + players.forEach(player -> player.sendMessage(ArenasConfig.getNotEnoughPlayersMessage().replace("$amount", minPlayers + ""))); + return; + } + state = InstancedRegionState.STARTING; + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + counter++; + players.forEach(player -> startMessage(counter, player)); + spectators.forEach(player -> startMessage(counter, player)); + if (counter >= 3) { + startMatch(); + cancel(); + } + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0L, 20L); + } + + private void startMessage(int counter, Player player) { + player.sendTitle(ArenasConfig.getStartingTitle(), ArenasConfig.getStartingSubtitle() + .replace("$count", (3 - counter) + ""), 0, 20, 0); + } + + protected void startMatch() { + state = InstancedRegionState.ONGOING; + participants = (HashSet) players.clone(); + } + + protected void endMatch() { + state = InstancedRegionState.COMPLETED; + } + + protected void resetMatch() { + state = InstancedRegionState.IDLE; + players.forEach(player -> player.teleport(exitLocation)); + spectators.forEach(player -> { + player.setGameMode(GameMode.SURVIVAL); + player.teleport(exitLocation); + }); + ((HashSet) players.clone()).forEach(this::removePlayer); + ((HashSet) spectators.clone()).forEach(this::removeSpectator); + deathBanners.values().forEach(deathLocation -> deathLocation.clear(false)); + deathBanners.clear(); + } + + public enum InstancedRegionState { + IDLE, STARTING, ONGOING, COMPLETED + } + + private DeathLocation getDeathLocationByPlayer(Player player) { + for (DeathLocation deathLocation : deathBanners.values()) + if (deathLocation.deadPlayer.equals(player)) + return deathLocation; + return null; + } + + public static class MatchInstanceEvents implements Listener { + @EventHandler + public void onPlayerLeave(PlayerQuitEvent event) { + instances.forEach(instance -> instance.removeAnyKind(event.getPlayer())); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + public void onPlayerDamage(EntityDamageEvent event) { + if (!event.getEntityType().equals(EntityType.PLAYER)) return; + Player player = (Player) event.getEntity(); + if (event.getFinalDamage() < player.getHealth()) return; + MatchInstance matchInstance = PlayerData.getMatchInstance(player); + if (matchInstance == null) return; + event.setCancelled(true); + matchInstance.playerDeath(player); + } + + @EventHandler + public void onPlayerBreakBlockEvent(BlockBreakEvent event) { + for (MatchInstance matchInstance : instances) + if (matchInstance.state.equals(InstancedRegionState.ONGOING)) + if (matchInstance.getDeathBanners().get(event.getBlock()) != null) + matchInstance.getDeathBanners().get(event.getBlock()).clear(true); + } + } + + private class DeathLocation { + private Block bannerBlock; + private Player deadPlayer; + private Location deathLocation = null; + private ArmorStand nameTag; + private ArmorStand livesLeft; + private ArmorStand instructions; + + private DeathLocation(Player player) { + if (playerLives.get(player) < 1) + return; + this.deadPlayer = player; + this.bannerBlock = player.getLocation().getBlock(); + findBannerLocation(player.getLocation()); + instructions = VisualArmorStand.VisualArmorStand(deathLocation.clone().add(new Vector(0, 2.2, 0)), ChatColorConverter.convert("&2Punch to rez!")); + nameTag = VisualArmorStand.VisualArmorStand(deathLocation.clone().add(new Vector(0, 2, 0)), player.getDisplayName()); + livesLeft = VisualArmorStand.VisualArmorStand(deathLocation.clone().add(new Vector(0, 1.8, 0)), playerLives.get(deadPlayer) + " lives left!"); + if (deathLocation != null) + deathBanners.put(bannerBlock, this); + + bannerWatchdog(); + } + + private void findBannerLocation(Location location) { + if (location.getBlock().getType().isAir()) + setBannerBlock(location); + else if (location.getY() < 320) + findBannerLocation(location.add(new Vector(0, 1, 0))); + } + + private void setBannerBlock(Location location) { + deathLocation = location; + bannerBlock = location.getBlock(); + location.getBlock().setType(Material.RED_BANNER, false); + } + + public void clear(boolean resurrect) { + bannerBlock.setType(Material.AIR); + EntityTracker.unregister(nameTag, RemovalReason.EFFECT_TIMEOUT); + EntityTracker.unregister(instructions, RemovalReason.EFFECT_TIMEOUT); + EntityTracker.unregister(livesLeft, RemovalReason.EFFECT_TIMEOUT); + deathBanners.remove(bannerBlock); + if (resurrect) + revivePlayer(deadPlayer, this); + } + + //This is necessary because physics updates might remove the banner while it should still be on there + public void bannerWatchdog(){ + new BukkitRunnable() { + @Override + public void run() { + if (!deathBanners.containsKey(bannerBlock)){ + cancel(); + return; + } + if (bannerBlock.getType().equals(Material.RED_BANNER)) return; + EntityTracker.unregister(nameTag, RemovalReason.EFFECT_TIMEOUT); + EntityTracker.unregister(instructions, RemovalReason.EFFECT_TIMEOUT); + EntityTracker.unregister(livesLeft, RemovalReason.EFFECT_TIMEOUT); + findBannerLocation(deathLocation); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 5, 5); + } + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/items/CustomItemConstructor.java b/src/main/java/com/magmaguy/elitemobs/items/CustomItemConstructor.java deleted file mode 100644 index cfbe001e7..000000000 --- a/src/main/java/com/magmaguy/elitemobs/items/CustomItemConstructor.java +++ /dev/null @@ -1,162 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.items; - -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.items.itemconstructor.ItemConstructor; -import com.magmaguy.elitemobs.items.parserutil.CustomEnchantmentConfigParser; -import com.magmaguy.elitemobs.items.parserutil.DropWeightConfigParser; -import com.magmaguy.elitemobs.items.parserutil.PotionEffectConfigParser; -import com.magmaguy.elitemobs.items.parserutil.ScalabilityConfigParser; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.configuration.Configuration; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.event.Listener; -import org.bukkit.inventory.ItemStack; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -import static com.magmaguy.elitemobs.ChatColorConverter.convert; -import static com.magmaguy.elitemobs.items.parserutil.ConfigPathBuilder.automatedStringBuilder; -import static com.magmaguy.elitemobs.items.parserutil.EnchantmentConfigParser.parseEnchantments; - -/** - * Created by MagmaGuy on 29/11/2016. - */ -public class CustomItemConstructor implements Listener { - - public static ArrayList customItemList = new ArrayList(); - public static HashMap staticCustomItemHashMap = new HashMap<>(); - public static HashMap> dynamicRankedItemStacks = new HashMap<>(); - - public void superDropParser() { - - List lootCount = lootCounter(); - - for (String lootEntry : lootCount) { - - StringBuilder path = new StringBuilder(); - path.append(lootEntry); - - String previousPath = path.toString(); - - Material material = getMaterial(previousPath); - Bukkit.getLogger().info("Adding: " + previousPath); - String rawName = getName(previousPath); - - if (material == null) - continue; - - Configuration configuration = ConfigValues.itemsCustomLootListConfig; - - HashMap enchantments = parseEnchantments(configuration, previousPath); - HashMap customEnchantments = CustomEnchantmentConfigParser.parseCustomEnchantments(configuration, previousPath); - List potionEffects = PotionEffectConfigParser.itemPotionEffectHandler(configuration, previousPath); - List lore = getCustomLore(previousPath); - String dropType = DropWeightConfigParser.getDropType(configuration, previousPath); - String scalability = ScalabilityConfigParser.parseItemScalability(configuration, previousPath); - - ItemStack itemStack = ItemConstructor.constructItem(rawName, material, enchantments, customEnchantments, - potionEffects, lore, dropType, scalability); - - customItemList.add(itemStack); - - } - - } - - private List lootCounter() { - - List lootCount = new ArrayList(); - - for (String configIterator : ConfigValues.itemsCustomLootListConfig.getKeys(true)) { - - int dotCount = 0; - - if (configIterator.contains("Loot.")) { - - for (int i = 0; i < configIterator.length(); i++) - if (configIterator.charAt(i) == '.') - dotCount++; - - if (dotCount == 1) - lootCount.add(configIterator); - - } - - } - - return lootCount; - - } - - private Material getMaterial(String previousPath) { - - String path = automatedStringBuilder(previousPath, "Item Type"); - - Material material; - - try { - - material = Material.getMaterial(ConfigValues.itemsCustomLootListConfig.getString(path)); - - } catch (Error error) { - - Bukkit.getLogger().warning("[EliteMobs] Invalid material!"); - return null; - - } - - - return material; - - } - - private String getName(String previousPath) { - - String name = automatedStringBuilder(previousPath, "Item Name"); - - if (ConfigValues.itemsCustomLootListConfig.getString(name) == null || ConfigValues.itemsCustomLootListConfig.getString(name).isEmpty()) - Bukkit.getLogger().warning("[EliteMobs] Invalid name!"); - - return convert(ConfigValues.itemsCustomLootListConfig.getString(name)); - - } - - private List getCustomLore(String previousPath) { - - String path = automatedStringBuilder(previousPath, "Item Lore"); - - List itemLore = (List) ConfigValues.itemsCustomLootListConfig.getList(path); - - List newList = new ArrayList<>(); - - if (itemLore != null && !itemLore.isEmpty()) - for (String string : itemLore) - if (string != null && !string.isEmpty()) - newList.add(convert(string)); - - if (newList.isEmpty()) - return itemLore; - - return newList; - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/items/DefaultDropsHandler.java b/src/main/java/com/magmaguy/elitemobs/items/DefaultDropsHandler.java index 248a5dc99..917841670 100644 --- a/src/main/java/com/magmaguy/elitemobs/items/DefaultDropsHandler.java +++ b/src/main/java/com/magmaguy/elitemobs/items/DefaultDropsHandler.java @@ -1,30 +1,13 @@ -/* - * 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 . - */ - package com.magmaguy.elitemobs.items; -import com.magmaguy.elitemobs.EntityTracker; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.ItemsDropSettingsConfig; +import com.magmaguy.elitemobs.api.EliteMobDeathEvent; +import com.magmaguy.elitemobs.config.ItemSettingsConfig; import org.bukkit.Material; import org.bukkit.entity.ExperienceOrb; import org.bukkit.entity.LivingEntity; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.inventory.EntityEquipment; import org.bukkit.inventory.ItemStack; @@ -36,47 +19,45 @@ */ public class DefaultDropsHandler implements Listener { - private List wornItems = new ArrayList<>(); + private final List wornItems = new ArrayList<>(); @EventHandler(priority = EventPriority.HIGHEST) - public void onDeath(EntityDeathEvent event) { - - if (!EntityTracker.isEliteMob(event.getEntity())) return; + public void onDeath(EliteMobDeathEvent event) { - if (!EntityTracker.isNaturalEntity(event.getEntity()) && - !ConfigValues.itemsDropSettingsConfig.getBoolean(ItemsDropSettingsConfig.SPAWNER_DEFAULT_LOOT_MULTIPLIER)) - return; + if (!(event.getEntity() instanceof LivingEntity)) return; + if (!event.getEliteEntity().isVanillaLoot()) return; + if (event.getEntityDeathEvent() == null) return; - List droppedItems = event.getDrops(); - int mobLevel = (int) (EntityTracker.getEliteMobEntity(event.getEntity()).getLevel() * - ConfigValues.itemsDropSettingsConfig.getDouble(ItemsDropSettingsConfig.DEFAULT_LOOT_MULTIPLIER)); + List droppedItems = event.getEntityDeathEvent().getDrops(); + int mobLevel = event.getEliteEntity().getLevel(); - if (mobLevel > ConfigValues.itemsDropSettingsConfig.getInt(ItemsDropSettingsConfig.MAXIMUM_LEVEL_FOR_LOOT_MULTIPLIER)) - mobLevel = ConfigValues.itemsDropSettingsConfig.getInt(ItemsDropSettingsConfig.MAXIMUM_LEVEL_FOR_LOOT_MULTIPLIER); + if (mobLevel > ItemSettingsConfig.getMaxLevelForDefaultLootMultiplier()) + mobLevel = ItemSettingsConfig.getMaxLevelForDefaultLootMultiplier(); - inventoryItemsConstructor(event.getEntity()); + inventoryItemsConstructor((LivingEntity) event.getEntity()); - for (ItemStack itemStack : droppedItems) { + if (ItemSettingsConfig.getDefaultLootMultiplier() != 0) { + for (ItemStack itemStack : droppedItems) { -// ItemStack can be null for some reason, probably due to other plugins - if (itemStack == null) continue; - boolean itemIsWorn = false; + if (itemStack == null) continue; + if (itemStack.getType().equals(Material.AIR)) continue; + boolean itemIsWorn = false; - for (ItemStack wornItem : wornItems) - if (wornItem.isSimilar(itemStack)) - itemIsWorn = true; + for (ItemStack wornItem : wornItems) + if (wornItem.isSimilar(itemStack)) + itemIsWorn = true; - if (!itemIsWorn) - for (int i = 0; i < mobLevel * 0.1; i++) - event.getEntity().getLocation().getWorld().dropItem(event.getEntity().getLocation(), itemStack); + if (!itemIsWorn) + for (int i = 0; i < mobLevel * 0.1 * ItemSettingsConfig.getDefaultLootMultiplier(); i++) + event.getEntity().getLocation().getWorld().dropItem(event.getEntity().getLocation(), itemStack); + } } - mobLevel = (int) (EntityTracker.getEliteMobEntity(event.getEntity()).getLevel() * - ConfigValues.itemsDropSettingsConfig.getDouble(ItemsDropSettingsConfig.EXPERIENCE_LOOT_MULTIPLIER)); + mobLevel = (int) (event.getEliteEntity().getLevel() * ItemSettingsConfig.getDefaultExperienceMultiplier()); - int droppedXP = (int) (event.getDroppedExp() + event.getDroppedExp() * 0.1 * mobLevel); - event.setDroppedExp(0); + int droppedXP = (int) (event.getEntityDeathEvent().getDroppedExp() + event.getEntityDeathEvent().getDroppedExp() * 0.1 * mobLevel); + event.getEntityDeathEvent().setDroppedExp(0); event.getEntity().getWorld().spawn(event.getEntity().getLocation(), ExperienceOrb.class).setExperience(droppedXP); } diff --git a/src/main/java/com/magmaguy/elitemobs/items/DynamicLore.java b/src/main/java/com/magmaguy/elitemobs/items/DynamicLore.java deleted file mode 100644 index 7548ea337..000000000 --- a/src/main/java/com/magmaguy/elitemobs/items/DynamicLore.java +++ /dev/null @@ -1,184 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.items; - -import com.magmaguy.elitemobs.ChatColorConverter; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.EconomySettingsConfig; -import com.magmaguy.elitemobs.config.ItemsDropSettingsConfig; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; - -import java.util.ArrayList; -import java.util.List; - -public class DynamicLore { - - public static boolean displayWorth = true; - - /* - This method runs inside of a repeating task that runs on a set interval - */ - public static void refreshDynamicLore() { - - for (Player player : Bukkit.getOnlinePlayers()) - for (ItemStack itemStack : player.getInventory().getContents()) { - - if (!(itemStack != null && itemStack.hasItemMeta() - && itemStack.getItemMeta().hasLore())) - continue; - - if (ObfuscatedSignatureLoreData.obfuscatedSignatureDetector(itemStack) - && !player.getInventory().getItemInMainHand().equals(itemStack) - && !player.getInventory().getItemInOffHand().equals(itemStack)) { - - if (displayWorth) { - - setLoreToWorth(itemStack); - - } else { - - setLoreToResale(itemStack); - - } - - } - - - } - - - displayWorth = !displayWorth; - - } - - private static void setLoreToWorth(ItemStack itemStack) { - - double itemWorth = ItemWorthCalculator.determineItemWorth(itemStack); - double itemResale = ItemWorthCalculator.determineResaleWorth(itemStack); - - ItemMeta itemMeta = itemStack.getItemMeta(); - - List newLore = new ArrayList<>(); - - for (String loreLine : itemMeta.getLore()) { - - if (isEconomyLoreLine(loreLine, itemWorth, itemResale)) { - - String lorePrefix = lorePrefix(loreLine, itemWorth, itemResale); - - newLore.add(lorePrefix + targetValueLine(itemWorth)); - - } else { - - newLore.add(loreLine); - - } - - } - - itemMeta.setLore(newLore); - itemStack.setItemMeta(itemMeta); - - } - - private static void setLoreToResale(ItemStack itemStack) { - - double itemWorth = ItemWorthCalculator.determineItemWorth(itemStack); - double itemResale = ItemWorthCalculator.determineResaleWorth(itemStack); - - ItemMeta itemMeta = itemStack.getItemMeta(); - - List newLore = new ArrayList<>(); - - for (String loreLine : itemMeta.getLore()) { - - if (isEconomyLoreLine(loreLine, itemWorth, itemResale)) { - - String lorePrefix = lorePrefix(loreLine, itemWorth, itemResale); - - newLore.add(lorePrefix + targetResaleLine(itemResale)); - - } else { - - newLore.add(loreLine); - - } - - } - - itemMeta.setLore(newLore); - itemStack.setItemMeta(itemMeta); - - } - - private static boolean isEconomyLoreLine(String loreLine, double worth, double resale) { - - String targetWorthLine = targetValueLine(worth); - String targetResaleLine = targetResaleLine(resale); - - return loreLine.contains(targetResaleLine) || loreLine.contains(targetWorthLine); - - } - - private static String lorePrefix(String loreLine, double worth, double resale) { - - String targetWorthLine = targetValueLine(worth); - String targetResaleLine = targetResaleLine(resale); - String lorePrefix = ""; - - if (loreLine.contains(targetWorthLine)) { - - lorePrefix = loreLine.substring(0, loreLine.indexOf(targetWorthLine)); - - } - - if (loreLine.contains(targetResaleLine)) { - - lorePrefix = loreLine.substring(0, loreLine.indexOf(targetResaleLine)); - - } - - return lorePrefix; - - } - - private static String targetValueLine(double worthOrResale) { - - String worthLore = ConfigValues.itemsDropSettingsConfig.getString(ItemsDropSettingsConfig.LORE_WORTH); - worthLore = worthLore.replace("$worth", worthOrResale + ""); - worthLore = worthLore.replace("$currencyName", ConfigValues.economyConfig.getString(EconomySettingsConfig.CURRENCY_NAME)); - worthLore = ChatColorConverter.convert(worthLore); - - return worthLore; - - } - - private static String targetResaleLine(double resale) { - - String resaleLore = ConfigValues.itemsDropSettingsConfig.getString(ItemsDropSettingsConfig.LORE_RESALE_WORTH); - resaleLore = resaleLore.replace("$resale", resale + ""); - resaleLore = resaleLore.replace("$currencyName", ConfigValues.economyConfig.getString(EconomySettingsConfig.CURRENCY_NAME)); - resaleLore = ChatColorConverter.convert(resaleLore); - - return resaleLore; - - } - - -} diff --git a/src/main/java/com/magmaguy/elitemobs/items/EliteEnchantments.java b/src/main/java/com/magmaguy/elitemobs/items/EliteEnchantments.java new file mode 100644 index 000000000..e252e87d2 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/items/EliteEnchantments.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.items; + +import org.bukkit.enchantments.Enchantment; + +public class EliteEnchantments { + + public static boolean isPotentialEliteEnchantment(Enchantment enchantment) { + return enchantment.getKey().equals(Enchantment.DAMAGE_ALL.getKey()) || + enchantment.getKey().equals(Enchantment.ARROW_DAMAGE.getKey()) || + enchantment.getKey().equals(Enchantment.PROTECTION_ENVIRONMENTAL.getKey()) || + enchantment.getKey().equals(Enchantment.DAMAGE_ARTHROPODS.getKey()) || + enchantment.getKey().equals(Enchantment.DAMAGE_UNDEAD.getKey()) || + enchantment.getKey().equals(Enchantment.PROTECTION_EXPLOSIONS.getKey()) || + enchantment.getKey().equals(Enchantment.PROTECTION_FIRE.getKey()) || + enchantment.getKey().equals(Enchantment.PROTECTION_PROJECTILE.getKey()) || + enchantment.getKey().equals(Enchantment.THORNS.getKey()); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/items/EliteItemLore.java b/src/main/java/com/magmaguy/elitemobs/items/EliteItemLore.java new file mode 100644 index 000000000..d1669e2f7 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/items/EliteItemLore.java @@ -0,0 +1,249 @@ +package com.magmaguy.elitemobs.items; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.api.EliteMobsItemDetector; +import com.magmaguy.elitemobs.config.EconomySettingsConfig; +import com.magmaguy.elitemobs.config.ItemSettingsConfig; +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfig; +import com.magmaguy.elitemobs.config.potioneffects.PotionEffectsConfig; +import com.magmaguy.elitemobs.items.customenchantments.CustomEnchantment; +import com.magmaguy.elitemobs.items.customenchantments.SoulbindEnchantment; +import com.magmaguy.elitemobs.items.potioneffects.ElitePotionEffect; +import com.magmaguy.elitemobs.items.potioneffects.ElitePotionEffectContainer; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.utils.WarningMessage; +import lombok.Getter; +import org.bukkit.ChatColor; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class EliteItemLore { + + @Getter + private ItemStack itemStack; + private ItemMeta itemMeta; + private List vanillaEnchantmentsLore = new ArrayList<>(); + private HashMap eliteVanillaEnchantments = new HashMap<>(); + private ArrayList eliteVanillaEnchantmentsLore = new ArrayList<>(); + private HashMap customEnchantments = new HashMap<>(); + private ArrayList customEnchantmentLore = new ArrayList<>(); + private List potionListLore = new ArrayList<>(); + private List lore; + private String soulbindInfo = null; + private boolean showItemWorth; + private String itemWorth = null; + private String itemSource = null; + private EliteEntity eliteEntity; + private Player soulboundPlayer = null; + private List customLore = new ArrayList<>(); + private int prestigeLevel = 0; + + + public EliteItemLore(ItemStack itemStack, boolean showItemWorth) { + + if (!EliteMobsItemDetector.isEliteMobsItem(itemStack)) { + new WarningMessage("Attempted to rewrite the lore of a non-elitemobs item! This is not supposed to happen."); + return; + } + + this.itemStack = itemStack; + this.itemMeta = itemStack.getItemMeta(); + this.lore = new ArrayList<>(); + this.showItemWorth = showItemWorth; + + constructVanillaEnchantments(); + + parseAllEliteEnchantments(); + constructEliteEnchantments(); + + parseCustomEnchantments(); + constructCustomEnchantments(); + + constructSoulbindEntry(); + constructSoulboundOwner(); + constructItemWorth(); + constructItemSource(); + constructCustomLore(); + constructPrestigeLevel(); + + constructPotionEffects(); + + writeNewLore(); + + this.itemMeta.setLore(lore); + this.itemStack.setItemMeta(this.itemMeta); + + } + + private void constructVanillaEnchantments() { + for (Enchantment enchantment : itemMeta.getEnchants().keySet()) + if (enchantment.getName().contains("CURSE")) + vanillaEnchantmentsLore.add(ChatColorConverter.convert( + "&c" + EnchantmentsConfig.getEnchantment(enchantment).getName() + " " + + itemMeta.getEnchants().get(enchantment))); + else + vanillaEnchantmentsLore.add(ChatColorConverter.convert( + "&7" + EnchantmentsConfig.getEnchantment(enchantment).getName() + " " + + itemMeta.getEnchants().get(enchantment))); + } + + private void parseAllEliteEnchantments() { + parseEliteEnchantments(Enchantment.DAMAGE_ALL); + parseEliteEnchantments(Enchantment.ARROW_DAMAGE); + parseEliteEnchantments(Enchantment.DAMAGE_ARTHROPODS); + parseEliteEnchantments(Enchantment.DAMAGE_UNDEAD); + parseEliteEnchantments(Enchantment.PROTECTION_ENVIRONMENTAL); + parseEliteEnchantments(Enchantment.PROTECTION_PROJECTILE); + parseEliteEnchantments(Enchantment.PROTECTION_EXPLOSIONS); + } + + private void parseEliteEnchantments(Enchantment enchantment) { + int enchantmentLevel = ItemTagger.getEnchantment(itemMeta, enchantment.getKey()); + if (enchantmentLevel > enchantment.getMaxLevel()) + eliteVanillaEnchantments.put(enchantment, enchantmentLevel - enchantment.getMaxLevel()); + } + + private void constructEliteEnchantments() { + for (Enchantment enchantment : eliteVanillaEnchantments.keySet()) + eliteVanillaEnchantmentsLore.add(ChatColorConverter.convert( + "&7" + ItemSettingsConfig.getEliteEnchantLoreString() + " " + + EnchantmentsConfig.getEnchantment(enchantment).getName() + + " " + eliteVanillaEnchantments.get(enchantment))); + + } + + /** + * Note: This excludes the soulbind enchantment as it doesn't store an integer value + */ + private void parseCustomEnchantments() { + for (CustomEnchantment customEnchantment : CustomEnchantment.getCustomEnchantments()) { + int enchantmentLevel = ItemTagger.getEnchantment(itemMeta, customEnchantment.getKey()); + if (enchantmentLevel > 0) + customEnchantments.put(customEnchantment, enchantmentLevel); + } + } + + private void constructCustomEnchantments() { + for (CustomEnchantment customEnchantment : customEnchantments.keySet()) + customEnchantmentLore.add(ChatColorConverter.convert + ("&6" + customEnchantment.getEnchantmentsConfigFields().getName() + " " + + customEnchantments.get(customEnchantment))); + } + + private void constructSoulbindEntry() { + Player player = SoulbindEnchantment.getSoulboundPlayer(itemMeta); + if (player == null) { + soulbindInfo = ChatColorConverter.convert(ItemSettingsConfig.getNoSoulbindLore()); + return; + } + soulbindInfo = ChatColorConverter.convert( + EnchantmentsConfig.getEnchantment("soulbind.yml") + .getFileConfiguration() + .getString("loreStrings") + .replace("$player", player.getDisplayName())); + } + + private void constructPrestigeLevel() { + this.prestigeLevel = SoulbindEnchantment.getPrestigeLevel(itemMeta); + } + + private void constructItemWorth() { + //Note: This writes a new value every time. Value might not have changed. This is not really an issue. + itemStack.setItemMeta(itemMeta); + ItemTagger.writeItemValue(itemStack, soulboundPlayer); + itemMeta = itemStack.getItemMeta(); + if (showItemWorth) + itemWorth = ItemSettingsConfig.getLoreWorth() + .replace("$worth", ItemWorthCalculator.determineItemWorth(itemStack, soulboundPlayer) + "") + .replace("$currencyName", EconomySettingsConfig.getCurrencyName()); + else + itemWorth = ItemSettingsConfig.getLoreResale() + .replace("$resale", ItemWorthCalculator.determineResaleWorth(itemStack, soulboundPlayer) + "") + .replace("$currencyName", EconomySettingsConfig.getCurrencyName()); + } + + private void constructSoulboundOwner() { + this.soulboundPlayer = SoulbindEnchantment.getSoulboundPlayer(itemMeta); + } + + private void constructItemSource() { + itemSource = ItemTagger.getItemSource(itemMeta); + } + + private void constructCustomLore() { + this.customLore = ItemTagger.getCustomLore(itemMeta); + } + + private void constructPotionEffects() { + for (ElitePotionEffect elitePotionEffect : ElitePotionEffectContainer.getElitePotionEffectContainer(itemMeta, ItemTagger.continuousPotionEffectKey)) + potionListLore.add(ChatColorConverter.convert(PotionEffectsConfig.getPotionEffect( + elitePotionEffect.getPotionEffect().getType().getName().toLowerCase() + ".yml").getName() + + ItemSettingsConfig.getPotionEffectContinuousLore() + " " + (elitePotionEffect.getPotionEffect().getAmplifier() + 1))); + for (ElitePotionEffect elitePotionEffect : ElitePotionEffectContainer.getElitePotionEffectContainer(itemMeta, ItemTagger.onHitPotionEffectKey)) + if (elitePotionEffect.getTarget().equals(ElitePotionEffect.Target.SELF)) + potionListLore.add(ChatColorConverter.convert(PotionEffectsConfig.getPotionEffect( + elitePotionEffect.getPotionEffect().getType().getName().toLowerCase() + ".yml").getName() + + ItemSettingsConfig.getPotionEffectOnHitSelfLore() + " " + (elitePotionEffect.getPotionEffect().getAmplifier() + 1))); + else + potionListLore.add(ChatColorConverter.convert(PotionEffectsConfig.getPotionEffect( + elitePotionEffect.getPotionEffect().getType().getName().toLowerCase() + ".yml").getName() + + ItemSettingsConfig.getPotionEffectOnHitTargetLore() + " " + (elitePotionEffect.getPotionEffect().getAmplifier() + 1))); + } + + private void writeNewLore() { + for (String string : ItemSettingsConfig.getLoreStructure()) { + + if (string.contains("$prestigeLevel")) + string = string.replace("$prestigeLevel", prestigeLevel + ""); + + if (string.contains("$itemLevel")) + string = string.replace("$itemLevel", ItemTierFinder.findBattleTier(itemStack) + ""); + + if (string.contains("$enchantments")) { + for (String entry : vanillaEnchantmentsLore) + lore.add(ChatColorConverter.convert(ItemSettingsConfig.getVanillaEnchantmentColor() + entry)); + } else if (string.contains("$eliteEnchantments")) { + for (String entry : eliteVanillaEnchantmentsLore) + lore.add(ChatColorConverter.convert(ItemSettingsConfig.getEliteEnchantmentColor() + ChatColor.stripColor(entry))); + } else if (string.contains("$itemSource")) { + if (itemSource != null) + lore.add(itemSource); + } else if (string.contains("$potionEffect")) { + for (String entry : potionListLore) + lore.add(ChatColorConverter.convert(ItemSettingsConfig.getPotionEffectColor() + entry)); + } else if (string.contains("$customEnchantments")) { + for (String entry : customEnchantmentLore) + lore.add(ChatColorConverter.convert(ItemSettingsConfig.getCustomEnchantmentColor() + ChatColor.stripColor(entry))); + } else if (string.contains("$loreResaleValue")) { + lore.add(itemWorth); + } else if (string.contains("$customLore")) { + for (String entry : customLore) + lore.add(ChatColorConverter.convert(entry)); + } else if (string.contains("$soulbindInfo")) { + lore.add(soulbindInfo); + //bypasses in case of conditional formatting + } else if (string.contains("$ifPotionEffects")) { + if (!potionListLore.isEmpty()) + lore.add(string.replace("$ifPotionEffects", "")); + } else if (string.contains("$ifEnchantments")) { + if (!vanillaEnchantmentsLore.isEmpty()) + lore.add(string.replace("$ifEnchantments", "")); + } else if (string.contains("$ifLore")) { + if (!customLore.isEmpty()) + lore.add(string.replace("$ifLore", "")); + } else if (string.contains("$ifCustomEnchantments")) { + if (!customEnchantments.isEmpty()) + lore.add(string.replace("$ifCustomEnchantments", "")); + } else + lore.add(ChatColorConverter.convert(string)); + + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/items/EnchantmentHider.java b/src/main/java/com/magmaguy/elitemobs/items/EnchantmentHider.java deleted file mode 100644 index 0d4c0e2e9..000000000 --- a/src/main/java/com/magmaguy/elitemobs/items/EnchantmentHider.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.items; - -import org.bukkit.inventory.ItemFlag; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; - -public class EnchantmentHider { - - public static ItemStack hideEnchantments(ItemStack itemStack) { - - ItemMeta itemMeta = itemStack.getItemMeta(); - itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); - itemStack.setItemMeta(itemMeta); - - return itemStack; - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/items/ItemDropVelocity.java b/src/main/java/com/magmaguy/elitemobs/items/ItemDropVelocity.java index 50ded0589..306c1ebb7 100644 --- a/src/main/java/com/magmaguy/elitemobs/items/ItemDropVelocity.java +++ b/src/main/java/com/magmaguy/elitemobs/items/ItemDropVelocity.java @@ -1,18 +1,3 @@ -/* - * 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 . - */ - package com.magmaguy.elitemobs.items; import org.bukkit.util.Vector; diff --git a/src/main/java/com/magmaguy/elitemobs/items/ItemLootShower.java b/src/main/java/com/magmaguy/elitemobs/items/ItemLootShower.java new file mode 100644 index 000000000..09aa2ddaf --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/items/ItemLootShower.java @@ -0,0 +1,447 @@ +package com.magmaguy.elitemobs.items; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.adventurersguild.GuildRank; +import com.magmaguy.elitemobs.config.EconomySettingsConfig; +import com.magmaguy.elitemobs.config.ItemSettingsConfig; +import com.magmaguy.elitemobs.economy.EconomyHandler; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.items.customenchantments.SoulbindEnchantment; +import com.magmaguy.elitemobs.playerdata.ElitePlayerInventory; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import com.magmaguy.elitemobs.utils.Round; +import com.magmaguy.elitemobs.utils.WarningMessage; +import net.md_5.bungee.api.ChatMessageType; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Item; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityPickupItemEvent; +import org.bukkit.event.inventory.InventoryPickupItemEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.UUID; +import java.util.concurrent.ThreadLocalRandom; + +public class ItemLootShower implements Listener { + + private static final HashMap playerCurrencyPickup = new HashMap<>(); + public static HashMap coinValues = new HashMap<>(); + private final Player player; + + public ItemLootShower(double eliteMobTier, Location location, Player player) { + + this.player = player; + + if (ElitePlayerInventory.playerInventories.get(player.getUniqueId()) == null) return; + + if (!EconomySettingsConfig.isEnableCurrencyShower() || !SoulbindEnchantment.isEnabled) + return; + + if (eliteMobTier - ElitePlayerInventory.playerInventories.get(player.getUniqueId()).getFullPlayerTier(false) < -ItemSettingsConfig.getLootLevelDifferenceLockout()) { + player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText( + ChatColorConverter.convert("&8EM] &4You are too well equipped to get coins for killing this Elite!"))); + return; + } + if (ItemSettingsConfig.isPutLootDirectlyIntoPlayerInventory()) + addDirectly(eliteMobTier); + else + addIndirectly(location, getCurrencyAmount(eliteMobTier)); + } + + public ItemLootShower(Location location, Player player, int amount) { + this.player = player; + addIndirectly(location, amount); + } + + private static void sendCurrencyNotification(Player player) { + if (playerCurrencyPickup.containsKey(player)) return; + + new BukkitRunnable() { + double oldAmount = 0; + + @Override + public void run() { + + if (!playerCurrencyPickup.containsKey(player)) { + playerCurrencyPickup.put(player, 0.0); + return; + } + + if (oldAmount != playerCurrencyPickup.get(player)) { + oldAmount = playerCurrencyPickup.get(player); + return; + } + + player.sendMessage(ChatColorConverter.convert(EconomySettingsConfig.getChatCurrencyShowerMessage() + .replace("$currency_name", EconomySettingsConfig.getCurrencyName()) + .replace("$amount", playerCurrencyPickup.get(player) + ""))); + + playerCurrencyPickup.remove(player); + sendAdventurersGuildNotification(player); + + cancel(); + + } + + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 40); + + } + + private static void sendAdventurersGuildNotification(Player player) { + player.spigot().sendMessage(ChatMessageType.ACTION_BAR, + TextComponent.fromLegacyText(ChatColorConverter.convert(EconomySettingsConfig.getAdventurersGuildNotificationMessage()))); + } + + private void addIndirectly(Location location, int currencyAmount2) { + new BukkitRunnable() { + int currencyAmount = currencyAmount2; + + @Override + public void run() { + + if (currencyAmount <= 0) { + cancel(); + return; + } + + if (currencyAmount >= 1000) { + if (ThreadLocalRandom.current().nextDouble() < 0.65) { + dropOneThousand(location); + currencyAmount -= 1000; + return; + } + } + + if (currencyAmount >= 500) { + if (ThreadLocalRandom.current().nextDouble() < 0.65) { + dropFiveHundred(location); + currencyAmount -= 500; + return; + } + } + + if (currencyAmount >= 100) { + if (ThreadLocalRandom.current().nextDouble() < 0.65) { + dropOneHundred(location); + currencyAmount -= 100; + return; + } + + } else if (currencyAmount >= 50) { + if (ThreadLocalRandom.current().nextDouble() < 0.65) { + dropFifty(location); + currencyAmount -= 50; + return; + } + + } else if (currencyAmount >= 20) { + if (ThreadLocalRandom.current().nextDouble() < 0.65) { + dropTwenty(location); + currencyAmount -= 20; + return; + } + + } else if (currencyAmount >= 10) { + if (ThreadLocalRandom.current().nextDouble() < 0.65) { + dropTen(location); + currencyAmount -= 10; + return; + } + + } else if (currencyAmount >= 5) { + if (ThreadLocalRandom.current().nextDouble() < 0.65) { + dropFive(location); + currencyAmount -= 5; + return; + } + + } else { + dropOne(location); + currencyAmount--; + } + } + }.runTaskTimer(MetadataHandler.PLUGIN, 2, 2); + } + + private int getCurrencyAmount(double eliteMobTier) { + return (int) (eliteMobTier / 2D * EconomySettingsConfig.getCurrencyShowerMultiplier() * + GuildRank.currencyBonusMultiplier(GuildRank.getGuildPrestigeRank(player))); + } + + private void addDirectly(double eliteMobTier) { + EconomyHandler.addCurrency(player.getUniqueId(), getCurrencyAmount(eliteMobTier)); + player.sendMessage(ChatColorConverter.convert(EconomySettingsConfig.getChatCurrencyShowerMessage() + .replace("$currency_name", EconomySettingsConfig.getCurrencyName()) + .replace("$amount", getCurrencyAmount(eliteMobTier) + ""))); + } + + private Item generateCurrencyItem(Material material, Location location, double value) { + + ItemStack currencyItemStack = SoulbindEnchantment.addEnchantment(ItemStackGenerator.generateItemStack(material, "", + Arrays.asList("EliteMobsCurrencyItem", value + "", ThreadLocalRandom.current().nextDouble() + "")), player); + int model = 1; + try { + model = EconomySettingsConfig.getThisConfiguration().getInt("lootShowerData." + (int) value); + } catch (Exception ex) { + new WarningMessage("Failed to get coin model for value " + value + " !"); + } + setCoinModel(currencyItemStack, model); + Item currencyItem = location.getWorld().dropItem(location.clone().add(new Vector(0, 1, 0)), currencyItemStack); + EntityTracker.registerVisualEffects(currencyItem); + + currencyItem.setVelocity(new Vector( + (ThreadLocalRandom.current().nextDouble() - 0.5) / 2, + 0.5, + (ThreadLocalRandom.current().nextDouble() - 0.5) / 2)); + + SoulbindEnchantment.addPhysicalDisplay(currencyItem, this.player); + + new Coin(value, player, currencyItem); + + return currencyItem; + + } + + private void dropOne(Location location) { + + Item currencyItem; + try { + currencyItem = generateCurrencyItem(Material.getMaterial(EconomySettingsConfig.getLootShowerMaterial1()), location, 1); + } catch (Exception ex) { + new WarningMessage("Material for EliteMob shower 1 is invalid. Defaulting to gold nugget."); + currencyItem = generateCurrencyItem(Material.GOLD_NUGGET, location, 1); + } + + currencyItem.setCustomName(ChatColorConverter.convert("&7" + 1 + " " + EconomySettingsConfig.getCurrencyName())); + currencyItem.setCustomNameVisible(true); + + } + + private void dropFive(Location location) { + + Item currencyItem; + try { + currencyItem = generateCurrencyItem(Material.getMaterial(EconomySettingsConfig.getLootShowerMaterial5()), location, 5); + } catch (Exception ex) { + new WarningMessage("Material for EliteMob shower 5 is invalid. Defaulting to gold ingot."); + currencyItem = generateCurrencyItem(Material.GOLD_INGOT, location, 5); + } + + currencyItem.setCustomName(ChatColorConverter.convert("&f" + 5 + " " + EconomySettingsConfig.getCurrencyName())); + currencyItem.setCustomNameVisible(true); + } + + private void dropTen(Location location) { + + Item currencyItem; + try { + currencyItem = generateCurrencyItem(Material.getMaterial(EconomySettingsConfig.getLootShowerMaterial10()), location, 10); + } catch (Exception ex) { + new WarningMessage("Material for EliteMob shower 10 is invalid. Defaulting to Gold block."); + currencyItem = generateCurrencyItem(Material.GOLD_BLOCK, location, 10); + } + + currencyItem.setCustomName(ChatColorConverter.convert("&a" + 10 + " " + EconomySettingsConfig.getCurrencyName())); + currencyItem.setCustomNameVisible(true); + } + + private void dropTwenty(Location location) { + + Item currencyItem; + try { + currencyItem = generateCurrencyItem(Material.getMaterial(EconomySettingsConfig.getLootShowerMaterial20()), location, 20); + } catch (Exception ex) { + new WarningMessage("Material for EliteMob shower 20 is invalid. Defaulting to emerald."); + currencyItem = generateCurrencyItem(Material.EMERALD, location, 20); + } + + currencyItem.setCustomName(ChatColorConverter.convert("&2" + 20 + " " + EconomySettingsConfig.getCurrencyName())); + currencyItem.setCustomNameVisible(true); + } + + private void dropFifty(Location location) { + + Item currencyItem; + try { + currencyItem = generateCurrencyItem(Material.getMaterial(EconomySettingsConfig.getLootShowerMaterial50()), location, 50); + } catch (Exception ex) { + new WarningMessage("Material for EliteMob shower 50 is invalid. Defaulting to emerald block."); + currencyItem = generateCurrencyItem(Material.EMERALD_BLOCK, location, 50); + } + + currencyItem.setCustomName(ChatColorConverter.convert("&2" + 50 + " " + EconomySettingsConfig.getCurrencyName())); + currencyItem.setCustomNameVisible(true); + } + + private void dropOneHundred(Location location) { + Item currencyItem; + try { + currencyItem = generateCurrencyItem(Material.getMaterial(EconomySettingsConfig.getLootShowerMaterial100()), location, 100); + } catch (Exception ex) { + new WarningMessage("Material for EliteMob shower 100 is invalid. Defaulting to diamond."); + currencyItem = generateCurrencyItem(Material.DIAMOND, location, 100); + } + + currencyItem.setCustomName(ChatColorConverter.convert("&2" + 100 + " " + EconomySettingsConfig.getCurrencyName())); + currencyItem.setCustomNameVisible(true); + } + + private void dropFiveHundred(Location location) { + Item currencyItem; + try { + currencyItem = generateCurrencyItem(Material.getMaterial(EconomySettingsConfig.getLootShowerMaterial500()), location, 500); + } catch (Exception ex) { + new WarningMessage("Material for EliteMob shower 500 is invalid. Defaulting to diamond block."); + currencyItem = generateCurrencyItem(Material.DIAMOND_BLOCK, location, 500); + } + + currencyItem.setCustomName(ChatColorConverter.convert("&2" + 500 + " " + EconomySettingsConfig.getCurrencyName())); + currencyItem.setCustomNameVisible(true); + } + + private void dropOneThousand(Location location) { + Item currencyItem; + try { + currencyItem = generateCurrencyItem(Material.getMaterial(EconomySettingsConfig.getLootShowerMaterial1000()), location, 1000); + } catch (Exception ex) { + new WarningMessage("Material for EliteMob shower 1000 is invalid. Defaulting to nether star."); + currencyItem = generateCurrencyItem(Material.NETHER_STAR, location, 1000); + } + + currencyItem.setCustomName(ChatColorConverter.convert("&2" + 1000 + " " + EconomySettingsConfig.getCurrencyName())); + currencyItem.setCustomNameVisible(true); + } + + private ItemStack setCoinModel(ItemStack itemStack, int data) { + ItemMeta itemMeta = itemStack.getItemMeta(); + itemMeta.setCustomModelData(data); + itemStack.setItemMeta(itemMeta); + return itemStack; + } + + /** + * Currency pickup event + */ + public static class ItemLootShowerEvents implements Listener { + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public static void onItemPickup(EntityPickupItemEvent event) { + //coins are soulbound so if someone can pick them up they can have it + if (!coinValues.containsKey(event.getItem().getUniqueId())) return; + event.setCancelled(true); + if (!event.getEntity().getType().equals(EntityType.PLAYER)) return; + + Coin coin = coinValues.get(event.getItem().getUniqueId()); + if (!coin.pickupable) + return; + + coinValues.remove(event.getItem().getUniqueId()); + double amountIncremented = coin.value; + Player player = (Player) event.getEntity(); + event.getItem().remove(); + EconomyHandler.addCurrency(player.getUniqueId(), amountIncremented); + sendCurrencyNotification(player); + + //cache for counting how much coin they're getting over a short amount of time + if (playerCurrencyPickup.containsKey(player)) + playerCurrencyPickup.put(player, playerCurrencyPickup.get(player) + amountIncremented); + else + playerCurrencyPickup.put(player, amountIncremented); + + player.spigot().sendMessage(ChatMessageType.ACTION_BAR, + TextComponent.fromLegacyText( + ChatColorConverter.convert(EconomySettingsConfig.getActionBarCurrencyShowerMessage() + .replace("$currency_name", EconomySettingsConfig.getCurrencyName()) + .replace("$amount", Round.twoDecimalPlaces(playerCurrencyPickup.get(player)) + "")))); + } + + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public static void onItemPickup(InventoryPickupItemEvent event) { + if (!coinValues.containsKey(event.getItem().getUniqueId())) return; + event.setCancelled(true); + } + } + + private class Coin { + UUID player; + UUID item; + double value; + boolean pickupable; + + public Coin(double value, Player player, Item item) { + this.player = player.getUniqueId(); + this.value = value; + this.item = item.getUniqueId(); + coinValues.put(item.getUniqueId(), this); + pickupable = false; + item.setGravity(false); + new BukkitRunnable() { + @Override + public void run() { + if (coinValues.containsKey(item.getUniqueId())) { + if (Bukkit.getEntity(item.getUniqueId()) != null) + Bukkit.getEntity(item.getUniqueId()).remove(); + coinValues.remove(item.getUniqueId()); + } + } + }.runTaskLater(MetadataHandler.PLUGIN, 20 * 60 * 5); + + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + + if (!item.isValid() || + !player.isValid() || + !player.getWorld().equals(item.getWorld()) || + counter > 20 * 4 || + item.getLocation().distanceSquared(player.getLocation()) > 900) { + cancel(); + pickupable = true; + item.setGravity(true); + return; + } + + item.setVelocity(player.getLocation().clone().subtract(item.getLocation()).toVector().normalize().multiply(0.2)); + + if (player.getLocation().distanceSquared(item.getLocation()) <= 1) { + item.remove(); + EconomyHandler.addCurrency(player.getUniqueId(), value); + sendCurrencyNotification(player); + + //cache for counting how much coin they're getting over a short amount of time + if (playerCurrencyPickup.containsKey(player)) + playerCurrencyPickup.put(player, playerCurrencyPickup.get(player) + value); + else + playerCurrencyPickup.put(player, value); + + player.spigot().sendMessage(ChatMessageType.ACTION_BAR, + TextComponent.fromLegacyText( + ChatColorConverter.convert(EconomySettingsConfig.getActionBarCurrencyShowerMessage() + .replace("$currency_name", EconomySettingsConfig.getCurrencyName()) + .replace("$amount", Round.twoDecimalPlaces(playerCurrencyPickup.get(player)) + "")))); + coinValues.remove(item.getUniqueId()); + cancel(); + return; + } + + counter++; + } + }.runTaskTimer(MetadataHandler.PLUGIN, 1, 1); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/items/ItemTagger.java b/src/main/java/com/magmaguy/elitemobs/items/ItemTagger.java new file mode 100644 index 000000000..19112c43b --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/items/ItemTagger.java @@ -0,0 +1,210 @@ +package com.magmaguy.elitemobs.items; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.config.ItemSettingsConfig; +import com.magmaguy.elitemobs.items.potioneffects.ElitePotionEffect; +import com.magmaguy.elitemobs.items.potioneffects.ElitePotionEffectContainer; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.utils.PersistentVanillaData; +import org.bukkit.NamespacedKey; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.tags.ItemTagType; +import org.bukkit.persistence.PersistentDataType; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Objects; + +public class ItemTagger { + + public static final NamespacedKey eliteMobsItemNamespacedKey = new NamespacedKey(MetadataHandler.PLUGIN, "EliteMobsItem"); + public static final NamespacedKey customLore = new NamespacedKey(MetadataHandler.PLUGIN, "CustomLore"); + public static String itemValue = "ItemValue"; + public static NamespacedKey onHitPotionEffectKey = new NamespacedKey(MetadataHandler.PLUGIN, "onHitPotionEffect"); + public static NamespacedKey continuousPotionEffectKey = new NamespacedKey(MetadataHandler.PLUGIN, "continuousPotionEffect"); + public static NamespacedKey itemSource = new NamespacedKey(MetadataHandler.PLUGIN, "itemSource"); + + public static void registerEliteItem(ItemMeta itemMeta) { + itemMeta.getPersistentDataContainer().set(eliteMobsItemNamespacedKey, PersistentDataType.BYTE, (byte) 1); + } + + /** + * Used to register custom lore as a string to the item. This is necessary for the lore updater as it redraws the custom + * lore portion of the item based on these contents. + * + * @param itemMeta ItemStack to which custom lore should be added + * @param lore Custom part of the lore to add + */ + public static void registerCustomLore(ItemMeta itemMeta, List lore) { + StringBuilder parsedLore = new StringBuilder(); + for (int i = 0; i < lore.size(); i++) { + parsedLore.append(lore.get(i)); + if (i < lore.size() - 1) + parsedLore.append("\n"); + } + itemMeta.getPersistentDataContainer().set(customLore, PersistentDataType.STRING, parsedLore.toString()); + } + + /** + * Returns any custom lore stored in an item. Returns null if there isn't any. + * + * @param itemMeta + * @return + */ + public static List getCustomLore(ItemMeta itemMeta) { + String rawLore = itemMeta.getPersistentDataContainer().get(customLore, PersistentDataType.STRING); + if (rawLore == null) + return new ArrayList<>(); + ArrayList parsedLore = new ArrayList(); + for (String entry : rawLore.split("\n")) + parsedLore.add(entry); + return parsedLore; + } + + public static boolean isEliteItem(ItemStack itemStack) { + if (itemStack == null) return false; + if (!itemStack.hasItemMeta()) return false; + if (itemStack.getItemMeta().getCustomTagContainer().hasCustomTag(eliteMobsItemNamespacedKey, ItemTagType.BYTE)) + return true; + return itemStack.getItemMeta().getPersistentDataContainer().has(eliteMobsItemNamespacedKey, PersistentDataType.BYTE); + } + + /** + * Registers all enchantments as they'd appear when constructing an item in EliteMobs + * + * @param itemMeta + * @param enchantmentMap + */ + public static void registerEnchantments(ItemMeta itemMeta, HashMap enchantmentMap) { + for (Enchantment enchantment : enchantmentMap.keySet()) + if (EliteEnchantments.isPotentialEliteEnchantment(enchantment)) + registerEnchantment(itemMeta, enchantment.getKey(), enchantmentMap.get(enchantment)); + } + + /** + * For minecraft enchantments + * + * @param itemMeta + * @param enchantmentKey + * @param enchantmentLevel + */ + public static void registerEnchantment(ItemMeta itemMeta, NamespacedKey enchantmentKey, int enchantmentLevel) { + itemMeta.getPersistentDataContainer().set(enchantmentKey, PersistentDataType.INTEGER, enchantmentLevel); + } + + public static void registerCustomEnchantments(ItemMeta itemMeta, HashMap customEnchantments) { + for (String subString : customEnchantments.keySet()) + registerCustomEnchantment(itemMeta, subString, customEnchantments.get(subString)); + } + + /** + * For custom enchantments + * + * @param itemMeta + * @param enchantmentKey + * @param enchantmentLevel + */ + public static void registerCustomEnchantment(ItemMeta itemMeta, String enchantmentKey, int enchantmentLevel) { + itemMeta.getPersistentDataContainer().set(new NamespacedKey(MetadataHandler.PLUGIN, enchantmentKey), PersistentDataType.INTEGER, enchantmentLevel); + } + + public static void registerCustomEnchantment(ItemMeta itemMeta, String enchantmentKey, String uuid) { + itemMeta.getPersistentDataContainer().set(new NamespacedKey(MetadataHandler.PLUGIN, enchantmentKey), PersistentDataType.STRING, uuid); + } + + public static int getEnchantment(ItemMeta itemMeta, String enchantmentKey) { + return getEnchantment(itemMeta, new NamespacedKey(MetadataHandler.PLUGIN, enchantmentKey)); + } + + /** + * Returns the level of that enchantment on the item. 0 means the enchantment is not present. + * + * @param itemMeta + * @param enchantmentKey + * @return + */ + public static int getEnchantment(ItemMeta itemMeta, NamespacedKey enchantmentKey) { + if (itemMeta == null) + return 0; + Integer level = itemMeta.getPersistentDataContainer().get(enchantmentKey, PersistentDataType.INTEGER); + if (level == null) { + Enchantment enchantment = Enchantment.getByKey(enchantmentKey); + if (enchantment != null) + return itemMeta.getEnchantLevel(enchantment); + else + return 0; + } else + return level; + } + + public static boolean hasEnchantment(ItemMeta itemMeta, NamespacedKey enchantmentKey) { + if (!itemMeta.hasLore()) //early performance tweak + return false; + if (itemMeta.getCustomTagContainer().hasCustomTag(enchantmentKey, ItemTagType.INTEGER)) + return true; + return itemMeta.getPersistentDataContainer().has(enchantmentKey, PersistentDataType.INTEGER); + } + + public static boolean hasKey(ItemStack itemStack, String key) { + if (itemStack == null) return false; + if (!itemStack.hasItemMeta()) return false; + return Objects.requireNonNull(itemStack.getItemMeta()).getPersistentDataContainer().has(new NamespacedKey(MetadataHandler.PLUGIN, key), PersistentDataType.STRING); + } + + public static boolean hasEnchantment(ItemMeta itemMeta, String keyString) { + NamespacedKey enchantmentKey = new NamespacedKey(MetadataHandler.PLUGIN, keyString); + if (!itemMeta.hasLore()) //early performance tweak + return false; + if (itemMeta.getCustomTagContainer().hasCustomTag(enchantmentKey, ItemTagType.INTEGER)) + return true; + return itemMeta.getPersistentDataContainer().has(enchantmentKey, PersistentDataType.INTEGER); + } + + public static ArrayList getPotionEffects(ItemMeta itemMeta, NamespacedKey namespacedKey) { + return ElitePotionEffectContainer.getElitePotionEffectContainer(itemMeta, namespacedKey); + } + + public static void registerItemSource(EliteEntity eliteEntity, ItemMeta itemMeta) { + if (eliteEntity == null) { + itemMeta.getPersistentDataContainer().set(itemSource, PersistentDataType.STRING, ChatColorConverter.convert(ItemSettingsConfig.getShopItemSource())); + return; + } + itemMeta.getPersistentDataContainer().set(itemSource, PersistentDataType.STRING, ChatColorConverter.convert(ItemSettingsConfig.getMobItemSource().replace("$mob", eliteEntity.getName()))); + } + + public static String getItemSource(ItemMeta itemMeta) { + return itemMeta.getPersistentDataContainer().get(itemSource, PersistentDataType.STRING); + } + + /** + * Writes the value into the persistent data container. This is used to only ever calculate item worth once. + * The weakness with this system is that if admins change the price scaling, the changes will not affect older items. + * This is still worth it to only ever calculate the price of items once, as mass calculating item prices can be costly. + * Also, item values will be updated with each lore refresh. + * NOTE: This is the item value, not the resale value. These are two very different values! + * + * @param itemStack ItemStack to register the value onto. + * @param player Player associated to the ItemStack. This is necessary because different prestige tiers will result in + * different prices. + */ + public static void writeItemValue(ItemStack itemStack, Player player) { + PersistentVanillaData.write(itemStack, itemValue, ItemWorthCalculator.writeItemWorth(itemStack, player)); + } + + /** + * Gets the item value for the selected Elite Item. + * + * @param itemStack ItemStack to get value from + * @return Value. Will be -1 if no values is registered! + */ + public static double getItemValue(ItemStack itemStack) { + return PersistentVanillaData.getDouble(itemStack, itemValue); + } + + +} diff --git a/src/main/java/com/magmaguy/elitemobs/items/ItemTierFinder.java b/src/main/java/com/magmaguy/elitemobs/items/ItemTierFinder.java index 0db959a06..75a05eb63 100644 --- a/src/main/java/com/magmaguy/elitemobs/items/ItemTierFinder.java +++ b/src/main/java/com/magmaguy/elitemobs/items/ItemTierFinder.java @@ -1,253 +1,330 @@ package com.magmaguy.elitemobs.items; -import com.magmaguy.elitemobs.items.itemconstructor.LoreGenerator; -import com.magmaguy.elitemobs.mobconstructor.CombatSystem; +import com.magmaguy.elitemobs.combatsystem.CombatSystem; +import com.magmaguy.elitemobs.config.ItemSettingsConfig; +import com.magmaguy.elitemobs.utils.VersionChecker; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; -import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - public class ItemTierFinder { - public static double findPlayerTier(Player player) { - - return (4 * findArmorSetTier(player) + findWeaponTier(player)) / 5; - - } - - public static double findArmorSetTier(Player player) { - - double totalArmorThreat = 0; - - if (player.getEquipment().getHelmet() != null) { - - ItemStack helmet = player.getEquipment().getHelmet(); - - totalArmorThreat += findBattleTier(helmet); - - } - - if (player.getEquipment().getChestplate() != null) { - - ItemStack chestplate = player.getEquipment().getChestplate(); - - totalArmorThreat += findBattleTier(chestplate); - - } - - if (player.getEquipment().getLeggings() != null) { - - ItemStack leggings = player.getEquipment().getLeggings(); - - totalArmorThreat += findBattleTier(leggings); - - } - - if (player.getEquipment().getBoots() != null) { - - ItemStack boots = player.getEquipment().getBoots(); - - totalArmorThreat += findBattleTier(boots); - - } - - double averageArmorThreat = totalArmorThreat / 4; - - return averageArmorThreat; - + private static final int IRON_TIER = CombatSystem.IRON_TIER_LEVEL; + private static final int STONE_CHAIN_TIER = CombatSystem.IRON_TIER_LEVEL; + private static final int GOLD_WOOD_LEATHER_TIER = CombatSystem.GOLD_WOOD_LEATHER_TIER_LEVEL; + private static final int DIAMOND_TIER = CombatSystem.DIAMOND_TIER_LEVEL; + private ItemTierFinder() { } - public static double findWeaponTier(Player player) { - - List itemList = new ArrayList<>(); - - if (player.getInventory().getItemInOffHand() != null && !player.getInventory().getItemInOffHand().getType().equals(Material.AIR)) { - - itemList.add(player.getInventory().getItemInOffHand()); - - } - - for (int i = 0; i < 9; i++) { - - if (player.getInventory().getItem(i) != null && !player.getInventory().getItem(i).getType().equals(Material.AIR)) { - - Material material = player.getInventory().getItem(i).getType(); - - if (material.equals(Material.DIAMOND_SWORD) || material.equals(Material.DIAMOND_AXE) || - material.equals(Material.IRON_SWORD) || material.equals(Material.IRON_AXE) || - material.equals(Material.STONE_SWORD) || material.equals(Material.STONE_AXE) || - material.equals(Material.GOLD_SWORD) || material.equals(Material.GOLD_AXE) || - material.equals(Material.WOOD_SWORD) || material.equals(Material.WOOD_AXE) || - material.equals(Material.BOW)) { - - itemList.add(player.getInventory().getItem(i)); - - } - - } - - } - - double highestTier = 0; - - if (itemList.size() > 0) { - - for (ItemStack itemStack : itemList) { - - double currentTier = findBattleTier(itemStack); - - if (currentTier > highestTier) { - - highestTier = currentTier; - - } - - } - - } - - return highestTier; - + public static int findBattleTier(ItemStack itemStack) { + return parseBattleMaterials(itemStack); } - private static final double IRON_TIER = CombatSystem.IRON_TIER_LEVEL; - private static final double STONE_CHAIN_TIER = CombatSystem.IRON_TIER_LEVEL; - private static final double GOLD_WOOD_LEATHER_TIER = CombatSystem.GOLD_WOOD_LEATHER_TIER_LEVEL; - private static final double DIAMOND_TIER = CombatSystem.DIAMOND_TIER_LEVEL; - - public static double findGenericTier(Material material, HashMap enchantmentList) { - - double tier = 0; - + private static int parseBattleMaterials(ItemStack itemStack) { + if (itemStack == null || itemStack.getItemMeta() == null) return 0; + int mainEnchantment = 0; + Material material = itemStack.getType(); switch (material) { - case DIAMOND_PICKAXE: - case DIAMOND_SPADE: - return DIAMOND_TIER + findMainEnchantment(enchantmentList, Enchantment.DIG_SPEED); - case STONE_PICKAXE: - case STONE_SPADE: - return STONE_CHAIN_TIER + findMainEnchantment(enchantmentList, Enchantment.DIG_SPEED); - case IRON_PICKAXE: - case IRON_SPADE: - return IRON_TIER + findMainEnchantment(enchantmentList, Enchantment.DIG_SPEED); - case GOLD_PICKAXE: - case GOLD_SPADE: - case WOOD_PICKAXE: - case WOOD_SPADE: - return GOLD_WOOD_LEATHER_TIER + findMainEnchantment(enchantmentList, Enchantment.DIG_SPEED); + case DIAMOND_HOE: + case IRON_HOE: + case STONE_HOE: + case GOLDEN_HOE: + case WOODEN_HOE: + if (!ItemSettingsConfig.isUseHoesAsWeapons()) return 0; + case DIAMOND_SWORD: + case DIAMOND_AXE: + case TRIDENT: + case IRON_AXE: + case IRON_SWORD: + case STONE_SWORD: + case STONE_AXE: + case WOODEN_SWORD: + case WOODEN_AXE: + case GOLDEN_SWORD: + case GOLDEN_AXE: + mainEnchantment = findMainEnchantment(itemStack, Enchantment.DAMAGE_ALL); + break; + case DIAMOND_BOOTS: + case DIAMOND_CHESTPLATE: + case DIAMOND_HELMET: + case DIAMOND_LEGGINGS: + case IRON_BOOTS: + case IRON_CHESTPLATE: + case IRON_HELMET: + case IRON_LEGGINGS: + case SHIELD: + case CHAINMAIL_BOOTS: + case CHAINMAIL_CHESTPLATE: + case CHAINMAIL_HELMET: + case CHAINMAIL_LEGGINGS: + case GOLDEN_BOOTS: + case GOLDEN_CHESTPLATE: + case GOLDEN_HELMET: + case GOLDEN_LEGGINGS: + case LEATHER_BOOTS: + case LEATHER_CHESTPLATE: + case LEATHER_HELMET: + case LEATHER_LEGGINGS: + case TURTLE_HELMET: + mainEnchantment = findMainEnchantment(itemStack, Enchantment.PROTECTION_ENVIRONMENTAL); + break; + case BOW: + case CROSSBOW: + mainEnchantment = findMainEnchantment(itemStack, Enchantment.ARROW_DAMAGE); + break; + default: + if (!VersionChecker.serverVersionOlderThan(16, 0)) { + if (material.equals(Material.NETHERITE_HELMET) || + material.equals(Material.NETHERITE_CHESTPLATE) || + material.equals(Material.NETHERITE_LEGGINGS) || + material.equals(Material.NETHERITE_BOOTS)) + mainEnchantment = findMainEnchantment(itemStack, Enchantment.PROTECTION_ENVIRONMENTAL); + if (material.equals(Material.NETHERITE_SWORD) || + material.equals(Material.NETHERITE_AXE) || + material.equals(Material.NETHERITE_HOE) && ItemSettingsConfig.isUseHoesAsWeapons()) + mainEnchantment = findMainEnchantment(itemStack, Enchantment.DAMAGE_ALL); + } } - - if (tier == 0) - tier = findBattleTier(material, enchantmentList); - - return tier; - + return getMaterialTier(material) + mainEnchantment; } - public static double findBattleTier(Material material, HashMap enchantmentList) { - - return parseMaterials(material, findMainEnchantment(enchantmentList, Enchantment.DAMAGE_ALL), findMainEnchantment(enchantmentList, Enchantment.PROTECTION_ENVIRONMENTAL), findMainEnchantment(enchantmentList, Enchantment.ARROW_DAMAGE)); - - } - - public static double findBattleTier(ItemStack itemStack) { - - Material material = itemStack.getType(); - - return parseMaterials(material, findMainEnchantment(itemStack, Enchantment.DAMAGE_ALL), findMainEnchantment(itemStack, Enchantment.PROTECTION_ENVIRONMENTAL), findMainEnchantment(itemStack, Enchantment.ARROW_DAMAGE)); - - } - - private static double parseMaterials(Material material, int mainEnchantment, int mainEnchantment2, int mainEnchantment3) { + public static int getMaterialTier(Material material) { switch (material) { + case TRIDENT: + return CombatSystem.TRIDENT_TIER_LEVEL; case DIAMOND_SWORD: case DIAMOND_AXE: - return DIAMOND_TIER + mainEnchantment; case DIAMOND_BOOTS: case DIAMOND_CHESTPLATE: case DIAMOND_HELMET: case DIAMOND_LEGGINGS: - return DIAMOND_TIER + mainEnchantment2; + return DIAMOND_TIER; case IRON_AXE: case IRON_SWORD: - return IRON_TIER + mainEnchantment; case IRON_BOOTS: case IRON_CHESTPLATE: case IRON_HELMET: case IRON_LEGGINGS: - return IRON_TIER + mainEnchantment2; case SHIELD: - return IRON_TIER + mainEnchantment2; + case BOW: + case CROSSBOW: + return IRON_TIER; case CHAINMAIL_BOOTS: case CHAINMAIL_CHESTPLATE: case CHAINMAIL_HELMET: case CHAINMAIL_LEGGINGS: - return STONE_CHAIN_TIER + mainEnchantment2; case STONE_SWORD: - return STONE_CHAIN_TIER + mainEnchantment; - case GOLD_BOOTS: - case GOLD_CHESTPLATE: - case GOLD_HELMET: - case GOLD_LEGGINGS: + case STONE_AXE: + return STONE_CHAIN_TIER; + case GOLDEN_BOOTS: + case GOLDEN_CHESTPLATE: + case GOLDEN_HELMET: + case GOLDEN_LEGGINGS: case LEATHER_BOOTS: case LEATHER_CHESTPLATE: case LEATHER_HELMET: case LEATHER_LEGGINGS: - return GOLD_WOOD_LEATHER_TIER + mainEnchantment2; - case WOOD_SWORD: - case WOOD_AXE: - case GOLD_SWORD: - case GOLD_AXE: - return GOLD_WOOD_LEATHER_TIER + mainEnchantment; - case BOW: - return IRON_TIER + mainEnchantment3; + case TURTLE_HELMET: + case WOODEN_SWORD: + case WOODEN_AXE: + case GOLDEN_SWORD: + case GOLDEN_AXE: + return GOLD_WOOD_LEATHER_TIER; + case DIAMOND_HOE: + case IRON_HOE: + case STONE_HOE: + case GOLDEN_HOE: + case WOODEN_HOE: + if (!ItemSettingsConfig.isUseHoesAsWeapons()) return 0; + if (material.equals(Material.DIAMOND_HOE)) + return DIAMOND_TIER; + if (material.equals(Material.IRON_HOE)) + return IRON_TIER; + if (material.equals(Material.STONE_HOE)) + return STONE_CHAIN_TIER; + if (material.equals(Material.GOLDEN_HOE) || material.equals(Material.WOODEN_HOE)) + return GOLD_WOOD_LEATHER_TIER; default: + if (!VersionChecker.serverVersionOlderThan(16, 0)) { + if (material.equals(Material.NETHERITE_HELMET) || + material.equals(Material.NETHERITE_CHESTPLATE) || + material.equals(Material.NETHERITE_LEGGINGS) || + material.equals(Material.NETHERITE_BOOTS)) + return CombatSystem.NETHERITE_TIER_LEVEL; + if (material.equals(Material.NETHERITE_SWORD) || + material.equals(Material.NETHERITE_AXE) || + material.equals(Material.NETHERITE_HOE) && ItemSettingsConfig.isUseHoesAsWeapons()) + return CombatSystem.NETHERITE_TIER_LEVEL; + } return 0; } } - private static int findMainEnchantment(HashMap enchantmentMap, Enchantment enchantment) { - - int enchantments = 0; + public static int mainHandCombatParser(ItemStack itemStack) { - if (!enchantmentMap.isEmpty()) - for (Enchantment currentEnchantment : enchantmentMap.keySet()) - if (currentEnchantment.equals(enchantment)) - enchantments += enchantmentMap.get(currentEnchantment); + Material material = itemStack.getType(); - return enchantments; + return parseMainHandMaterials(material, findMainEnchantment(itemStack, Enchantment.DAMAGE_ALL), findMainEnchantment(itemStack, Enchantment.PROTECTION_ENVIRONMENTAL), findMainEnchantment(itemStack, Enchantment.ARROW_DAMAGE)); } - private static int findMainEnchantment(ItemStack itemStack, Enchantment enchantment) { - - int enchantments = 0; - - if (ObfuscatedSignatureLoreData.obfuscatedSignatureDetector(itemStack)) { - String deobfuscatedString = itemStack.getItemMeta().getLore().get(0).replace("§", ""); - if (deobfuscatedString.contains(LoreGenerator.OBFUSCATED_ENCHANTMENTS)) - return findObfuscatedMainEnchantment(deobfuscatedString, enchantment); + private static int parseMainHandMaterials(Material material, int mainEnchantment, int mainEnchantment2, int mainEnchantment3) { + switch (material) { + case DIAMOND_SWORD: + case DIAMOND_AXE: + return DIAMOND_TIER + mainEnchantment; + case TRIDENT: + return CombatSystem.TRIDENT_TIER_LEVEL + mainEnchantment; + case IRON_AXE: + case IRON_SWORD: + return IRON_TIER + mainEnchantment; + case STONE_SWORD: + case STONE_AXE: + return STONE_CHAIN_TIER + mainEnchantment; + case WOODEN_SWORD: + case WOODEN_AXE: + case GOLDEN_SWORD: + case GOLDEN_AXE: + return GOLD_WOOD_LEATHER_TIER + mainEnchantment; + case BOW: + case CROSSBOW: + return IRON_TIER + mainEnchantment3; + case DIAMOND_HOE: + case IRON_HOE: + case STONE_HOE: + case GOLDEN_HOE: + case WOODEN_HOE: + if (!ItemSettingsConfig.isUseHoesAsWeapons()) return 0; + if (material.equals(Material.DIAMOND_HOE)) + return DIAMOND_TIER + mainEnchantment; + if (material.equals(Material.IRON_HOE)) + return IRON_TIER + mainEnchantment; + if (material.equals(Material.STONE_HOE)) + return STONE_CHAIN_TIER + mainEnchantment; + if (material.equals(Material.GOLDEN_HOE) || material.equals(Material.WOODEN_HOE)) + return GOLD_WOOD_LEATHER_TIER + mainEnchantment; + default: + if (!VersionChecker.serverVersionOlderThan(16, 0)) + if (material.equals(Material.NETHERITE_SWORD) || + material.equals(Material.NETHERITE_AXE) || + material.equals(Material.NETHERITE_HOE) && ItemSettingsConfig.isUseHoesAsWeapons()) + return CombatSystem.NETHERITE_TIER_LEVEL + mainEnchantment; + return 0; } + } - if (!itemStack.getEnchantments().isEmpty()) - for (Map.Entry entry : itemStack.getEnchantments().entrySet()) - if (entry.getKey().equals(enchantment)) - enchantments += entry.getValue(); - - return enchantments; - + public static boolean isWeaponMaterial(ItemStack itemStack) { + if (itemStack == null) return false; + Material material = itemStack.getType(); + switch (material) { + case DIAMOND_SWORD: + case DIAMOND_AXE: + case TRIDENT: + case IRON_AXE: + case IRON_SWORD: + case STONE_SWORD: + case STONE_AXE: + case WOODEN_SWORD: + case WOODEN_AXE: + case GOLDEN_SWORD: + case GOLDEN_AXE: + case BOW: + case CROSSBOW: + return true; + case DIAMOND_HOE: + case IRON_HOE: + case STONE_HOE: + case GOLDEN_HOE: + case WOODEN_HOE: + if (!ItemSettingsConfig.isUseHoesAsWeapons()) return false; + return true; + default: + if (!VersionChecker.serverVersionOlderThan(16, 0)) + if (material.equals(Material.NETHERITE_SWORD) || + material.equals(Material.NETHERITE_AXE) || + material.equals(Material.NETHERITE_HOE) && ItemSettingsConfig.isUseHoesAsWeapons()) + return true; + return false; + } } - private static int findObfuscatedMainEnchantment(String deobfuscatedLore, Enchantment enchantment) { - for (String string : deobfuscatedLore.split(",")) - if (string.contains(enchantment.getName())) - return Integer.parseInt(string.split(":")[1]); + private static int findMainEnchantment(ItemStack itemStack, Enchantment enchantment) { + if (itemStack == null) + return 0; + int enchantLevel = ItemTagger.getEnchantment(itemStack.getItemMeta(), enchantment.getKey()); + if (enchantLevel == 0) + if (itemStack.hasItemMeta() && itemStack.getItemMeta().hasEnchant(enchantment)) + enchantLevel = itemStack.getItemMeta().getEnchantLevel(enchantment); + return enchantLevel; + } - return 0; + /** + * Returns enchantment type that an item usses for the main enchantment. Returns null if there isn't one. Only takes + * combat items into account. + * + * @param material + * @return + */ + public static Enchantment getMainCombatEnchantment(Material material) { + switch (material) { + case DIAMOND_HOE: + case GOLDEN_HOE: + case IRON_HOE: + case STONE_HOE: + case WOODEN_HOE: + if (!ItemSettingsConfig.isUseHoesAsWeapons()) return null; + case TRIDENT: + case DIAMOND_SWORD: + case GOLDEN_SWORD: + case IRON_SWORD: + case STONE_SWORD: + case WOODEN_SWORD: + case DIAMOND_AXE: + case GOLDEN_AXE: + case IRON_AXE: + case STONE_AXE: + case WOODEN_AXE: + return Enchantment.DAMAGE_ALL; + case BOW: + case CROSSBOW: + return Enchantment.ARROW_DAMAGE; + case CHAINMAIL_HELMET: + case DIAMOND_HELMET: + case GOLDEN_HELMET: + case IRON_HELMET: + case LEATHER_HELMET: + case TURTLE_HELMET: + case CHAINMAIL_CHESTPLATE: + case DIAMOND_CHESTPLATE: + case GOLDEN_CHESTPLATE: + case IRON_CHESTPLATE: + case LEATHER_CHESTPLATE: + case CHAINMAIL_LEGGINGS: + case DIAMOND_LEGGINGS: + case GOLDEN_LEGGINGS: + case IRON_LEGGINGS: + case LEATHER_LEGGINGS: + case CHAINMAIL_BOOTS: + case DIAMOND_BOOTS: + case GOLDEN_BOOTS: + case IRON_BOOTS: + case LEATHER_BOOTS: + return Enchantment.PROTECTION_ENVIRONMENTAL; + default: + if (!VersionChecker.serverVersionOlderThan(16, 0)) { + if (material.equals(Material.NETHERITE_SWORD) || + material.equals(Material.NETHERITE_AXE) || + material.equals(Material.NETHERITE_HOE) && ItemSettingsConfig.isUseHoesAsWeapons()) + return Enchantment.DAMAGE_ALL; + + if (material.equals(Material.NETHERITE_HELMET) || + material.equals(Material.NETHERITE_CHESTPLATE) || + material.equals(Material.NETHERITE_LEGGINGS) || + material.equals(Material.NETHERITE_BOOTS)) + return Enchantment.PROTECTION_ENVIRONMENTAL; + } + return null; + } } } diff --git a/src/main/java/com/magmaguy/elitemobs/items/ItemWorthCalculator.java b/src/main/java/com/magmaguy/elitemobs/items/ItemWorthCalculator.java index 62113c9c1..ae4904a4b 100644 --- a/src/main/java/com/magmaguy/elitemobs/items/ItemWorthCalculator.java +++ b/src/main/java/com/magmaguy/elitemobs/items/ItemWorthCalculator.java @@ -1,411 +1,79 @@ -/* - * 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 . - */ - package com.magmaguy.elitemobs.items; -import com.magmaguy.elitemobs.config.ConfigValues; +import com.magmaguy.elitemobs.adventurersguild.GuildRank; import com.magmaguy.elitemobs.config.EconomySettingsConfig; -import com.magmaguy.elitemobs.items.itemconstructor.LoreGenerator; +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfig; +import com.magmaguy.elitemobs.items.customenchantments.CustomEnchantment; +import com.magmaguy.elitemobs.items.potioneffects.ElitePotionEffect; +import com.magmaguy.elitemobs.items.potioneffects.ElitePotionEffectContainer; +import com.magmaguy.elitemobs.utils.Round; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import static com.magmaguy.elitemobs.config.EconomySettingsConfig.*; +import org.bukkit.inventory.meta.ItemMeta; public class ItemWorthCalculator { - public static double determineItemWorth(ItemStack itemStack) { - - double itemWorth = 1 + Math.round((itemTypeWorth(itemStack.getType()) + getAllEnchantmentsValue(itemStack) + potionEffectValue(itemStack)) * 100.0) / 100.0; - - return itemWorth; - - } - - public static double determineItemWorth(Material material, HashMap enchantmentsMap) { - - double itemWorth = 1 + Math.round((itemTypeWorth(material) + getAllEnchantmentsValue(enchantmentsMap)) * 100.0) / 100.0; + public static double determineItemWorth(ItemStack itemStack, Player player) { - return itemWorth; + if (itemStack == null || itemStack.getItemMeta() == null || itemStack.getType().equals(Material.AIR)) return 0; - } - - public static double determineItemWorth(Material material, HashMap enchantmentsMap, List potionsMap) { + //Check if value's already been written into the item. If it hasn't, the value will be -1 + double value = ItemTagger.getItemValue(itemStack); + if (value != -1) return value; - double itemWorth = 1 + Math.round((itemTypeWorth(material) + getAllEnchantmentsValue(enchantmentsMap) + potionEffectValue(potionsMap)) * 100.0) / 100.0; + double prestigeMultiplier; + if (player == null) + prestigeMultiplier = 1; + else + prestigeMultiplier = GuildRank.currencyBonusMultiplier(GuildRank.getGuildPrestigeRank(player)); - return itemWorth; + return 1 + Round.twoDecimalPlaces( + (EconomySettingsConfig.getMaterialWorth(itemStack.getType()) + + getAllEnchantmentValues(itemStack) + + getAllPotionEffectValues(itemStack.getItemMeta())) * + prestigeMultiplier); } - public static double determineResaleWorth(ItemStack itemStack) { - - double resaleWorth = Math.round((determineItemWorth(itemStack) * (ConfigValues.economyConfig.getDouble(EconomySettingsConfig.RESALE_VALUE) / 100)) * 100.0) / 100.0; - - return resaleWorth; - - } - - private static double configGetter(String string) { - - return ConfigValues.economyConfig.getDouble(string); - - } - - public static double itemTypeWorth(Material material) { - - switch (material) { - - case DIAMOND_AXE: - return configGetter(DIAMOND_AXE); - case DIAMOND_BARDING: - return configGetter(DIAMOND_BARDING); - case DIAMOND_BLOCK: - return configGetter(DIAMOND_BLOCK); - case DIAMOND_BOOTS: - return configGetter(DIAMOND_BOOTS); - case DIAMOND_CHESTPLATE: - return configGetter(DIAMOND_CHESTPLATE); - case DIAMOND_HELMET: - return configGetter(DIAMOND_HELMET); - case DIAMOND_HOE: - return configGetter(DIAMOND_HOE); - case DIAMOND_LEGGINGS: - return configGetter(DIAMOND_LEGGINGS); - case DIAMOND_ORE: - return configGetter(DIAMOND_ORE); - case DIAMOND_PICKAXE: - return configGetter(DIAMOND_PICKAXE); - case DIAMOND_SPADE: - return configGetter(DIAMOND_SPADE); - case DIAMOND_SWORD: - return configGetter(DIAMOND_SWORD); - case IRON_AXE: - return configGetter(IRON_AXE); - case IRON_BARDING: - return configGetter(IRON_BARDING); - case IRON_BLOCK: - return configGetter(IRON_BLOCK); - case IRON_BOOTS: - return configGetter(IRON_BOOTS); - case IRON_CHESTPLATE: - return configGetter(IRON_CHESTPLATE); - case IRON_HELMET: - return configGetter(IRON_HELMET); - case IRON_HOE: - return configGetter(IRON_HOE); - case IRON_INGOT: - return configGetter(IRON_INGOT); - case IRON_LEGGINGS: - return configGetter(IRON_LEGGINGS); - case IRON_NUGGET: - return configGetter(IRON_NUGGET); - case IRON_ORE: - return configGetter(IRON_ORE); - case IRON_PICKAXE: - return configGetter(IRON_PICKAXE); - case IRON_SPADE: - return configGetter(IRON_SPADE); - case IRON_SWORD: - return configGetter(IRON_SWORD); - case BOW: - return configGetter(BOW); - case SHIELD: - return configGetter(SHIELD); - case CHAINMAIL_BOOTS: - return configGetter(CHAINMAIL_BOOTS); - case CHAINMAIL_CHESTPLATE: - return configGetter(CHAINMAIL_CHESTPLATE); - case CHAINMAIL_HELMET: - return configGetter(CHAINMAIL_HELMET); - case CHAINMAIL_LEGGINGS: - return configGetter(CHAINMAIL_LEGGINGS); - case STONE_SWORD: - return configGetter(STONE_SWORD); - case STONE_SPADE: - return configGetter(STONE_SPADE); - case STONE_AXE: - return configGetter(STONE_AXE); - case STONE_PICKAXE: - return configGetter(STONE_PICKAXE); - case GOLD_AXE: - return configGetter(GOLD_AXE); - case GOLD_BARDING: - return configGetter(GOLD_BARDING); - case GOLD_BLOCK: - return configGetter(GOLD_BLOCK); - case GOLD_BOOTS: - return configGetter(GOLD_BOOTS); - case GOLD_CHESTPLATE: - return configGetter(GOLD_CHESTPLATE); - case GOLD_HELMET: - return configGetter(GOLD_HELMET); - case GOLD_HOE: - return configGetter(GOLD_HOE); - case GOLD_INGOT: - return configGetter(GOLD_INGOT); - case GOLD_LEGGINGS: - return configGetter(GOLD_LEGGINGS); - case GOLD_NUGGET: - return configGetter(GOLD_NUGGET); - case GOLD_ORE: - return configGetter(GOLD_ORE); - case GOLD_PICKAXE: - return configGetter(GOLD_PICKAXE); - case GOLD_SPADE: - return configGetter(GOLD_SPADE); - case GOLD_SWORD: - return configGetter(GOLD_SWORD); - case GOLDEN_APPLE: - return configGetter(GOLDEN_APPLE); - case GOLDEN_CARROT: - return configGetter(GOLDEN_CARROT); - case LEATHER_BOOTS: - return configGetter(LEATHER_BOOTS); - case LEATHER_CHESTPLATE: - return configGetter(LEATHER_CHESTPLATE); - case LEATHER_HELMET: - return configGetter(LEATHER_HELMET); - case LEATHER_LEGGINGS: - return configGetter(LEATHER_LEGGINGS); - case WOOD_SWORD: - return configGetter(WOOD_SWORD); - case WOOD_AXE: - return configGetter(WOOD_AXE); - case WOOD_PICKAXE: - return configGetter(WOOD_PICKAXE); - case WOOD_HOE: - return configGetter(WOOD_HOE); - default: - return configGetter(OTHER); - - } - - } - - private static double getAllEnchantmentsValue(ItemStack itemStack) { - - double enchantmentsValue = 0; - - if (!itemStack.getEnchantments().isEmpty()) { - - for (Map.Entry entry : itemStack.getEnchantments().entrySet()) { - - enchantmentsValue += enchantmentWorthGetter(entry.getKey()) * entry.getValue(); - - } - - } - - return enchantmentsValue; - + public static double writeItemWorth(ItemStack itemStack, Player player) { + return determineItemWorth(itemStack, player); } - private static double getAllEnchantmentsValue(HashMap enchantmentsMap) { - - double enchantmentsValue = 0; - - if (!enchantmentsMap.isEmpty()) { - - for (Enchantment enchantment : enchantmentsMap.keySet()) { - - enchantmentsValue += enchantmentWorthGetter(enchantment) * enchantmentsMap.get(enchantment); - - } - - } - - return enchantmentsValue; - + public static double determineResaleWorth(ItemStack itemStack, Player player) { + double value = ItemTagger.getItemValue(itemStack); + value = value == -1 ? Round.twoDecimalPlaces(determineItemWorth(itemStack, player) * (EconomySettingsConfig.getResaleValue() / 100)) : + Round.twoDecimalPlaces(value * (EconomySettingsConfig.getResaleValue() / 100)); + return value; } - public static double enchantmentWorthGetter(Enchantment enchantment) { - - if (enchantment == null) return 0; - - String enchantmentName = enchantment.getName(); - - switch (enchantmentName) { - - case "ARROW_DAMAGE": - return configGetter(ARROW_DAMAGE); - case "ARROW_FIRE": - return configGetter(ARROW_FIRE); - case "ARROW_INFINITE": - return configGetter(ARROW_INFINITE); - case "ARROW_KNOCKBACK": - return configGetter(ARROW_KNOCKBACK); - case "BINDING_CURSE": - return configGetter(BINDING_CURSE); - case "DAMAGE_ALL": - return configGetter(DAMAGE_ALL); - case "DAMAGE_ARTHROPODS": - return configGetter(DAMAGE_ARTHROPODS); - case "DAMAGE_UNDEAD": - return configGetter(DAMAGE_UNDEAD); - case "DEPTH_STRIDER": - return configGetter(DEPTH_STRIDER); - case "DIG_SPEED": - return configGetter(DIG_SPEED); - case "DURABILITY": - return configGetter(DURABILITY); - case "FIRE_ASPECT": - return configGetter(FIRE_ASPECT); - case "FROST_WALKER": - return configGetter(FROST_WALKER); - case "KNOCKBACK": - return configGetter(KNOCKBACK); - case "LOOT_BONUS_BLOCKS": - return configGetter(LOOT_BONUS_BLOCKS); - case "LOOT_BONUS_MOBS": - return configGetter(LOOT_BONUS_MOBS); - case "LUCK": - return configGetter(LUCK_ENCHANTMENT); - case "LURE": - return configGetter(LURE); - case "MENDING": - return configGetter(MENDING); - case "OXYGEN": - return configGetter(OXYGEN); - case "PROTECTION_ENVIRONMENTAL": - return configGetter(PROTECTION_ENVIRONMENTAL); - case "PROTECTION_EXPLOSIONS": - return configGetter(PROTECTION_EXPLOSIONS); - case "PROTECTION_FALL": - return configGetter(PROTECTION_FALL); - case "PROTECTION_PROJECTILE": - return configGetter(PROTECTION_PROJECTILE); - case "PROTECTION_FIRE": - return configGetter(PROTECTION_FIRE); - case "SILK_TOUCH": - return configGetter(SILK_TOUCH); - case "SWEEPING_EDGE": - return configGetter(SWEEPING_EDGE); - case "THORNS": - return configGetter(THORNS); - case "VANISHING_CURSE": - return configGetter(VANISHING_CURSE); - case "WATER_WORKER": - return configGetter(WATER_WORKER); - default: - return 0; + private static double getAllEnchantmentValues(ItemStack itemStack) { + double value = 0; + for (Enchantment enchantment : itemStack.getEnchantments().keySet()) { + if (EliteEnchantments.isPotentialEliteEnchantment(enchantment)) { + if (ItemTagger.getEnchantment(itemStack.getItemMeta(), enchantment.getKey()) != 0) { + value += EnchantmentsConfig.getEnchantment(enchantment).getValue() * ItemTagger.getEnchantment(itemStack.getItemMeta(), enchantment.getKey()); + continue; + } + } else + value += EnchantmentsConfig.getEnchantment(enchantment).getValue() * itemStack.getEnchantments().get(enchantment); } - - } - - private static double potionEffectValue(ItemStack itemStack) { - - double potionEffectValue = 0; - if (!itemStack.hasItemMeta() && itemStack.getItemMeta().hasLore()) return potionEffectValue; - - String potionEffectLoreLine = itemStack.getItemMeta().getLore().get(0).replace("§", ""); - if (!potionEffectLoreLine.contains(LoreGenerator.OBFUSCATED_POTIONS)) return potionEffectValue; - - for (String substring : potionEffectLoreLine.split(",")) { - - List parsedSubstring = Arrays.asList(substring.split(":")); - if (parsedSubstring.size() > 1) { - potionEffectValue += getPotionEffectValue(parsedSubstring.get(0)) * (Integer.valueOf(parsedSubstring.get(1)) + 1); - } - + for (CustomEnchantment customEnchantment : CustomEnchantment.getCustomEnchantments()) { + int enchantmentLevel = ItemTagger.getEnchantment(itemStack.getItemMeta(), customEnchantment.key); + if (enchantmentLevel > 0) + value += customEnchantment.getEnchantmentsConfigFields().getValue() * ItemTagger.getEnchantment(itemStack.getItemMeta(), customEnchantment.key); } - - return potionEffectValue; - + return value; } - private static double potionEffectValue(List potionString) { - - double potionEffectValue = 0; - - if (potionString == null || potionString.isEmpty()) return potionEffectValue; - - for (String string : potionString) - potionEffectValue += getPotionEffectValue(string.split(",")[0]) * (Integer.parseInt(string.split(",")[1]) + 1); - - return potionEffectValue; - - } - - private static double getPotionEffectValue(String string) { - - switch (string) { - - case "ABSORPTION": - return configGetter(ABSORPTION); - case "BLINDNESS": - return configGetter(BLINDNESS); - case "CONFUSION": - return configGetter(CONFUSION); - case "DAMAGE_RESISTANCE": - return configGetter(DAMAGE_RESISTANCE); - case "FAST_DIGGING": - return configGetter(FAST_DIGGING); - case "FIRE_RESISTANCE": - return configGetter(FIRE_RESISTANCE); - case "GLOWING": - return configGetter(GLOWING); - case "HARM": - return configGetter(HARM); - case "HEAL": - return configGetter(HEAL); - case "HEALTH_BOOST": - return configGetter(HEALTH_BOOST); - case "HUNGER": - return configGetter(HUNGER); - case "INCREASE_DAMAGE": - return configGetter(INCREASE_DAMAGE); - case "INVISIBILITY": - return configGetter(INVISIBILITY); - case "JUMP": - return configGetter(JUMP); - case "LEVITATION": - return configGetter(LEVITATION); - case "LUCK": - return configGetter(LUCK_POTION); - case "NIGHT_VISION": - return configGetter(NIGHT_VISION); - case "POISON": - return configGetter(POISON); - case "REGENERATION": - return configGetter(REGENERATION); - case "SATURATION": - return configGetter(SATURATION); - case "SLOW": - return configGetter(SLOW); - case "SLOW_DIGGING": - return configGetter(SLOW_DIGGING); - case "SPEED": - return configGetter(SPEED); - case "UNLUCK": - return configGetter(UNLUCK); - case "WATER_BREATHING": - return configGetter(WATER_BREATHING); - case "WEAKNESS": - return configGetter(WEAKNESS); - case "WITHER": - return configGetter(WITHER); - default: - return 0; - } - + private static double getAllPotionEffectValues(ItemMeta itemMeta) { + double value = 0; + for (ElitePotionEffect elitePotionEffect : ElitePotionEffectContainer.getElitePotionEffects(itemMeta, ElitePotionEffect.ApplicationMethod.CONTINUOUS)) + value += (elitePotionEffect.getValue() * (elitePotionEffect.getPotionEffect().getAmplifier() + 1)); + for (ElitePotionEffect elitePotionEffect : ElitePotionEffectContainer.getElitePotionEffects(itemMeta, ElitePotionEffect.ApplicationMethod.ONHIT)) + value += (elitePotionEffect.getValue() * (elitePotionEffect.getPotionEffect().getAmplifier() + 1)); + return value; } } diff --git a/src/main/java/com/magmaguy/elitemobs/items/LootTables.java b/src/main/java/com/magmaguy/elitemobs/items/LootTables.java index 10c6b0468..bd695f945 100644 --- a/src/main/java/com/magmaguy/elitemobs/items/LootTables.java +++ b/src/main/java/com/magmaguy/elitemobs/items/LootTables.java @@ -1,139 +1,216 @@ package com.magmaguy.elitemobs.items; -import com.magmaguy.elitemobs.EntityTracker; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.ItemsDropSettingsConfig; -import com.magmaguy.elitemobs.config.ItemsProceduralSettingsConfig; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.adventurersguild.GuildRank; +import com.magmaguy.elitemobs.api.EliteMobDeathEvent; +import com.magmaguy.elitemobs.config.AdventurersGuildConfig; +import com.magmaguy.elitemobs.config.ItemSettingsConfig; +import com.magmaguy.elitemobs.config.ProceduralItemGenerationSettingsConfig; +import com.magmaguy.elitemobs.items.customenchantments.SoulbindEnchantment; +import com.magmaguy.elitemobs.items.customitems.CustomItem; import com.magmaguy.elitemobs.items.itemconstructor.ItemConstructor; -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.mobconstructor.custombosses.RegionalBossEntity; +import com.magmaguy.elitemobs.playerdata.database.PlayerData; +import com.magmaguy.elitemobs.utils.InfoMessage; +import com.magmaguy.elitemobs.utils.WarningMessage; +import net.md_5.bungee.api.ChatMessageType; +import net.md_5.bungee.api.chat.TextComponent; import org.bukkit.Location; import org.bukkit.entity.Item; +import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.inventory.ItemStack; +import org.bukkit.scheduler.BukkitRunnable; import java.util.HashMap; import java.util.concurrent.ThreadLocalRandom; -import static com.magmaguy.elitemobs.utils.WeightedProbablity.pickWeighedProbability; +import static com.magmaguy.elitemobs.utils.WeightedProbability.pickWeighedProbability; /** * Created by MagmaGuy on 04/06/2017. */ public class LootTables implements Listener { - @EventHandler(priority = EventPriority.LOWEST) - public void onDeath(EntityDeathEvent event) { - - if (event.getEntity() == null) return; - - EliteMobEntity eliteMobEntity = EntityTracker.getEliteMobEntity(event.getEntity()); - if (eliteMobEntity == null) return; - - if (!eliteMobEntity.isNaturalEntity()) return; - if (!eliteMobEntity.getHasNormalLoot()) return; - - if (eliteMobEntity.getLevel() < 2) return; - - Item item = generateLoot(eliteMobEntity); + private static boolean proceduralItemsOn; + private static boolean customItemsOn; + private static boolean weighedItemsExist; + private static boolean fixedItemsExist; + private static boolean limitedItemsExist; + private static boolean scalableItemsExist; + + public static void generatePlayerLoot(EliteEntity eliteEntity) { + if (eliteEntity.isTriggeredAntiExploit()) return; + for (Player player : eliteEntity.getDamagers().keySet()) { + + if (player.hasMetadata("NPC") || !PlayerData.isInMemory(player.getUniqueId())) continue; + + if (eliteEntity.getDamagers().get(player) / eliteEntity.getMaxHealth() < 0.1) continue; + + if (eliteEntity.getPower("bonus_coins.yml") == null) + new ItemLootShower(eliteEntity.getLevel(), eliteEntity.getUnsyncedLivingEntity().getLocation(), player); + + if (!(eliteEntity.isRandomLoot())) continue; + + if (AdventurersGuildConfig.isGuildLootLimiter()) { + double itemTier = setItemTier(eliteEntity.getLevel()); + if (itemTier > GuildRank.getActiveGuildRank(player) * 10) { + itemTier = GuildRank.getActiveGuildRank(player) * 10D; + new BukkitRunnable() { + @Override + public void run() { + player.spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(AdventurersGuildConfig.getLootLimiterMessage())); + } + }.runTaskLater(MetadataHandler.PLUGIN, 20 * 10L); + } + generateLoot((int) Math.floor(itemTier), eliteEntity, player); + } else generateLoot(eliteEntity, player); + } + } - if (item == null) return; - - RareDropEffect.runEffect(item); + public static void initialize() { + proceduralItemsOn = ProceduralItemGenerationSettingsConfig.isDoProceduralItemDrops(); + customItemsOn = ItemSettingsConfig.isDoEliteMobsLoot() && !CustomItem.getCustomItemStackList().isEmpty(); + weighedItemsExist = CustomItem.getWeighedFixedItems() != null && !CustomItem.getWeighedFixedItems().isEmpty(); + fixedItemsExist = CustomItem.getFixedItems() != null && !CustomItem.getFixedItems().isEmpty(); + limitedItemsExist = CustomItem.getLimitedItem() != null && !CustomItem.getLimitedItem().isEmpty(); + scalableItemsExist = CustomItem.getScalableItems() != null && !CustomItem.getScalableItems().isEmpty(); } - private static boolean proceduralItemsOn = ConfigValues.itemsProceduralSettingsConfig.getBoolean(ItemsProceduralSettingsConfig.DROP_ITEMS_ON_DEATH); - private static boolean customItemsOn = ConfigValues.itemsDropSettingsConfig.getBoolean(ItemsDropSettingsConfig.DROP_CUSTOM_ITEMS) && - !CustomItemConstructor.customItemList.isEmpty(); - private static boolean staticWeightCustomItemsExist = CustomItemConstructor.staticCustomItemHashMap.size() > 0; - private static boolean dynamicWeightCustomItemsExist = CustomItemConstructor.dynamicRankedItemStacks.size() > 0; - - public static Item generateLoot(EliteMobEntity eliteMobEntity) { + private static ItemStack generateLoot(EliteEntity eliteEntity, Player player) { + int mobTier = (int) MobTierCalculator.findMobTier(eliteEntity); - int mobTier = (int) MobTierFinder.findMobTier(eliteMobEntity); /* Add some wiggle room to avoid making obtaining loot too linear */ int itemTier = (int) setItemTier(mobTier); - /* - Handle the odds of an item dropping - */ - double baseChance = ConfigValues.itemsDropSettingsConfig.getDouble(ItemsDropSettingsConfig.ELITE_ITEM_FLAT_DROP_RATE) / 100; - double dropChanceBonus = ConfigValues.itemsDropSettingsConfig.getDouble(ItemsDropSettingsConfig.ELITE_ITEM_TIER_DROP_RATE) / 100 * itemTier; + return generateLoot(itemTier, eliteEntity, player); - if (ThreadLocalRandom.current().nextDouble() > baseChance + dropChanceBonus) - return null; + } - /* - First split: Check if the loot should be procedural or based on unique/custom items - This makes more sense because the ratio between custom/unique items and procedural items is quite drastic - */ - if (!proceduralItemsOn && !customItemsOn) return null; - if (proceduralItemsOn && customItemsOn) { + public static ItemStack generateLoot(int itemTier, EliteEntity eliteEntity, Player player) { - HashMap weightedConfigValues = new HashMap<>(); - weightedConfigValues.put(ItemsDropSettingsConfig.PROCEDURAL_ITEM_WEIGHT, ConfigValues.itemsDropSettingsConfig.getDouble(ItemsDropSettingsConfig.PROCEDURAL_ITEM_WEIGHT)); - weightedConfigValues.put(ItemsDropSettingsConfig.CUSTOM_ITEM_WEIGHT, ConfigValues.itemsDropSettingsConfig.getDouble(ItemsDropSettingsConfig.CUSTOM_ITEM_WEIGHT)); + /* + Handle the odds of an item dropping + */ + double baseChance = ItemSettingsConfig.getFlatDropRate(); + if (eliteEntity instanceof RegionalBossEntity) + baseChance = ItemSettingsConfig.getRegionalBossNonUniqueDropRate(); + double dropChanceBonus = ItemSettingsConfig.getTierIncreaseDropRate() * itemTier; - String selectedLootSystem = pickWeighedProbability(weightedConfigValues); + if (ThreadLocalRandom.current().nextDouble() > baseChance + dropChanceBonus) return null; - if (selectedLootSystem.equals(ItemsDropSettingsConfig.PROCEDURAL_ITEM_WEIGHT)) - return dropProcedurallyGeneratedItem(itemTier, eliteMobEntity); + HashMap weightedProbability = new HashMap<>(); + if (proceduralItemsOn) weightedProbability.put("procedural", ItemSettingsConfig.getProceduralItemWeight()); + if (customItemsOn) { + if (weighedItemsExist) weightedProbability.put("weighed", ItemSettingsConfig.getWeighedItemWeight()); + if (fixedItemsExist) if (CustomItem.getFixedItems().containsKey(itemTier)) + weightedProbability.put("fixed", ItemSettingsConfig.getFixedItemWeight()); + if (limitedItemsExist) weightedProbability.put("limited", ItemSettingsConfig.getLimitedItemWeight()); + if (scalableItemsExist) weightedProbability.put("scalable", ItemSettingsConfig.getScalableItemWeight()); + } + String selectedLootSystem = pickWeighedProbability(weightedProbability); + if (selectedLootSystem == null) { + new InfoMessage("Your EliteMobs loot configuration resulted in no loot getting dropped. This is not a bug. " + "If you want! players to be able to progress at all in the EliteMobs plugin, review your configuration settings."); + return null; } + switch (selectedLootSystem) { + case "procedural": + return dropProcedurallyGeneratedItem(itemTier, eliteEntity, player); + case "weighed": + return dropWeighedFixedItem(eliteEntity, player); + case "fixed": + return dropFixedItem(eliteEntity, itemTier, player); + case "limited": + return dropLimitedItem(eliteEntity, itemTier, player); + case "scalable": + return dropScalableItem(eliteEntity, itemTier, player); + } - if (proceduralItemsOn && !customItemsOn) - return dropProcedurallyGeneratedItem(itemTier, eliteMobEntity); + return null; + } + /** + * Used for "fake" drops. Currently this means it's used by the SimLootHandler, reason will default to shop. + * + * @param itemTier + * @param location + * @param player + * @return + */ + public static ItemStack generateLoot(int itemTier, Location location, Player player) { - /* - First split is done, moving on to second split - Split between static and dynamic weight loot + /* + Handle the odds of an item dropping */ - if (staticWeightCustomItemsExist && dynamicWeightCustomItemsExist) { - - HashMap weightedConfigValues = new HashMap<>(); - weightedConfigValues.put(ItemsDropSettingsConfig.CUSTOM_DYNAMIC_ITEM_WEIGHT, ConfigValues.itemsDropSettingsConfig.getDouble(ItemsDropSettingsConfig.CUSTOM_DYNAMIC_ITEM_WEIGHT)); - weightedConfigValues.put(ItemsDropSettingsConfig.CUSTOM_STATIC_ITEM_WEIGHT, ConfigValues.itemsDropSettingsConfig.getDouble(ItemsDropSettingsConfig.CUSTOM_STATIC_ITEM_WEIGHT)); + double baseChance = ItemSettingsConfig.getFlatDropRate(); + double dropChanceBonus = ItemSettingsConfig.getTierIncreaseDropRate() * itemTier; - String selectedLootSystem = pickWeighedProbability(weightedConfigValues); + if (ThreadLocalRandom.current().nextDouble() > baseChance + dropChanceBonus) return null; - if (selectedLootSystem.equals(ItemsDropSettingsConfig.CUSTOM_STATIC_ITEM_WEIGHT)) { - return dropCustomStaticLoot(eliteMobEntity.getLivingEntity().getLocation()); + HashMap weightedProbability = new HashMap<>(); + if (proceduralItemsOn) weightedProbability.put("procedural", ItemSettingsConfig.getProceduralItemWeight()); + if (customItemsOn) { + if (weighedItemsExist) weightedProbability.put("weighed", ItemSettingsConfig.getWeighedItemWeight()); + if (fixedItemsExist) if (CustomItem.getFixedItems().containsKey(itemTier)) + weightedProbability.put("fixed", ItemSettingsConfig.getFixedItemWeight()); + if (limitedItemsExist) weightedProbability.put("limited", ItemSettingsConfig.getLimitedItemWeight()); + if (scalableItemsExist) weightedProbability.put("scalable", ItemSettingsConfig.getScalableItemWeight()); + } - } + String selectedLootSystem = pickWeighedProbability(weightedProbability); + switch (selectedLootSystem) { + case "procedural": + return dropProcedurallyGeneratedItem(itemTier, location, player); + case "weighed": + return dropWeighedFixedItem(location, player); + case "fixed": + return dropFixedItem(location, itemTier, player); + case "limited": + return dropLimitedItem(location, itemTier, player); + case "scalable": + return dropScalableItem(location, itemTier, player); } - /* - Second split is done, moving on to third split - At this point only scalability type is left, can be either static, limited or dynamic - */ + return null; + + } + + public static ItemStack generateItemStack(int itemTier, Player player, EliteEntity eliteEntity) { + HashMap weightedProbability = new HashMap<>(); - if (ScalableItemConstructor.dynamicallyScalableItems.size() > 0) - weightedProbability.put("dynamic", 33.0); - if (ScalableItemConstructor.limitedScalableItems.size() > 0) - weightedProbability.put("limited", 33.0); - if (ScalableItemConstructor.staticItems.size() > 0) - weightedProbability.put("static", 33.0); + if (proceduralItemsOn) weightedProbability.put("procedural", ItemSettingsConfig.getProceduralItemWeight()); + if (customItemsOn) { + if (weighedItemsExist) weightedProbability.put("weighed", ItemSettingsConfig.getWeighedItemWeight()); + if (fixedItemsExist) if (CustomItem.getFixedItems().containsKey(itemTier)) + weightedProbability.put("fixed", ItemSettingsConfig.getFixedItemWeight()); + if (limitedItemsExist) weightedProbability.put("limited", ItemSettingsConfig.getLimitedItemWeight()); + if (scalableItemsExist) weightedProbability.put("scalable", ItemSettingsConfig.getScalableItemWeight()); + } String selectedLootSystem = pickWeighedProbability(weightedProbability); switch (selectedLootSystem) { - case "dynamic": - return dropDynamicallyScalingItem(eliteMobEntity, itemTier); + case "procedural": + return generateProcedurallyGeneratedItem(itemTier, player, eliteEntity); + case "weighed": + return generateWeighedFixedItemStack(player); + case "fixed": + return generateFixedItem(itemTier, player, eliteEntity); case "limited": - return dropLimitedScalingItem(eliteMobEntity, itemTier); - case "static": - return dropStaticScalingItem(eliteMobEntity, itemTier); + return generateLimitedItem(itemTier, player, eliteEntity); + case "scalable": + return generateScalableItem(itemTier, player, eliteEntity); } return null; @@ -142,10 +219,9 @@ public static Item generateLoot(EliteMobEntity eliteMobEntity) { public static double setItemTier(int mobTier) { - double chanceToUpgradeTier = 10 / (double) mobTier * ConfigValues.itemsDropSettingsConfig.getDouble(ItemsDropSettingsConfig.MAXIMUM_LOOT_TIER); + double chanceToUpgradeTier = 10 / (double) mobTier * ItemSettingsConfig.getMaximumLootTier(); - if (ThreadLocalRandom.current().nextDouble() * 100 < chanceToUpgradeTier) - return mobTier + 1; + if (ThreadLocalRandom.current().nextDouble() * 100 < chanceToUpgradeTier) return mobTier + 1D; double diceRoll = ThreadLocalRandom.current().nextDouble(); @@ -156,10 +232,8 @@ public static double setItemTier(int mobTier) { 50% of the time, give an item better than what the player is wearing If you're wondering why this isn't configurable, wonder instead why no one has noticed it isn't before you reading this */ - if (diceRoll < 0.10) - mobTier -= 2; - else if (diceRoll < 0.50) - mobTier -= 1; + if (diceRoll < 0.10) mobTier -= 2; + else if (diceRoll < 0.50) mobTier -= 1; if (mobTier < 0) mobTier = 0; @@ -167,61 +241,136 @@ else if (diceRoll < 0.50) } - private static Item dropCustomStaticLoot(Location location) { + public static ItemStack dropWeighedFixedItem(EliteEntity eliteEntity, Player player) { + ItemStack itemStack = generateWeighedFixedItemStack(player); + if (ItemSettingsConfig.isPutLootDirectlyIntoPlayerInventory()) player.getInventory().addItem(itemStack); + else processPhysicalItem(eliteEntity.getLocation(), itemStack, player); + return itemStack; + } - double totalWeight = 0; - for (ItemStack itemStack : CustomItemConstructor.staticCustomItemHashMap.keySet()) - totalWeight += CustomItemConstructor.staticCustomItemHashMap.get(itemStack); + public static ItemStack dropWeighedFixedItem(Location location, Player player) { + ItemStack itemStack = generateWeighedFixedItemStack(player); + if (ItemSettingsConfig.isPutLootDirectlyIntoPlayerInventory()) player.getInventory().addItem(itemStack); + else processPhysicalItem(location, itemStack, player); + return itemStack; + } + private static ItemStack generateWeighedFixedItemStack(Player player) { + double totalWeight = 0; + + for (ItemStack itemStack : CustomItem.getWeighedFixedItems().keySet()) { + Double shouldntBeNull = CustomItem.getWeighedFixedItems().get(itemStack); + if (shouldntBeNull != null) totalWeight += CustomItem.getWeighedFixedItems().get(itemStack); + else new WarningMessage("Item " + itemStack.getItemMeta().getDisplayName() + " reported a null weight!"); + } ItemStack generatedItemStack = null; double random = Math.random() * totalWeight; - for (ItemStack itemStack : CustomItemConstructor.staticCustomItemHashMap.keySet()) { - - random -= CustomItemConstructor.staticCustomItemHashMap.get(itemStack); - + for (ItemStack itemStack : CustomItem.getWeighedFixedItems().keySet()) { + random -= CustomItem.getWeighedFixedItems().get(itemStack); if (random <= 0) { - - generatedItemStack = itemStack; + generatedItemStack = itemStack.clone(); break; - } - } - return location.getWorld().dropItem(location, generatedItemStack); + SoulbindEnchantment.addEnchantment(generatedItemStack, player); + return generatedItemStack; + } + + private static ItemStack dropProcedurallyGeneratedItem(int tierLevel, EliteEntity eliteEntity, Player player) { + ItemStack itemStack = generateProcedurallyGeneratedItem(tierLevel, player, eliteEntity); + if (ItemSettingsConfig.isPutLootDirectlyIntoPlayerInventory()) player.getInventory().addItem(itemStack); + else processPhysicalItem(eliteEntity.getLocation(), itemStack, player); + return itemStack; + } + + private static ItemStack dropProcedurallyGeneratedItem(int tierLevel, Location location, Player player) { + ItemStack itemStack = generateProcedurallyGeneratedItem(tierLevel, player, null); + if (ItemSettingsConfig.isPutLootDirectlyIntoPlayerInventory()) player.getInventory().addItem(itemStack); + else processPhysicalItem(location, itemStack, player); + return itemStack; + } + + private static ItemStack generateProcedurallyGeneratedItem(int tierLevel, Player player, EliteEntity eliteEntity) { + return ItemConstructor.constructItem(tierLevel, eliteEntity, player, false); + } + private static ItemStack dropScalableItem(EliteEntity eliteEntity, int itemTier, Player player) { + ItemStack itemStack = generateScalableItem(itemTier, player, eliteEntity); + if (ItemSettingsConfig.isPutLootDirectlyIntoPlayerInventory()) player.getInventory().addItem(itemStack); + else processPhysicalItem(eliteEntity.getLocation(), itemStack, player); + return itemStack; } - private static Item dropProcedurallyGeneratedItem(int tierLevel, EliteMobEntity eliteMobEntity) { + private static ItemStack dropScalableItem(Location location, int itemTier, Player player) { + ItemStack itemStack = generateScalableItem(itemTier, player, null); + if (ItemSettingsConfig.isPutLootDirectlyIntoPlayerInventory()) player.getInventory().addItem(itemStack); + else processPhysicalItem(location, itemStack, player); + return itemStack; + } - ItemStack randomLoot = ItemConstructor.constructItem(tierLevel, eliteMobEntity); - return eliteMobEntity.getLivingEntity().getWorld().dropItem(eliteMobEntity.getLivingEntity().getLocation(), randomLoot); + private static ItemStack generateScalableItem(int itemTier, Player player, EliteEntity eliteEntity) { + return ScalableItemConstructor.randomizeScalableItem(itemTier, player, eliteEntity); + } + private static ItemStack dropLimitedItem(EliteEntity eliteEntity, int itemTier, Player player) { + ItemStack itemStack = generateLimitedItem(itemTier, player, eliteEntity); + if (ItemSettingsConfig.isPutLootDirectlyIntoPlayerInventory()) player.getInventory().addItem(itemStack); + else processPhysicalItem(eliteEntity.getLocation(), itemStack, player); + return itemStack; } - private static Item dropDynamicallyScalingItem(EliteMobEntity eliteMobEntity, int itemTier) { + private static ItemStack dropLimitedItem(Location location, int itemTier, Player player) { + ItemStack itemStack = generateLimitedItem(itemTier, player, null); + if (ItemSettingsConfig.isPutLootDirectlyIntoPlayerInventory()) player.getInventory().addItem(itemStack); + else processPhysicalItem(location, itemStack, player); + return itemStack; + } - return eliteMobEntity.getLivingEntity().getWorld().dropItem(eliteMobEntity.getLivingEntity().getLocation(), - ScalableItemConstructor.constructDynamicItem(itemTier)); + private static ItemStack generateLimitedItem(int itemTier, Player player, EliteEntity eliteEntity) { + return ScalableItemConstructor.randomizeLimitedItem(itemTier, player, eliteEntity); + } + private static ItemStack dropFixedItem(EliteEntity eliteEntity, int itemTier, Player player) { + ItemStack itemStack = generateFixedItem(itemTier, player, eliteEntity); + if (ItemSettingsConfig.isPutLootDirectlyIntoPlayerInventory()) player.getInventory().addItem(itemStack); + else processPhysicalItem(eliteEntity.getLocation(), itemStack, player); + return itemStack; } - private static Item dropLimitedScalingItem(EliteMobEntity eliteMobEntity, int itemTier) { + private static ItemStack dropFixedItem(Location location, int itemTier, Player player) { + ItemStack itemStack = generateFixedItem(itemTier, player, null); + if (ItemSettingsConfig.isPutLootDirectlyIntoPlayerInventory()) player.getInventory().addItem(itemStack); + else processPhysicalItem(location, itemStack, player); + return itemStack; + } - return eliteMobEntity.getLivingEntity().getWorld().dropItem(eliteMobEntity.getLivingEntity().getLocation(), - ScalableItemConstructor.constructLimitedItem(itemTier)); + private static ItemStack generateFixedItem(int itemTier, Player player, EliteEntity eliteEntity) { + return CustomItem.getFixedItems().get(itemTier).get(ThreadLocalRandom.current().nextInt(CustomItem.getFixedItems().get(itemTier).size())).generateDefaultsItemStack(player, false, eliteEntity); + } + private static void processPhysicalItem(Location location, ItemStack itemStack, Player player) { + Item item = location.getWorld().dropItem(location, itemStack); + if (item.getItemStack().hasItemMeta() && item.getItemStack().getItemMeta().hasDisplayName()) { + item.setCustomName(item.getItemStack().getItemMeta().getDisplayName()); + item.setCustomNameVisible(true); + } + SoulbindEnchantment.addPhysicalDisplay(item, player); + RareDropEffect.runEffect(item); } - private static Item dropStaticScalingItem(EliteMobEntity eliteMobEntity, int itemTier) { - return eliteMobEntity.getLivingEntity().getWorld().dropItem(eliteMobEntity.getLivingEntity().getLocation(), - ScalableItemConstructor.staticItems.get(itemTier).get(ThreadLocalRandom.current() - .nextInt(ScalableItemConstructor.staticItems.get(itemTier).size()) - 1)); + @EventHandler + public void onDeath(EliteMobDeathEvent event) { + if (!event.getEliteEntity().isVanillaLoot()) event.getEntityDeathEvent().getDrops().clear(); + if (!event.getEliteEntity().isEliteLoot()) return; + if (event.getEliteEntity().getLevel() < 1) return; + if (event.getEliteEntity().getDamagers().isEmpty()) return; + generatePlayerLoot(event.getEliteEntity()); } } diff --git a/src/main/java/com/magmaguy/elitemobs/items/MobTierCalculator.java b/src/main/java/com/magmaguy/elitemobs/items/MobTierCalculator.java new file mode 100644 index 000000000..1b01bdabf --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/items/MobTierCalculator.java @@ -0,0 +1,23 @@ +package com.magmaguy.elitemobs.items; + +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; + +public class MobTierCalculator { + public static final double PER_TIER_LEVEL_INCREASE = 1; + + private MobTierCalculator() { + } + + public static double findMobTier(EliteEntity eliteEntity) { + return eliteEntity.getLevel() / PER_TIER_LEVEL_INCREASE; + } + + public static double findMobTier(int mobLevel) { + return mobLevel / PER_TIER_LEVEL_INCREASE; + } + + public static int findMobLevel(int mobTier) { + return (int) (mobTier * PER_TIER_LEVEL_INCREASE); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/items/MobTierFinder.java b/src/main/java/com/magmaguy/elitemobs/items/MobTierFinder.java deleted file mode 100644 index 44a01c0ed..000000000 --- a/src/main/java/com/magmaguy/elitemobs/items/MobTierFinder.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.magmaguy.elitemobs.items; - -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; - -public class MobTierFinder { - - public static final double PER_TIER_LEVEL_INCREASE = ConfigValues.mobCombatSettingsConfig.getDouble(MobCombatSettingsConfig.PER_TIER_LEVEL_INCREASE); - - public static double findMobTier(EliteMobEntity eliteMobEntity) { - - return eliteMobEntity.getLevel() / PER_TIER_LEVEL_INCREASE; - - } - - public static double findMobTier(int mobLevel) { - - return mobLevel / PER_TIER_LEVEL_INCREASE; - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/items/ObfuscatedSignatureLoreData.java b/src/main/java/com/magmaguy/elitemobs/items/ObfuscatedSignatureLoreData.java deleted file mode 100644 index e533f1876..000000000 --- a/src/main/java/com/magmaguy/elitemobs/items/ObfuscatedSignatureLoreData.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.items; - -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; - -public class ObfuscatedSignatureLoreData { - - public static final String ITEM_SIGNATURE = "EliteItem"; - - public static Boolean obfuscatedSignatureDetector(ItemStack itemStack) { - - if (itemStack == null || itemStack.getType().equals(Material.AIR) || !itemStack.getItemMeta().hasLore()) return false; - - return itemStack.getItemMeta().getLore().get(0).replace("§", "").contains(ITEM_SIGNATURE); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/items/PlaceEventPrevent.java b/src/main/java/com/magmaguy/elitemobs/items/PlaceEventPrevent.java index 93c1e1904..5a63b6087 100644 --- a/src/main/java/com/magmaguy/elitemobs/items/PlaceEventPrevent.java +++ b/src/main/java/com/magmaguy/elitemobs/items/PlaceEventPrevent.java @@ -1,22 +1,6 @@ -/* - * 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 . - */ - package com.magmaguy.elitemobs.items; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.ItemsCustomLootSettingsConfig; +import com.magmaguy.elitemobs.config.ItemSettingsConfig; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.block.Action; @@ -27,7 +11,7 @@ public class PlaceEventPrevent implements Listener { @EventHandler public void onPlaceForbiddenItem(PlayerInteractEvent event) { - if (!ConfigValues.itemsCustomLootSettingsConfig.getBoolean(ItemsCustomLootSettingsConfig.PREVENT_CUSTOM_ITEM_PLACING)) + if (!ItemSettingsConfig.isPreventCustomItemPlacement()) return; if (!event.isBlockInHand()) return; @@ -36,7 +20,7 @@ public void onPlaceForbiddenItem(PlayerInteractEvent event) { if (event.getItem() == null || event.getItem().getItemMeta() == null) return; - if (ObfuscatedSignatureLoreData.obfuscatedSignatureDetector(event.getItem())) + if (ItemTagger.isEliteItem(event.getItem())) event.setCancelled(true); } diff --git a/src/main/java/com/magmaguy/elitemobs/items/PotionEffectApplier.java b/src/main/java/com/magmaguy/elitemobs/items/PotionEffectApplier.java deleted file mode 100644 index 678cfde04..000000000 --- a/src/main/java/com/magmaguy/elitemobs/items/PotionEffectApplier.java +++ /dev/null @@ -1,441 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.items; - -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.ItemsCustomLootSettingsConfig; -import com.magmaguy.elitemobs.items.itemconstructor.LoreGenerator; -import org.bukkit.Bukkit; -import org.bukkit.entity.Arrow; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.inventory.ItemStack; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; - -/** - * Created by MagmaGuy on 14/03/2017. - */ -public class PotionEffectApplier implements Listener { - - public static final String TARGET = "TARGET"; - public static final String SELF = "SELF"; - public static final String CONTINUOUS = "CONTINUOUS"; - public static final String ONHIT = "ONHIT"; - List offensivePotionEffects = new ArrayList<>(Arrays.asList( - PotionEffectType.BLINDNESS, - PotionEffectType.CONFUSION, - PotionEffectType.GLOWING, - PotionEffectType.HARM, - PotionEffectType.HUNGER, - PotionEffectType.LEVITATION, - PotionEffectType.POISON, - PotionEffectType.SLOW, - PotionEffectType.SLOW_DIGGING, - PotionEffectType.UNLUCK, - PotionEffectType.WEAKNESS, - PotionEffectType.WITHER - )); - - public void potionEffectApplier() { - - //scan through what players are wearing - for (Player player : Bukkit.getOnlinePlayers()) { - - if (player.getInventory().getItemInMainHand() != null) { - - itemPotionEffectCheck(player.getInventory().getItemInMainHand(), player, false); - - } - - if (player.getInventory().getItemInOffHand() != null) { - - itemPotionEffectCheck(player.getInventory().getItemInOffHand(), player, false); - - } - - if (player.getInventory().getBoots() != null) { - - itemPotionEffectCheck(player.getInventory().getBoots(), player, false); - - } - - if (player.getInventory().getLeggings() != null) { - - itemPotionEffectCheck(player.getInventory().getLeggings(), player, false); - - } - - if (player.getInventory().getChestplate() != null) { - - itemPotionEffectCheck(player.getInventory().getChestplate(), player, false); - - } - - if (player.getInventory().getHelmet() != null) { - - itemPotionEffectCheck(player.getInventory().getHelmet(), player, false); - - } - - } - - } - - private void itemPotionEffectCheck(ItemStack itemStack, Player player, boolean event) { - - itemPotionEffectCheck(itemStack, player, event, null); - - } - - private void itemPotionEffectCheck(ItemStack itemStack, Player player, boolean event, LivingEntity livingEntity) { - - if (itemStack.getItemMeta() == null || itemStack.getItemMeta().getLore() == null) return; - - List deobfuscatedLore = loreDeobfuscator(itemStack); - - if (deobfuscatedLore.size() > 0) { - - HashMap> potionEffects = potionEffectCreator(deobfuscatedLore, event); - - if (!event) { - - continuousPotionEffectApplier(potionEffects, player); - - } - - if (event) { - - eventPotionEffectApplier(potionEffects, player, livingEntity); - - } - - } - - } - - public List loreDeobfuscator(ItemStack itemStack) { - - List lore = itemStack.getItemMeta().getLore(); - List deobfuscatedPotionEffect = new ArrayList<>(); - - if (lore.isEmpty()) return deobfuscatedPotionEffect; - - String deobfuscatedString = lore.get(0).replace("§", ""); - - if (!deobfuscatedString.contains(LoreGenerator.OBFUSCATED_POTIONS)) return deobfuscatedPotionEffect; - - for (PotionEffectType potionEffectType : PotionEffectType.values()) - if (potionEffectType != null) - for (String spaceSeparation : deobfuscatedString.split(",")) { - //individual potion effects are separated at this level - List amplifierSeparation = Arrays.asList(spaceSeparation.split(":")); - - if (amplifierSeparation.size() > 1 && amplifierSeparation.get(0).equals(potionEffectType.getName())) - deobfuscatedPotionEffect.add(spaceSeparation); - - } - - - return deobfuscatedPotionEffect; - - } - - private HashMap> potionEffectCreator(List deobfuscatedLore, boolean event) { - - HashMap> potionEffects = new HashMap<>(); - - - for (String string : deobfuscatedLore) { - - int substringIndex = 0; - PotionEffectType potionEffectType = null; - int potionEffectMagnitude = 0; - String victim; - List tags = new ArrayList<>(); - - - for (String substring : string.split(":")) { - - if (substringIndex == 0) { - - potionEffectType = PotionEffectType.getByName(substring); - - } - - if (substringIndex == 1) { - - potionEffectMagnitude = Integer.parseInt(substring); - - } - - if (substringIndex == 2) { - - victim = substring; - if (victim.equalsIgnoreCase(TARGET) || victim.equalsIgnoreCase(SELF)) { - - tags.add(victim); - - } else { - - Bukkit.getLogger().info("[EliteMobs] Error with ItemsCustomLootList.yml: was expecting '" + TARGET + "' or '" - + SELF + "' values but got '" + victim + "' instead."); - - } - - } - - if (substringIndex == 3) { - - if (substring.equalsIgnoreCase(CONTINUOUS)) { - - tags.add(substring); - - } else if (substring.equalsIgnoreCase(ONHIT)) { - - tags.add(substring); - - } else { - - Bukkit.getLogger().info("[EliteMobs] Error with ItemsCustomLootList.yml: was expecting '" + CONTINUOUS + - "' or '" + ONHIT + "' value but got '" + substring + "' instead."); - - } - - } - - substringIndex++; - - } - - if (potionEffectType != null && potionEffectMagnitude > 0) { - - PotionEffect potionEffect; - - if (!event) potionEffect = continuousPotionEffect(potionEffectType, potionEffectMagnitude - 1); - else potionEffect = eventPotionEffect(potionEffectType, potionEffectMagnitude - 1); - - potionEffects.put(potionEffect, tags); - - } else { - - Bukkit.getLogger().info("[EliteMobs] There seems to be something very wrong with one of your potion effects."); - Bukkit.getLogger().info("[EliteMobs] An item has an invalid potion effect or potion effect level."); - Bukkit.getLogger().info("[EliteMobs] Problematic entry has the follow settings: " + string); - - } - - } - - - return potionEffects; - - } - - private PotionEffect continuousPotionEffect(PotionEffectType potionEffectType, int potionEffectMagnitude) { - - if (potionEffectType.equals(PotionEffectType.NIGHT_VISION)) { - return new PotionEffect(potionEffectType, 15 * 20, potionEffectMagnitude); - } - return new PotionEffect(potionEffectType, 2 * 20, potionEffectMagnitude); - - } - - private PotionEffect eventPotionEffect(PotionEffectType potionEffectType, int potionEffectMagnitude) { - - return new PotionEffect(potionEffectType, potionEffectDuration(potionEffectType), potionEffectMagnitude); - - } - - private int potionEffectDuration(PotionEffectType potionEffectType) { - - if (ConfigValues.itemsCustomLootSettingsConfig.contains(ItemsCustomLootSettingsConfig.DEFAULT_POTION_EFFECT_DURATION_NODE_PREFIX + potionEffectType.getName())) { - - return 20 * ConfigValues.itemsCustomLootSettingsConfig.getInt(ItemsCustomLootSettingsConfig.DEFAULT_POTION_EFFECT_DURATION_NODE_PREFIX + potionEffectType.getName()); - - } else { - - return 1; - - } - - } - - private void continuousPotionEffectApplier(HashMap> potionEffects, Player - player) { - - for (PotionEffect potionEffect : potionEffects.keySet()) { - - if (potionEffects.get(potionEffect).size() > 0) { - - if (potionEffects.get(potionEffect).get(0).equalsIgnoreCase(SELF)) { - - if ((!offensivePotionEffects.contains(potionEffect.getType()) && potionEffects.get(potionEffect).size() == 1) || - (!offensivePotionEffects.contains(potionEffect.getType()) && potionEffects.get(potionEffect).get(1).equalsIgnoreCase(CONTINUOUS))) { - - player.removePotionEffect(potionEffect.getType()); - player.addPotionEffect(potionEffect); - - } - - if (offensivePotionEffects.contains(potionEffect.getType()) && potionEffects.get(potionEffect).size() > 1) { - - if (potionEffects.get(potionEffect).get(1).equalsIgnoreCase(CONTINUOUS)) { - - player.removePotionEffect(potionEffect.getType()); - player.addPotionEffect(potionEffect); - - } - - } - - - } else if (potionEffects.get(potionEffect).get(0).equalsIgnoreCase(TARGET)) { - - //this doesn't do anything since this will only continuously apply to the player. - - } - - } else { - - //legacy config settings where there are no tags - if (!offensivePotionEffects.contains(potionEffect.getType())) { - - player.removePotionEffect(potionEffect.getType()); - player.addPotionEffect(potionEffect); - - } - - } - - } - - } - - private void eventPotionEffectApplier(HashMap> potionEffects, Player - player, LivingEntity livingEntity) { - - for (PotionEffect potionEffect : potionEffects.keySet()) { - - if (potionEffects.get(potionEffect).size() > 0) { - - if (potionEffects.get(potionEffect).get(0).equalsIgnoreCase(SELF)) { - - player.removePotionEffect(potionEffect.getType()); - player.addPotionEffect(potionEffect); - - if (potionEffects.get(potionEffect).size() > 1) { - - if (potionEffects.get(potionEffect).get(1).equalsIgnoreCase(CONTINUOUS)) { - - player.removePotionEffect(potionEffect.getType()); - - } - - } - - - } else if (potionEffects.get(potionEffect).get(0).equalsIgnoreCase(TARGET)) { - - livingEntity.removePotionEffect(potionEffect.getType()); - livingEntity.addPotionEffect(potionEffect); - - } - - } else { - - //legacy config settings where there are no tags - if (offensivePotionEffects.contains(potionEffect.getType())) { - - livingEntity.removePotionEffect(potionEffect.getType()); - livingEntity.addPotionEffect(potionEffect); - - } - - } - - } - - } - - @EventHandler - public void onPlayerHitWithPotionEffect(EntityDamageByEntityEvent event) { - - if (event.isCancelled()) return; - - Player player; - - //deal with bows - if (event.getDamager() instanceof Arrow) { - - Arrow arrow = (Arrow) event.getDamager(); - - if (arrow.getShooter() instanceof Player) { - - player = (Player) arrow.getShooter(); - - } else { - - return; - - } - - } else if (event.getDamager() instanceof Player) { - - player = (Player) event.getDamager(); - - } else { - - return; - - } - - LivingEntity damagee; - - if (event.getEntity() instanceof LivingEntity) { - - damagee = (LivingEntity) event.getEntity(); - - } else { - - return; - - } - - if (player.getInventory().getItemInMainHand() != null) { - - itemPotionEffectCheck(player.getInventory().getItemInMainHand(), player, true, damagee); - - } - - if (player.getInventory().getItemInOffHand() != null) { - - itemPotionEffectCheck(player.getInventory().getItemInOffHand(), player, true, damagee); - - } - - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/items/RareDropEffect.java b/src/main/java/com/magmaguy/elitemobs/items/RareDropEffect.java index 848cfa9d2..2d007a551 100644 --- a/src/main/java/com/magmaguy/elitemobs/items/RareDropEffect.java +++ b/src/main/java/com/magmaguy/elitemobs/items/RareDropEffect.java @@ -1,27 +1,26 @@ package com.magmaguy.elitemobs.items; import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.config.ItemSettingsConfig; import com.magmaguy.elitemobs.items.itemconstructor.ItemQualityColorizer; -import org.bukkit.Location; import org.bukkit.Particle; import org.bukkit.entity.Item; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.entity.ItemSpawnEvent; import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.util.Vector; - -import java.util.concurrent.ThreadLocalRandom; public class RareDropEffect implements Listener { public static void runEffect(Item item) { + if (!ItemSettingsConfig.isEnableRareItemParticleEffects()) return; if (!(ItemQualityColorizer.getItemQuality(item.getItemStack()).equals(ItemQualityColorizer.ItemQuality.LIGHT_BLUE) || ItemQualityColorizer.getItemQuality(item.getItemStack()).equals(ItemQualityColorizer.ItemQuality.GOLD))) return; new BukkitRunnable() { + int counter = 0; @Override public void run() { @@ -31,31 +30,21 @@ public void run() { return; } - for (int i = 0; i < 3; i++) { - - Location location = item.getLocation().clone(); - double randomizedY = ThreadLocalRandom.current().nextDouble() * 2; - double randomizedX = (ThreadLocalRandom.current().nextDouble() * 2 - 1) / randomizedY; - double randomizedZ = (ThreadLocalRandom.current().nextDouble() * 2 - 1) / randomizedY; - location.add(new Vector(randomizedX, randomizedY, randomizedZ)); - - location.getWorld().spawnParticle(Particle.FIREWORKS_SPARK, location, 1, 0, 0, 0, 0); - - } + item.getWorld().spawnParticle(Particle.PORTAL, item.getLocation(), 5, 0.01, 0.01, 0.01, 0.5); + counter += 20; + if (counter > 20 * 60 * 2) + cancel(); } - }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 20); } @EventHandler public void onItemDrop(ItemSpawnEvent event) { - - if (!ObfuscatedSignatureLoreData.obfuscatedSignatureDetector(event.getEntity().getItemStack())) return; - + if (!ItemTagger.isEliteItem(event.getEntity().getItemStack())) return; runEffect(event.getEntity()); - } } diff --git a/src/main/java/com/magmaguy/elitemobs/items/ScalableItemConstructor.java b/src/main/java/com/magmaguy/elitemobs/items/ScalableItemConstructor.java index e4c73f470..1e7450317 100644 --- a/src/main/java/com/magmaguy/elitemobs/items/ScalableItemConstructor.java +++ b/src/main/java/com/magmaguy/elitemobs/items/ScalableItemConstructor.java @@ -1,10 +1,14 @@ package com.magmaguy.elitemobs.items; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.ItemsDropSettingsConfig; +import com.magmaguy.elitemobs.config.ItemSettingsConfig; +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfig; +import com.magmaguy.elitemobs.items.customitems.CustomItem; import com.magmaguy.elitemobs.items.itemconstructor.ItemConstructor; -import com.magmaguy.elitemobs.items.itemconstructor.ScallableItemObject; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import java.util.ArrayList; @@ -14,48 +18,44 @@ public class ScalableItemConstructor { + private ScalableItemConstructor() { + } - public static List dynamicallyScalableItems = new ArrayList<>(); - public static HashMap> limitedScalableItems = new HashMap<>(); - public static HashMap> staticItems = new HashMap<>(); - - /* - Fully dynamic scalable items can be of any item rank all the way up to the maximum valid item tier. - As such, there is no sense in trying to sort this by tiers. - */ - public static ItemStack constructDynamicItem(int itemTier) { - - ScallableItemObject scalableItemObject = dynamicallyScalableItems.get(ThreadLocalRandom.current().nextInt(dynamicallyScalableItems.size())); - - HashMap newEnchantmentList = updateDynamicEnchantments(scalableItemObject.enchantments, itemTier); + public static ItemStack randomizeScalableItem(int itemTier, Player player, EliteEntity eliteEntity) { + CustomItem customItem = CustomItem.getScalableItems().get(ThreadLocalRandom.current().nextInt(CustomItem.getScalableItems().size())); + return constructScalableItem(itemTier, customItem, player, eliteEntity); + } + public static ItemStack constructScalableItem(int itemTier, CustomItem customItem, Player player, EliteEntity eliteEntity) { + if (!customItem.getPermission().isEmpty() && !player.hasPermission(customItem.getPermission())) return null; + HashMap newEnchantmentList = updateDynamicEnchantments(customItem.getEnchantments(), itemTier, false); return ItemConstructor.constructItem( - scalableItemObject.rawName, - scalableItemObject.material, + customItem.getName(), + customItem.getMaterial(), newEnchantmentList, - scalableItemObject.customEnchantments, - scalableItemObject.potionEffects, - scalableItemObject.lore + customItem.getCustomEnchantments(), + customItem.getPotionEffects(), + customItem.getLore(), + eliteEntity, + player, + false, + customItem.getCustomLootConfigFields().getCustomModelID() ); - } - private static HashMap updateDynamicEnchantments(HashMap enchantmentsList, int itemTier) { + private static HashMap updateDynamicEnchantments(HashMap enchantmentsList, int itemTier, boolean isLimited) { if (enchantmentsList.containsKey(Enchantment.PROTECTION_ENVIRONMENTAL) && - enchantmentsList.get(Enchantment.PROTECTION_ENVIRONMENTAL) > - ConfigValues.itemsDropSettingsConfig.getInt(ItemsDropSettingsConfig.MAXIMUM_LOOT_TIER)) - itemTier = ConfigValues.itemsDropSettingsConfig.getInt(ItemsDropSettingsConfig.MAXIMUM_LOOT_TIER); + enchantmentsList.get(Enchantment.PROTECTION_ENVIRONMENTAL) > ItemSettingsConfig.getMaximumLootTier()) + itemTier = ItemSettingsConfig.getMaximumLootTier(); if (enchantmentsList.containsKey(Enchantment.DAMAGE_ALL) && - enchantmentsList.get(Enchantment.DAMAGE_ALL) > - ConfigValues.itemsDropSettingsConfig.getInt(ItemsDropSettingsConfig.MAXIMUM_LOOT_TIER)) - itemTier = ConfigValues.itemsDropSettingsConfig.getInt(ItemsDropSettingsConfig.MAXIMUM_LOOT_TIER); + enchantmentsList.get(Enchantment.DAMAGE_ALL) > ItemSettingsConfig.getMaximumLootTier()) + itemTier = ItemSettingsConfig.getMaximumLootTier(); if (enchantmentsList.containsKey(Enchantment.ARROW_DAMAGE) && - enchantmentsList.get(Enchantment.ARROW_DAMAGE) > - ConfigValues.itemsDropSettingsConfig.getInt(ItemsDropSettingsConfig.MAXIMUM_LOOT_TIER)) - itemTier = ConfigValues.itemsDropSettingsConfig.getInt(ItemsDropSettingsConfig.MAXIMUM_LOOT_TIER); + enchantmentsList.get(Enchantment.ARROW_DAMAGE) > ItemSettingsConfig.getMaximumLootTier()) + itemTier = ItemSettingsConfig.getMaximumLootTier(); HashMap newEnchantmentList = new HashMap<>(); HashMap secondaryEnchantmentList = new HashMap<>(); @@ -73,7 +73,10 @@ private static HashMap updateDynamicEnchantments(HashMap updateDynamicEnchantments(HashMap updateDynamicEnchantments(HashMap localLootList = new ArrayList<>(); + List localLootList = new ArrayList<>(); for (int i = 0; i < itemTier; i++) - if (limitedScalableItems.containsKey(i)) - localLootList.addAll(limitedScalableItems.get(i)); + if (CustomItem.getLimitedItem().containsKey(i)) + localLootList.addAll(CustomItem.getLimitedItem().get(i)); + + /* + Currently elitemobs has no way of telling if there will be a limited item available for the specific asked tier + //todo: fix this + */ + if (localLootList.size() == 0) + ItemStackGenerator.generateItemStack(Material.AIR); + + CustomItem customItem = localLootList.get(ThreadLocalRandom.current().nextInt(localLootList.size())); + if (!customItem.getPermission().isEmpty() && !player.hasPermission(customItem.getPermission())) return null; + + return constructLimitedItem(itemTier, customItem, player, eliteEntity); + + } + public static ItemStack constructLimitedItem(int itemTier, CustomItem customItem, Player player, EliteEntity eliteEntity) { - ScallableItemObject scalableItemObject = localLootList.get(ThreadLocalRandom.current().nextInt(localLootList.size()) - 1); - HashMap newEnchantmentList = updateLimitedEnchantments(scalableItemObject.enchantments, itemTier); + HashMap newEnchantmentList = updateLimitedEnchantments(customItem.getEnchantments(), itemTier); return ItemConstructor.constructItem( - scalableItemObject.rawName, - scalableItemObject.material, + customItem.getName(), + customItem.getMaterial(), newEnchantmentList, - scalableItemObject.customEnchantments, - scalableItemObject.potionEffects, - scalableItemObject.lore + customItem.getCustomEnchantments(), + customItem.getPotionEffects(), + customItem.getLore(), + eliteEntity, + player, + false, + customItem.getCustomLootConfigFields().getCustomModelID() ); } @@ -137,17 +164,15 @@ private static HashMap updateLimitedEnchantments(HashMap - ConfigValues.itemsDropSettingsConfig.getInt(ItemsDropSettingsConfig.MAXIMUM_LOOT_TIER)) + enchantmentsList.get(Enchantment.DAMAGE_ALL) > ItemSettingsConfig.getMaximumLootTier()) itemTier = enchantmentsList.get(Enchantment.DAMAGE_ALL); if (enchantmentsList.containsKey(Enchantment.ARROW_DAMAGE) && - enchantmentsList.get(Enchantment.ARROW_DAMAGE) > - ConfigValues.itemsDropSettingsConfig.getInt(ItemsDropSettingsConfig.MAXIMUM_LOOT_TIER)) + enchantmentsList.get(Enchantment.ARROW_DAMAGE) > ItemSettingsConfig.getMaximumLootTier()) itemTier = enchantmentsList.get(Enchantment.ARROW_DAMAGE); - return updateDynamicEnchantments(enchantmentsList, itemTier); + return updateDynamicEnchantments(enchantmentsList, itemTier, true); } diff --git a/src/main/java/com/magmaguy/elitemobs/items/ShareItem.java b/src/main/java/com/magmaguy/elitemobs/items/ShareItem.java new file mode 100644 index 000000000..17f7e5cd5 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/items/ShareItem.java @@ -0,0 +1,41 @@ +package com.magmaguy.elitemobs.items; + +import com.magmaguy.elitemobs.api.EliteMobsItemDetector; +import net.md_5.bungee.api.chat.ComponentBuilder; +import net.md_5.bungee.api.chat.HoverEvent; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +public class ShareItem { + + public static void showOnChat(Player player) { + if (player.getInventory().getItemInMainHand().getType().equals(Material.AIR)) return; + ItemStack itemStack = player.getInventory().getItemInMainHand(); + if (!itemStack.hasItemMeta()) return; + if (!itemStack.getItemMeta().hasDisplayName()) return; + if (!itemStack.getItemMeta().hasLore()) return; + + String name = itemStack.getItemMeta().getDisplayName(); + + TextComponent interactiveMessage = new TextComponent(player.getDisplayName() + ": " + name); + setItemHoverEvent(interactiveMessage, itemStack); + + for (Player onlinePlayer : Bukkit.getServer().getOnlinePlayers()) + onlinePlayer.spigot().sendMessage(interactiveMessage); + } + + public static void setItemHoverEvent(TextComponent textComponent, ItemStack itemStack) { + if (!EliteMobsItemDetector.isEliteMobsItem(itemStack)) + return; + String stringList = itemStack.getItemMeta().getDisplayName(); + if (itemStack.getItemMeta().hasLore()) + for (String loreString : itemStack.getItemMeta().getLore()) + stringList += "\n" + ChatColor.DARK_PURPLE + ChatColor.ITALIC + loreString; + textComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(stringList).create())); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/items/customenchantments/CriticalStrikesEnchantment.java b/src/main/java/com/magmaguy/elitemobs/items/customenchantments/CriticalStrikesEnchantment.java new file mode 100644 index 000000000..ecf37b917 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/items/customenchantments/CriticalStrikesEnchantment.java @@ -0,0 +1,21 @@ +package com.magmaguy.elitemobs.items.customenchantments; + +import com.magmaguy.elitemobs.config.enchantments.premade.CriticalStrikesConfig; +import com.magmaguy.elitemobs.utils.DialogArmorStand; +import org.bukkit.entity.Entity; +import org.bukkit.util.Vector; + + +public class CriticalStrikesEnchantment extends CustomEnchantment { + + public static String key = "critical_strikes"; + + public CriticalStrikesEnchantment() { + super(key, true); + } + + public static void criticalStrikePopupMessage(Entity entity, Vector offset) { + DialogArmorStand.createDialogArmorStand(entity, CriticalStrikesConfig.getCriticalHitPopup(), offset); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/items/customenchantments/CustomEnchantment.java b/src/main/java/com/magmaguy/elitemobs/items/customenchantments/CustomEnchantment.java index a5fcc7c61..1461d4620 100644 --- a/src/main/java/com/magmaguy/elitemobs/items/customenchantments/CustomEnchantment.java +++ b/src/main/java/com/magmaguy/elitemobs/items/customenchantments/CustomEnchantment.java @@ -1,76 +1,80 @@ package com.magmaguy.elitemobs.items.customenchantments; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfig; +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; +import com.magmaguy.elitemobs.items.ItemTagger; import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; -import java.util.List; +import java.util.ArrayList; public abstract class CustomEnchantment { - /* - Code here has been maintained as static because the key value is frequently accessed and stores a static value - setKey() and setName() need to be rewritten in every class - */ - - public void initialize() { - - setKey(); - + private static final ArrayList customEnchantments = new ArrayList<>(); + public final String key; + private final boolean dynamic; + private final EnchantmentsConfigFields enchantmentsConfigFields; + private final Enchantment originalEnchantment = null; + + public CustomEnchantment(String key, boolean dynamic) { + this.key = key; + this.dynamic = dynamic; + this.enchantmentsConfigFields = EnchantmentsConfig.getEnchantment(key + ".yml"); + customEnchantments.add(this); } - /* - Key is used to hide the enchantment in the lore to later ID the item, is independent from name to avoid issues with - config changes invalidating old enchantment names - It's also used as the value to write in for the configuration file - */ - public String key = setKey(); - - public String setKey() { - return "placeholder key"; + public static ArrayList getCustomEnchantments() { + return customEnchantments; } - public String getKey() { - return key; - } - - /* - Get the enchantment string for assembling configurations - */ - public String assembleConfigString(int enchantmentLevel) { - return key + "," + enchantmentLevel; + public static void initializeCustomEnchantments() { + new FlamethrowerEnchantment(); + new PlasmaBootsEnchantment(); + new HunterEnchantment(); + new CriticalStrikesEnchantment(); + new DrillingEnchantment(); + new IceBreakerEnchantment(); + new MeteorShowerEnchantment(); + new SummonMerchantEnchantment(); + new SummonWolfEnchantment(); + new UnbindEnchantment(); + new LightningEnchantment(); + new GrapplingHookEnchantment(); + new EarthquakeEnchantment(); } /* Check an itemstack has this enchantment */ - public boolean hasCustomEnchantment(ItemStack itemStack) { + public static boolean hasCustomEnchantment(ItemStack itemStack, String key) { if (itemStack == null || itemStack.getType().equals(Material.AIR)) return false; if (!itemStack.hasItemMeta()) return false; if (!itemStack.getItemMeta().hasLore()) return false; - return hasCustomEnchantment(itemStack.getItemMeta().getLore()); + return hasCustomEnchantment(itemStack.getItemMeta(), key); } - public boolean hasCustomEnchantment(List lore) { - return (lore.get(0).replace("§", "").contains(key)); + public static boolean hasCustomEnchantment(ItemMeta itemMeta, String key) { + return ItemTagger.getEnchantment(itemMeta, new NamespacedKey(MetadataHandler.PLUGIN, key)) > 0; } /* Get a custom enchantment's level */ - public int getCustomEnchantmentLevel(ItemStack itemStack) { - if (!itemStack.hasItemMeta()) return 0; - if (!itemStack.getItemMeta().hasLore()) return 0; - return getCustomEnchantmentLevel(itemStack.getItemMeta().getLore()); + public static int getCustomEnchantmentLevel(ItemStack itemStack, String key) { + if (itemStack == null) return 0; + return ItemTagger.getEnchantment(itemStack.getItemMeta(), new NamespacedKey(MetadataHandler.PLUGIN, key)); } - public int getCustomEnchantmentLevel(List lore) { - - for (String string : lore.get(0).replace("§", "").split(",")) - if (string.contains(key)) - return Integer.parseInt(string.split(":")[1]); - - return 0; + public String getKey() { + return key; + } + public EnchantmentsConfigFields getEnchantmentsConfigFields() { + return enchantmentsConfigFields; } } diff --git a/src/main/java/com/magmaguy/elitemobs/items/customenchantments/CustomEnchantmentCache.java b/src/main/java/com/magmaguy/elitemobs/items/customenchantments/CustomEnchantmentCache.java deleted file mode 100644 index 791d7aa34..000000000 --- a/src/main/java/com/magmaguy/elitemobs/items/customenchantments/CustomEnchantmentCache.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.magmaguy.elitemobs.items.customenchantments; - -public class CustomEnchantmentCache { - - /* - In order to implement use inheritance the custom enchantments can't be static - However, accessing the data stored in them benefits from static access, as ultimately the custom enchantments just - store a bunch on unchanging values - Hence, static access to these basically final values is provided in this class. - It also prevents issues related with having to re-initialize the values every time an instance of the method is invoked. - There's probably a better way of doing this, but I don't know it. If you do, let me know. - */ - - public static FlamethrowerEnchantment flamethrowerEnchantment = new FlamethrowerEnchantment(); - public static HunterEnchantment hunterEnchantment = new HunterEnchantment(); - -// Necessary for registering the config keys and item names, needs to run before items get constructed - public static void initialize(){ - - flamethrowerEnchantment.initialize(); - hunterEnchantment.initialize(); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/items/customenchantments/DrillingEnchantment.java b/src/main/java/com/magmaguy/elitemobs/items/customenchantments/DrillingEnchantment.java new file mode 100644 index 000000000..a6c11cd39 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/items/customenchantments/DrillingEnchantment.java @@ -0,0 +1,223 @@ +package com.magmaguy.elitemobs.items.customenchantments; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.items.ItemTagger; +import com.magmaguy.elitemobs.utils.EventCaller; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.Vector; + +import java.util.HashSet; +import java.util.Set; + +public class DrillingEnchantment extends CustomEnchantment { + + public static String key = "drilling"; + + public DrillingEnchantment() { + super(key, false); + } + + public static class DrillingEnchantmentEvents implements Listener { + private static final Set activePlayers = new HashSet<>(); + private Material material = null; + private ItemStack itemStack = null; + private MiningDirection miningDirection = null; + private Player player; + + @EventHandler(priority = EventPriority.HIGHEST) + public void onDig(BlockBreakEvent event) { + if (event.isCancelled()) return; + if (event.getPlayer().isSneaking()) return; + if (activePlayers.contains(event.getPlayer())) return; + if (!event.getPlayer().getInventory().getItemInMainHand().hasItemMeta() || + event.getPlayer().getInventory().getItemInMainHand().getItemMeta() == null) return; + if (!ItemTagger.hasEnchantment(event.getPlayer().getInventory().getItemInMainHand().getItemMeta(), new NamespacedKey(MetadataHandler.PLUGIN, key))) + return; + + + drillBlocks(event.getBlock(), + ItemTagger.getEnchantment(event.getPlayer().getInventory().getItemInMainHand().getItemMeta(), new NamespacedKey(MetadataHandler.PLUGIN, key)), + event.getPlayer().getLocation(), + event.getPlayer().getInventory().getItemInMainHand(), + event.getPlayer()); + + } + + private void drillBlocks(Block originalBlock, int enchantmentLevel, Location playerLocation, ItemStack playerItem, Player player) { + + this.player = player; + this.material = originalBlock.getType(); + this.itemStack = playerItem; + this.miningDirection = determineDirection(originalBlock.getLocation(), playerLocation); + + activePlayers.add(player); + + switch (enchantmentLevel) { + case 1: + drillLevel1(originalBlock); + break; + case 2: + drillLevel2(originalBlock); + break; + case 3: + drillLevel3(originalBlock); + drillLevel2(drillLevel1(originalBlock)); + break; + case 4: + drillLevel3(originalBlock); + drillLevel3(drillLevel1(originalBlock)); + drillLevel2(drillLevel1(drillLevel1(originalBlock))); + break; + case 5: + default: + drillLevel3(originalBlock); + drillLevel3(drillLevel1(originalBlock)); + drillLevel3(drillLevel1(drillLevel1(originalBlock))); + } + + activePlayers.remove(player); + + } + + private MiningDirection determineDirection(Location blockLocation, Location playerLocation) { + + Location adjustedPlayerLocation = playerLocation.clone().add(new Vector(0, 1, 0)); + Location adjustedBlockLocation = blockLocation.clone().add(new Vector(0.5, 0.5, 0.5)); + + Vector directionVector = adjustedBlockLocation.clone().subtract(adjustedPlayerLocation).toVector().normalize(); + + double x = directionVector.getX(); + double y = directionVector.getY(); + double z = directionVector.getZ(); + + if (Math.abs(y) > 0.9) { + if (y > 0) + return MiningDirection.UP; + else + return MiningDirection.DOWN; + } + + if (Math.abs(x) > Math.abs(z)) { + if (x > 0) + return MiningDirection.EAST; + else + return MiningDirection.WEST; + } + + if (z > 0) + return MiningDirection.NORTH; + + return MiningDirection.SOUTH; + + } + + private Block processBlock(Block originalBlock, Vector addedVector) { + if (originalBlock == null) return null; + Block finalBlock = originalBlock.getWorld().getBlockAt(originalBlock.getLocation().clone().add(addedVector)); + if (!this.material.equals(finalBlock.getType())) return finalBlock; + + BlockBreakEvent blockBreakEvent = new BlockBreakEvent(finalBlock, player); + new EventCaller(blockBreakEvent); + if (blockBreakEvent.isCancelled()) return null; + + finalBlock.breakNaturally(this.itemStack); + return finalBlock; + } + + private Block drillLevel1(Block originalBlock) { + + switch (miningDirection) { + case NORTH: + return processBlock(originalBlock, new Vector(0, 0, 1)); + case SOUTH: + return processBlock(originalBlock, new Vector(0, 0, -1)); + case EAST: + return processBlock(originalBlock, new Vector(1, 0, 0)); + case WEST: + return processBlock(originalBlock, new Vector(-1, 0, 0)); + case UP: + return processBlock(originalBlock, new Vector(0, 1, 0)); + case DOWN: + return processBlock(originalBlock, new Vector(0, -1, 0)); + default: + return null; + } + + } + + private void drillLevel2(Block originalBlock) { + + switch (miningDirection) { + case NORTH: + case SOUTH: + processBlock(originalBlock, new Vector(0, 1, 0)); + processBlock(originalBlock, new Vector(0, -1, 0)); + processBlock(originalBlock, new Vector(1, 0, 0)); + processBlock(originalBlock, new Vector(-1, 0, 0)); + break; + case EAST: + case WEST: + processBlock(originalBlock, new Vector(0, 1, 0)); + processBlock(originalBlock, new Vector(0, -1, 0)); + processBlock(originalBlock, new Vector(0, 0, 1)); + processBlock(originalBlock, new Vector(0, 0, -1)); + break; + case UP: + case DOWN: + processBlock(originalBlock, new Vector(1, 0, 0)); + processBlock(originalBlock, new Vector(-1, 0, 0)); + processBlock(originalBlock, new Vector(0, 0, 1)); + processBlock(originalBlock, new Vector(0, 0, -1)); + break; + } + + } + + private void drillLevel3(Block originalBlock) { + + switch (miningDirection) { + case NORTH: + case SOUTH: + for (int x = -1; x < 2; x++) + for (int y = -1; y < 2; y++) + if (!(x == 0 && y == 0)) + processBlock(originalBlock, new Vector(x, y, 0)); + break; + case EAST: + case WEST: + for (int y = -1; y < 2; y++) + for (int z = -1; z < 2; z++) + if (!(y == 0 && z == 0)) + processBlock(originalBlock, new Vector(0, y, z)); + break; + case UP: + case DOWN: + for (int x = -1; x < 2; x++) + for (int z = -1; z < 2; z++) + if (!(x == 0 && z == 0)) + processBlock(originalBlock, new Vector(x, 0, z)); + break; + } + + } + + private enum MiningDirection { + UP, + DOWN, + NORTH, + SOUTH, + EAST, + WEST + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/items/customenchantments/EarthquakeEnchantment.java b/src/main/java/com/magmaguy/elitemobs/items/customenchantments/EarthquakeEnchantment.java new file mode 100644 index 000000000..e80f68ab2 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/items/customenchantments/EarthquakeEnchantment.java @@ -0,0 +1,97 @@ +package com.magmaguy.elitemobs.items.customenchantments; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.config.enchantments.premade.EarthquakeConfig; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.playerdata.ElitePlayerInventory; +import org.bukkit.Bukkit; +import org.bukkit.Color; +import org.bukkit.Particle; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerToggleSneakEvent; +import org.bukkit.util.Vector; + +import java.util.HashSet; +import java.util.UUID; +import java.util.concurrent.ThreadLocalRandom; + +public class EarthquakeEnchantment extends CustomEnchantment { + public static String key = "earthquake"; + + public EarthquakeEnchantment() { + super(key, false); + } + + public static void doEarthquakeEnchantment(int earthquakeLevel, Player player) { + player.sendMessage(EarthquakeConfig.getEarthquakeActivationMessage()); + player.setVelocity(player.getLocation().getDirection().normalize().multiply((Math.log(earthquakeLevel + 2 / 2D) + 1) / 20D).setY(Math.log(earthquakeLevel + 2 / 2D))); + Bukkit.getScheduler().runTaskTimer(MetadataHandler.PLUGIN, (task) -> { + player.setFallDistance(0f); + if (!player.isValid() || !player.getLocation().clone().subtract(new Vector(0, 1, 0)).getBlock().isPassable() + && player.getLocation().getY() - player.getLocation().getBlock().getY() < 0.1 || !player.getLocation().clone().getBlock().isPassable()) { + task.cancel(); + doLanding(earthquakeLevel, player); + return; + } + player.getWorld().spawnParticle(Particle.REDSTONE, player.getLocation().getX(), player.getLocation().getY(), player.getLocation().getZ(), + 20, 0.1, 0.1, 0.1, 1, new Particle.DustOptions(Color.fromRGB( + ThreadLocalRandom.current().nextInt(80, 100), + ThreadLocalRandom.current().nextInt(20, 40), + ThreadLocalRandom.current().nextInt(10, 20) + ), 1)); + }, 5, 1); + } + + public static void doLanding(int level, Player player) { + double distance = Math.log(level + 2 / 2D) * 3; + for (Entity entity : player.getNearbyEntities(distance, distance, distance)) { + if (entity instanceof LivingEntity) { + if (entity.getType().equals(EntityType.PLAYER)) continue; + EliteEntity eliteEntity = EntityTracker.getEliteMobEntity(entity); + if (eliteEntity == null) { + entity.setVelocity(entity.getLocation().subtract(player.getLocation()).toVector().normalize().setY(.3).multiply(distance / 2d)); + } else { + entity.setVelocity(entity.getLocation().subtract(player.getLocation()).toVector().normalize().setY(.3) + .multiply((distance / 2d) / (eliteEntity.getLevel() * eliteEntity.getHealthMultiplier()))); + } + } + } + } + + public static class EarthquakeEnchantmentEvents implements Listener { + private static HashSet players = new HashSet<>(); + private static HashSet cooldownPlayers = new HashSet<>(); + + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH) + public void onSneak(PlayerToggleSneakEvent event) { + if (!event.isSneaking()) return; + if (event.getPlayer().isFlying()) return; + if (cooldownPlayers.contains(event.getPlayer().getUniqueId())) return; + //todo: don't check this event if the power is disabled + if (ElitePlayerInventory.playerInventories.get(event.getPlayer().getUniqueId()) == null) return; + double earthquakeLevel = ElitePlayerInventory.playerInventories.get(event.getPlayer().getUniqueId()).getEarthquakeLevel(true); + if (earthquakeLevel < 1) return; + if (!players.contains(event.getPlayer().getUniqueId())) { + players.add(event.getPlayer().getUniqueId()); + Bukkit.getScheduler().runTaskLater(MetadataHandler.PLUGIN, (task) -> players.remove(event.getPlayer().getUniqueId()), 10); + return; + } + players.remove(event.getPlayer().getUniqueId()); + cooldownPlayers.add(event.getPlayer().getUniqueId()); + Bukkit.getScheduler().runTaskLater(MetadataHandler.PLUGIN, (task) -> { + event.getPlayer().sendMessage(EarthquakeConfig.getEarthquakeAvailableMessage()); + cooldownPlayers.remove(event.getPlayer().getUniqueId()); + }, 20L * 60 * 2); + + doEarthquakeEnchantment((int) earthquakeLevel, event.getPlayer()); + + } + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/items/customenchantments/FlamethrowerEnchantment.java b/src/main/java/com/magmaguy/elitemobs/items/customenchantments/FlamethrowerEnchantment.java index bca993415..107dff350 100644 --- a/src/main/java/com/magmaguy/elitemobs/items/customenchantments/FlamethrowerEnchantment.java +++ b/src/main/java/com/magmaguy/elitemobs/items/customenchantments/FlamethrowerEnchantment.java @@ -1,7 +1,15 @@ package com.magmaguy.elitemobs.items.customenchantments; -import com.magmaguy.elitemobs.events.mobs.ZombieKing; -import com.magmaguy.elitemobs.utils.Cooldown; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfig; +import com.magmaguy.elitemobs.events.BossCustomAttackDamage; +import com.magmaguy.elitemobs.playerdata.ElitePlayerInventory; +import com.magmaguy.elitemobs.utils.CooldownHandler; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; @@ -10,41 +18,166 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.potion.PotionEffect; import org.bukkit.potion.PotionEffectType; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; -public class FlamethrowerEnchantment extends CustomEnchantment implements Listener { +public class FlamethrowerEnchantment extends CustomEnchantment { - public String setKey() { - return "FLAMETHROWER"; + private static final List playersUsingFlamethrower = new ArrayList<>(); + public static String key = "flamethrower"; + + public FlamethrowerEnchantment() { + super(key, false); + } + + private static List generateDamagePoints(Player player, Location fixedPlayerLocation) { + List locations = new ArrayList<>(); + Location eliteMobLocation = player.getLocation().clone(); + Vector toPlayerVector = fixedPlayerLocation.clone().subtract(eliteMobLocation).toVector().normalize().multiply(0.5); + for (int i = 0; i < 40; i++) + locations.add(eliteMobLocation.add(toPlayerVector).clone()); + return locations; } - private static ArrayList playersUsingFlamethrower = new ArrayList<>(); + private static void doDamage(List locations, Player player) { + for (Location location : locations) + for (Entity entity : location.getWorld().getNearbyEntities(location, 0.5, 0.5, 0.5)) + if (entity instanceof LivingEntity) { + if (entity.getType().equals(EntityType.PLAYER)) + continue; + if (((LivingEntity) entity).hasPotionEffect(PotionEffectType.FIRE_RESISTANCE)) continue; + BossCustomAttackDamage.dealCustomDamage(player, (LivingEntity) entity, ElitePlayerInventory.playerInventories.get(player.getUniqueId()).getWeaponTier(false)); + } - @EventHandler - public void onIteract(PlayerInteractEvent event) { + } - Player player = event.getPlayer(); - if (!(event.getAction().equals(Action.RIGHT_CLICK_BLOCK) || event.getAction().equals(Action.RIGHT_CLICK_AIR))) - return; + public static class FlamethrowerEnchantmentEvents implements Listener { - if (playersUsingFlamethrower.contains(player)) return; + @EventHandler + public void onInteract(PlayerInteractEvent event) { - ItemStack zombieKingAxe = player.getInventory().getItemInMainHand(); + if (!EnchantmentsConfig.getEnchantment("flamethrower.yml").isEnabled()) return; - if (hasCustomEnchantment(zombieKingAxe)) { + Player player = event.getPlayer(); - if (zombieKingAxe.getDurability() + 4 > zombieKingAxe.getType().getMaxDurability()) { + if (!(event.getAction().equals(Action.RIGHT_CLICK_BLOCK) || event.getAction().equals(Action.RIGHT_CLICK_AIR))) return; - } else zombieKingAxe.setDurability((short) (zombieKingAxe.getDurability() + 4)); - ZombieKing.initializeFlamethrower(player.getLocation(), player.getLocation().getDirection(), player, true); - Cooldown.initialize(playersUsingFlamethrower, player, 3 * 60); - player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 3 * 20, 5)); + if (playersUsingFlamethrower.contains(player)) return; + + ItemStack zombieKingAxe = player.getInventory().getItemInMainHand(); + + if (hasCustomEnchantment(zombieKingAxe, "flamethrower")) { + + if (zombieKingAxe.getDurability() + 4 > zombieKingAxe.getType().getMaxDurability()) { + return; + } else zombieKingAxe.setDurability((short) (zombieKingAxe.getDurability() + 4)); + + + doFlamethrowerPhase1(player, player.getTargetBlock(null, 30).getLocation().clone().add(0.5, 1, 0.5)); + CooldownHandler.initialize(playersUsingFlamethrower, player, 3 * 60); + player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 5 * 20, 20)); + + } + + } + + private void doFlamethrowerPhase1(Player player, Location targetLocation) { + + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + + if (!player.isValid() || !player.getLocation().getWorld().equals(targetLocation.getWorld())) { + cancel(); + return; + } + + doParticleEffect(player, targetLocation, Particle.SMOKE_NORMAL); + counter++; + + if (counter < 20) return; + doFlamethrowerPhase2(player, targetLocation); + cancel(); + + } + + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); } + private void doParticleEffect(Player player, Location target, Particle particle) { + if (!player.getWorld().equals(target.getWorld())) return; + Vector directionVector = target.clone().subtract(player.getLocation()).toVector().normalize(); + for (int i = 0; i < 5; i++) { + player.getWorld().spawnParticle( + particle, + player.getEyeLocation().clone().add(directionVector.getX(), -0.5, directionVector.getZ()), + 0, + (ThreadLocalRandom.current().nextDouble() - 0.5) * 0.1 + directionVector.getX(), + (ThreadLocalRandom.current().nextDouble() - 0.5) * 0.1 + directionVector.getY(), + (ThreadLocalRandom.current().nextDouble() - 0.5) * 0.1 + directionVector.getZ(), + ThreadLocalRandom.current().nextDouble() + 0.05); + } + } + + /** + * Damage phase + * + * @param player + */ + private void doFlamethrowerPhase2(Player player, Location target) { + List damagePoints = generateDamagePoints(player, target); + new BukkitRunnable() { + int timer = 0; + + @Override + public void run() { + if (!player.isValid() || !player.getLocation().getWorld().equals(target.getWorld())) { + cancel(); + return; + } + doParticleEffect(player, target, Particle.FLAME); + if (timer % 10 == 0) + doDamage(damagePoints, player); + timer++; + if (timer < 20 * 3) return; + doFlamethrowerPhase3(player, target); + cancel(); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + } + + + /** + * Cooldown phase + * + * @param player + */ + private void doFlamethrowerPhase3(Player player, Location fixedPlayerLocation) { + new BukkitRunnable() { + int timer = 0; + + @Override + public void run() { + if (!player.isValid() || !player.getLocation().getWorld().equals(fixedPlayerLocation.getWorld())) { + cancel(); + return; + } + timer++; + doParticleEffect(player, fixedPlayerLocation, Particle.SMOKE_NORMAL); + if (timer < 20) return; + cancel(); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + } } } diff --git a/src/main/java/com/magmaguy/elitemobs/items/customenchantments/GrapplingHookEnchantment.java b/src/main/java/com/magmaguy/elitemobs/items/customenchantments/GrapplingHookEnchantment.java new file mode 100644 index 000000000..67c506906 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/items/customenchantments/GrapplingHookEnchantment.java @@ -0,0 +1,108 @@ +package com.magmaguy.elitemobs.items.customenchantments; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.items.ItemTagger; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.AbstractArrow; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityShootBowEvent; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +public class GrapplingHookEnchantment extends CustomEnchantment { + public static String key = "grappling_hook"; + + public GrapplingHookEnchantment() { + super(key, false); + } + + public static boolean isGrapplingHookProjectile(ItemMeta itemMeta) { + return ItemTagger.getEnchantment(itemMeta, key) > 0; + } + + public static void trackGrapplingHook(AbstractArrow arrow, Player player) { + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + if (counter > 20 * 10 || arrow.isInBlock()) { + if (arrow.getAttachedBlock() != null) { + Location targetBlock = getTargetBlock(arrow.getLocation()); + if (targetBlock != null) { + zipline(player, arrow.getAttachedBlock().getRelative(arrow.getFacing()).getLocation().add(new Vector(0.5, 0.5, 0.5))); + arrow.setPickupStatus(AbstractArrow.PickupStatus.DISALLOWED); + } + } + cancel(); + return; + } + counter++; + } + }.runTaskTimer(MetadataHandler.PLUGIN, 1, 1); + } + + private static void zipline(Player player, Location location) { + player.addPotionEffect(new PotionEffect(PotionEffectType.LEVITATION, 20 * 10, 1)); + new BukkitRunnable() { + int timer = 0; + + @Override + public void run() { + if (timer > 20 * 10 || player.getLocation().distance(location) < 1) { + player.setGravity(true); + player.removePotionEffect(PotionEffectType.LEVITATION); + player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW_FALLING, 20 * 3, 1)); + cancel(); + return; + } + player.setVelocity(location.clone().subtract(player.getLocation()).toVector().normalize().multiply(.5)); + timer++; + } + }.runTaskTimer(MetadataHandler.PLUGIN, 1L, 1L); + } + + private static Location getTargetBlock(Location airLocation) { + if (checkBlock(airLocation)) return airLocation; + Location up = airLocation.clone().add(new Vector(0, 1, 0)); + if (checkBlock(up)) return up; + Location down = airLocation.clone().add(new Vector(0, -1, 0)); + if (checkBlock(down)) return down; + Location front = airLocation.clone().add(new Vector(1, 0, 0)); + if (checkBlock(front)) return front; + Location back = airLocation.clone().add(new Vector(-1, 0, 0)); + if (checkBlock(back)) return back; + Location left = airLocation.clone().add(new Vector(0, 0, 1)); + if (checkBlock(left)) return left; + Location right = airLocation.clone().add(new Vector(0, 0, -1)); + if (checkBlock(right)) return right; + return null; + } + + private static boolean checkBlock(Location location) { + return location.getBlock().getType().equals(Material.TARGET); + } + + public static class GrapplingHookEnchantmentEvents implements Listener { + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) + public void onArrowFire(EntityShootBowEvent event) { + if (!(event.getEntity() instanceof Player)) return; + if (!event.getProjectile().getType().equals(EntityType.ARROW) && + !event.getProjectile().getType().equals(EntityType.SPECTRAL_ARROW)) return; + if (event.getConsumable() == null || !isGrapplingHookProjectile(event.getConsumable().getItemMeta())) + return; + ((AbstractArrow) event.getProjectile()).setBounce(false); + event.getEntity().setLeashHolder(event.getEntity()); + trackGrapplingHook((AbstractArrow) event.getProjectile(), (Player) event.getEntity()); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/items/customenchantments/HunterEnchantment.java b/src/main/java/com/magmaguy/elitemobs/items/customenchantments/HunterEnchantment.java index 893b7a639..a32a1b0d8 100644 --- a/src/main/java/com/magmaguy/elitemobs/items/customenchantments/HunterEnchantment.java +++ b/src/main/java/com/magmaguy/elitemobs/items/customenchantments/HunterEnchantment.java @@ -1,9 +1,23 @@ package com.magmaguy.elitemobs.items.customenchantments; +import com.magmaguy.elitemobs.playerdata.ElitePlayerInventory; +import org.bukkit.entity.Player; + +import java.util.List; + public class HunterEnchantment extends CustomEnchantment { - public String setKey() { - return "HUNTER"; + public static String key = "hunter"; + + public HunterEnchantment() { + super(key, false); + } + + public static double getHuntingGearBonus(List players) { + double huntingGearChanceAdder = 0; + for (Player player : players) + huntingGearChanceAdder += ElitePlayerInventory.playerInventories.get(player.getUniqueId()).getHunterChance(true); + return huntingGearChanceAdder; } } diff --git a/src/main/java/com/magmaguy/elitemobs/items/customenchantments/IceBreakerEnchantment.java b/src/main/java/com/magmaguy/elitemobs/items/customenchantments/IceBreakerEnchantment.java new file mode 100644 index 000000000..39413b3d8 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/items/customenchantments/IceBreakerEnchantment.java @@ -0,0 +1,95 @@ +package com.magmaguy.elitemobs.items.customenchantments; + +import org.bukkit.FluidCollisionMode; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.Vector; + +public class IceBreakerEnchantment extends CustomEnchantment { + + public static String key = "ice_breaker"; + + public IceBreakerEnchantment() { + super(key, false); + } + + private static boolean isValidBlock(Block block) { + if (block == null) + return false; + Material material = block.getType(); + return material.equals(Material.WATER) || + material.equals(Material.ICE) || + material.equals(Material.BLUE_ICE) || + material.equals(Material.FROSTED_ICE) || + material.equals(Material.PACKED_ICE); + } + + private static void freezeBlocks(Block block, ItemStack itemStack) { + switch (getCustomEnchantmentLevel(itemStack, key)) { + case 1: + freezeBlocks1(block, itemStack); + break; + case 2: + default: + freezeBlocks2(block, itemStack); + break; + } + } + + private static void freezeBlocks1(Block block, ItemStack itemStack) { + parseBlock(block, 0, 0, 0, itemStack); + } + + private static void freezeBlocks2(Block block, ItemStack itemStack) { + parseBlock(block, 0, 0, 0, itemStack); + parseBlock(block, 1, 0, 0, itemStack); + parseBlock(block, -1, 0, 0, itemStack); + parseBlock(block, 0, 1, 0, itemStack); + parseBlock(block, 0, -1, 0, itemStack); + parseBlock(block, 0, 0, 1, itemStack); + parseBlock(block, 0, 0, -1, itemStack); + } + + private static void parseBlock(Block block, int x, int y, int z, ItemStack itemStack) { + Block newBlock = block.getLocation().clone().add(new Vector(x, y, z)).getBlock(); + if (!newBlock.getType().equals(Material.WATER)) + return; + + newBlock.setType(Material.ICE); + itemStack.setDurability((short) (itemStack.getDurability() + 1)); + } + + public static class IceBreakerEnchantmentEvent implements Listener { + + @EventHandler + public void onInteract(PlayerInteractEvent event) { + ItemStack mainHandItem = event.getPlayer().getInventory().getItemInMainHand(); + if (!hasCustomEnchantment(mainHandItem, IceBreakerEnchantment.key)) return; + + if (event.getPlayer().rayTraceBlocks(6, FluidCollisionMode.ALWAYS) == null) return; + + Block block = event.getPlayer().rayTraceBlocks(6, FluidCollisionMode.ALWAYS).getHitBlock(); + + if (!isValidBlock(block)) return; + + freezeBlocks(block, mainHandItem); + } + + @EventHandler + public void onMine(BlockBreakEvent event) { + if (event.isCancelled()) return; + if (!isValidBlock(event.getBlock())) return; + ItemStack mainHandItem = event.getPlayer().getInventory().getItemInMainHand(); + if (!hasCustomEnchantment(mainHandItem, IceBreakerEnchantment.key)) return; + freezeBlocks(event.getBlock(), mainHandItem); + event.getBlock().setType(Material.AIR); + } + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/items/customenchantments/LightningEnchantment.java b/src/main/java/com/magmaguy/elitemobs/items/customenchantments/LightningEnchantment.java new file mode 100644 index 000000000..49059e27f --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/items/customenchantments/LightningEnchantment.java @@ -0,0 +1,56 @@ +package com.magmaguy.elitemobs.items.customenchantments; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerEvent; +import com.magmaguy.elitemobs.collateralminecraftchanges.LightningSpawnBypass; +import com.magmaguy.elitemobs.config.enchantments.premade.LightningConfig; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.playerdata.ElitePlayerInventory; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; + +import java.util.HashSet; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.ThreadLocalRandom; + +public class LightningEnchantment extends CustomEnchantment { + public static final String key = "lightning"; + + public LightningEnchantment() { + super(key, false); + } + + public static void playerLightning(Player player, Location location) { + LightningSpawnBypass.bypass(); + Objects.requireNonNull(location.getWorld()).strikeLightningEffect(location); + location.getWorld().getNearbyEntities(location, 2.5, 2.5, 2.5).forEach((entity -> { + EliteEntity eliteEntity = EntityTracker.getEliteMobEntity(entity); + if (eliteEntity == null) return; + double damage = ElitePlayerInventory.playerInventories.get(player.getUniqueId()).getWeaponTier(true) * 2.5; + eliteEntity.damage(damage); + })); + } + + public static class LightningEnchantmentEvents implements Listener { + private static final Set playersInCooldown = new HashSet<>(); + + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH) + public void onEntityDamagedByPlayer(EliteMobDamagedByPlayerEvent event) { + if (event.getPlayer().hasMetadata("NPC") || + ElitePlayerInventory.playerInventories.containsKey(event.getPlayer().getUniqueId())) return; + if (playersInCooldown.contains(event.getPlayer())) return; + double lightningChance = ElitePlayerInventory.playerInventories.get(event.getPlayer().getUniqueId()).getLightningChance(true); + if (lightningChance <= 0) return; + if (lightningChance >= ThreadLocalRandom.current().nextDouble()) return; + playersInCooldown.add(event.getPlayer()); + Bukkit.getScheduler().runTaskLater(MetadataHandler.PLUGIN, () -> playersInCooldown.remove(event.getPlayer()), LightningConfig.minimumCooldown * 20L); + playerLightning(event.getPlayer(), event.getEliteMobEntity().getLivingEntity().getLocation()); + } + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/items/customenchantments/MeteorShowerEnchantment.java b/src/main/java/com/magmaguy/elitemobs/items/customenchantments/MeteorShowerEnchantment.java new file mode 100644 index 000000000..fdc0cae8f --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/items/customenchantments/MeteorShowerEnchantment.java @@ -0,0 +1,90 @@ +package com.magmaguy.elitemobs.items.customenchantments; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.items.ItemTagger; +import org.bukkit.Location; +import org.bukkit.NamespacedKey; +import org.bukkit.Particle; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Fireball; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import java.util.concurrent.ThreadLocalRandom; + +public class MeteorShowerEnchantment extends CustomEnchantment { + + public static String key = "meteor_shower"; + + public MeteorShowerEnchantment() { + super(key, false); + } + + public static void doMeteorShower(Player player) { + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + + if (!player.isValid()) { + cancel(); + return; + } + + if (counter > 10 * 20) { + cancel(); + return; + } + + counter++; + + doCloudEffect(player.getLocation().clone().add(new Vector(0, 10, 0))); + + if (counter > 2 * 20) { + + doFireballs(player.getLocation().clone().add(new Vector(0, 10, 0)), player); + + } + + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + } + + private static void doCloudEffect(Location location) { + for (int i = 0; i < 1; i++) { + int randX = ThreadLocalRandom.current().nextInt(30) - 15; + int randY = ThreadLocalRandom.current().nextInt(2); + int randZ = ThreadLocalRandom.current().nextInt(30) - 15; + Location newLocation = location.clone().add(new Vector(randX, randY, randZ)); + location.getWorld().spawnParticle(Particle.EXPLOSION_HUGE, newLocation, 1, 0, 0, 0, 0); + } + } + + private static void doFireballs(Location location, Player player) { + for (int i = 0; i < 1; i++) { + int randX = ThreadLocalRandom.current().nextInt(30) - 15; + int randY = ThreadLocalRandom.current().nextInt(2); + int randZ = ThreadLocalRandom.current().nextInt(30) - 15; + Location newLocation = location.clone().add(new Vector(randX, randY, randZ)); + newLocation = newLocation.setDirection(new Vector(ThreadLocalRandom.current().nextDouble() - 0.5, -1, ThreadLocalRandom.current().nextDouble() - 0.5)); + Fireball fireball = (Fireball) location.getWorld().spawnEntity(newLocation, EntityType.FIREBALL); + fireball.setShooter(player); + } + } + + public static class MeteorShowerEvents implements Listener { + @EventHandler + public void onInteract(PlayerInteractEvent event) { + int meteorShower = ItemTagger.getEnchantment(event.getPlayer().getInventory().getItemInMainHand().getItemMeta(), new NamespacedKey(MetadataHandler.PLUGIN, MeteorShowerEnchantment.key)); + if (meteorShower < 1) return; + event.getItem().setAmount(event.getItem().getAmount() - 1); + MeteorShowerEnchantment.doMeteorShower(event.getPlayer()); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/items/customenchantments/PlasmaBootsEnchantment.java b/src/main/java/com/magmaguy/elitemobs/items/customenchantments/PlasmaBootsEnchantment.java new file mode 100644 index 000000000..4d3619fee --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/items/customenchantments/PlasmaBootsEnchantment.java @@ -0,0 +1,138 @@ +package com.magmaguy.elitemobs.items.customenchantments; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.playerdata.ElitePlayerInventory; +import org.bukkit.Bukkit; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerToggleSneakEvent; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import java.util.HashSet; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.ThreadLocalRandom; + +public class PlasmaBootsEnchantment extends CustomEnchantment { + public static String key = "plasma_boots"; + + public PlasmaBootsEnchantment() { + super(key, false); + } + + public static void doPlasmaBootsEnchantment(int level, Player player) { + player.setVelocity(new Vector(0, .8, 0)); + Bukkit.getScheduler().runTaskTimer(MetadataHandler.PLUGIN, (task) -> { + if (!player.isValid() || !player.getLocation().clone().subtract(new Vector(0, 1, 0)).getBlock().isPassable() + && player.getLocation().getY() - player.getLocation().getBlock().getY() < 0.1 || !player.getLocation().clone().getBlock().isPassable()) { + task.cancel(); + doLanding(level, player); + return; + } + player.getWorld().spawnParticle(Particle.REDSTONE, player.getLocation().getX(), player.getLocation().getY(), player.getLocation().getZ(), + 20, 0.1, 0.1, 0.1, 1, new Particle.DustOptions(Color.fromRGB( + ThreadLocalRandom.current().nextInt(0, 100), + ThreadLocalRandom.current().nextInt(122, 255), + ThreadLocalRandom.current().nextInt(0, 100) + ), 1)); + }, 5, 1); + } + + private static void doLanding(int level, Player player) { + for (int i = 1; i < level + 1; i++) + doProjectileArray(i, player); + } + + private static void doProjectileArray(int level, Player player) { + double height = (level + .2 - 1) / 2; + Vector vector = new Vector(1, height, 0); + for (int i = 0; i < 8; i++) { + Vector offsetVector = vector.rotateAroundY(i * Math.PI / 4); + Location shotLocation = player.getLocation().clone().add(offsetVector); + Vector shotVector = shotLocation.clone().subtract(player.getLocation()).toVector().normalize().multiply(0.2); + createProjectile(shotVector, shotLocation, player); + } + } + + private static void createProjectile(Vector shotVector, Location sourceLocation, Player player) { + new BukkitRunnable() { + final Location currentLocation = sourceLocation.clone(); + int counter = 0; + + @Override + public void run() { + if (counter > 20 * 3) { + cancel(); + return; + } + counter++; + for (Entity entity : Objects.requireNonNull(currentLocation.getWorld()) + .getNearbyEntities(currentLocation, 0.1, 0.1, 0.1)) { + if (!(entity instanceof LivingEntity)) continue; + if (entity.getType().equals(EntityType.PLAYER)) continue; + cancel(); + doDamage(player, (LivingEntity) entity); + break; + } + + doVisualEffect(currentLocation); + + currentLocation.add(shotVector); + if (!currentLocation.getBlock().isPassable()) { + cancel(); + } + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + } + + private static void doDamage(Player player, LivingEntity livingEntity) { + livingEntity.damage(2, player); + } + + private static void doVisualEffect(Location currentLocation) { + Objects.requireNonNull(currentLocation.getWorld()) + .spawnParticle(Particle.REDSTONE, currentLocation.getX(), currentLocation.getY(), currentLocation.getZ(), + 5, 0.1, 0.1, 0.1, 1, new Particle.DustOptions(Color.fromRGB( + ThreadLocalRandom.current().nextInt(0, 100), + ThreadLocalRandom.current().nextInt(122, 255), + ThreadLocalRandom.current().nextInt(0, 100)), + 1)); + } + + public static class PlasmaBootsEnchantmentEvents implements Listener { + private static final HashSet players = new HashSet<>(); + private static final HashSet cooldownPlayers = new HashSet<>(); + + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH) + public void onSneak(PlayerToggleSneakEvent event) { + if (!event.isSneaking()) return; + if (event.getPlayer().isFlying()) return; + if (cooldownPlayers.contains(event.getPlayer().getUniqueId())) return; + //todo: don't check this event if the power is disabled + if (ElitePlayerInventory.playerInventories.get(event.getPlayer().getUniqueId()) == null) return; + double plasmaBootLevel = ElitePlayerInventory.playerInventories.get(event.getPlayer().getUniqueId()).getPlasmaBootsLevel(true); + if (plasmaBootLevel < 1) return; + if (!players.contains(event.getPlayer().getUniqueId())) { + players.add(event.getPlayer().getUniqueId()); + Bukkit.getScheduler().runTaskLater(MetadataHandler.PLUGIN, task -> players.remove(event.getPlayer().getUniqueId()), 10); + return; + } + players.remove(event.getPlayer().getUniqueId()); + cooldownPlayers.add(event.getPlayer().getUniqueId()); + Bukkit.getScheduler().runTaskLater(MetadataHandler.PLUGIN, task -> cooldownPlayers.remove(event.getPlayer().getUniqueId()), 20L * 60 * 2); + + doPlasmaBootsEnchantment((int) plasmaBootLevel, event.getPlayer()); + + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/items/customenchantments/SoulbindEnchantment.java b/src/main/java/com/magmaguy/elitemobs/items/customenchantments/SoulbindEnchantment.java new file mode 100644 index 000000000..1fc333fbf --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/items/customenchantments/SoulbindEnchantment.java @@ -0,0 +1,146 @@ +package com.magmaguy.elitemobs.items.customenchantments; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.adventurersguild.GuildRank; +import com.magmaguy.elitemobs.api.internal.RemovalReason; +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfig; +import com.magmaguy.elitemobs.config.enchantments.premade.SoulbindConfig; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.items.EliteItemLore; +import com.magmaguy.elitemobs.utils.VisualArmorStand; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.NamespacedKey; +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.Item; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerPickupItemEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.persistence.PersistentDataType; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import java.util.UUID; + +public class SoulbindEnchantment extends CustomEnchantment { + + public static final NamespacedKey PRESTIGE_KEY = new NamespacedKey(MetadataHandler.PLUGIN, "prestige"); + public static String key = "soulbind"; + public static final NamespacedKey SOULBIND_KEY = new NamespacedKey(MetadataHandler.PLUGIN, key); + public static boolean isEnabled; + + public SoulbindEnchantment() { + super(key, true); + } + + public static ItemStack addEnchantment(ItemStack itemStack, Player player) { + isEnabled = EnchantmentsConfig.getEnchantment(SoulbindEnchantment.key + ".yml").isEnabled(); + if (!isEnabled) return null; + if (itemStack == null || player == null) return null; + ItemMeta itemMeta = itemStack.getItemMeta(); + itemMeta.getPersistentDataContainer().set(SOULBIND_KEY, PersistentDataType.STRING, player.getUniqueId().toString()); + setPrestigeLevel(itemMeta, GuildRank.getGuildPrestigeRank(player)); + itemStack.setItemMeta(itemMeta); + return itemStack; + } + + public static void removeEnchantment(ItemStack itemStack) { + if (itemStack == null) return; + ItemMeta itemMeta = itemStack.getItemMeta(); + itemMeta.getPersistentDataContainer().remove(SOULBIND_KEY); + itemStack.setItemMeta(itemMeta); + //update item lore display + new EliteItemLore(itemStack, false); + } + + public static void addPhysicalDisplay(Item item, Player player) { + new BukkitRunnable() { + @Override + public void run() { + if (item == null) + return; + ArmorStand soulboundPlayer = VisualArmorStand.VisualArmorStand(item.getLocation().clone().add(new Vector(0, -50, 0)), ChatColorConverter.convert( + SoulbindConfig.hologramStrings.replace("$player", player.getDisplayName()))); + new BukkitRunnable() { + final Location lastLocation = item.getLocation().clone(); + int counter = 0; + + @Override + public void run() { + counter++; + if (counter > 20 * 60 * 5 || !item.isValid()) { + cancel(); + EntityTracker.unregister(soulboundPlayer, RemovalReason.EFFECT_TIMEOUT); + return; + } + if (!lastLocation.equals(item.getLocation())) + soulboundPlayer.teleport(item.getLocation().clone().add(new Vector(0, 0.5, 0))); + if (counter == 1) + soulboundPlayer.teleport(item.getLocation().clone().add(new Vector(0, 0.5, 0))); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 1, 1); + } + }.runTaskLater(MetadataHandler.PLUGIN, 20 * 3); + } + + public static boolean isValidSoulbindUser(ItemMeta itemMeta, Player player) { + if (!isEnabled) return true; + if (player.hasPermission("elitemobs.soulbind.bypass")) return true; + if (itemMeta == null) + return true; + if (!itemMeta.getPersistentDataContainer().has(SOULBIND_KEY, PersistentDataType.STRING)) + return true; + if (GuildRank.getGuildPrestigeRank(player) == 0) + return itemMeta.getPersistentDataContainer().get(new NamespacedKey(MetadataHandler.PLUGIN, key), PersistentDataType.STRING).equals(player.getUniqueId().toString()); + //this is kept for legacy reasons, old items just appended the prestige tier at the end of the uuid + else if ((itemMeta.getPersistentDataContainer().get(new NamespacedKey(MetadataHandler.PLUGIN, key), PersistentDataType.STRING)).equals(player.getUniqueId().toString() + GuildRank.getGuildPrestigeRank(player))) + return true; + else + return getPrestigeLevel(itemMeta) == GuildRank.getGuildPrestigeRank(player) && + itemMeta.getPersistentDataContainer().get(new NamespacedKey(MetadataHandler.PLUGIN, key), PersistentDataType.STRING).equals(player.getUniqueId().toString()); + } + + public static Player getSoulboundPlayer(ItemMeta itemMeta) { + if (!itemMeta.getPersistentDataContainer().has(SOULBIND_KEY, PersistentDataType.STRING)) + return null; + try { + UUID uuid = UUID.fromString(itemMeta.getPersistentDataContainer().get(new NamespacedKey(MetadataHandler.PLUGIN, key), PersistentDataType.STRING)); + return Bukkit.getPlayer(uuid); + } catch (Exception ex) { + + } + return null; + //return Bukkit.getPlayer(UUID.fromString(itemMeta.getPersistentDataContainer().get(new NamespacedKey(MetadataHandler.PLUGIN, key), PersistentDataType.STRING))); + } + + public static boolean itemHasSoulbindEnchantment(ItemMeta itemMeta) { + return itemMeta.getPersistentDataContainer().has(SOULBIND_KEY, PersistentDataType.STRING); + } + + private static void setPrestigeLevel(ItemMeta itemMeta, int prestigeLevel) { + itemMeta.getPersistentDataContainer().set(PRESTIGE_KEY, PersistentDataType.INTEGER, prestigeLevel); + } + + public static int getPrestigeLevel(ItemMeta itemMeta) { + if (!itemMeta.getPersistentDataContainer().has(SOULBIND_KEY, PersistentDataType.STRING)) + return 0; + int prestige = 0; + if (itemMeta.getPersistentDataContainer().get(PRESTIGE_KEY, PersistentDataType.INTEGER) != null) + prestige = itemMeta.getPersistentDataContainer().get(PRESTIGE_KEY, PersistentDataType.INTEGER); + return prestige; + } + + public static class SoulbindEnchantmentEvents implements Listener { + @EventHandler(priority = EventPriority.LOWEST) + public void onPickup(PlayerPickupItemEvent event) { + if (isValidSoulbindUser(event.getItem().getItemStack().getItemMeta(), event.getPlayer())) return; + event.setCancelled(true); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/items/customenchantments/SummonMerchantEnchantment.java b/src/main/java/com/magmaguy/elitemobs/items/customenchantments/SummonMerchantEnchantment.java new file mode 100644 index 000000000..c2925467b --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/items/customenchantments/SummonMerchantEnchantment.java @@ -0,0 +1,102 @@ +package com.magmaguy.elitemobs.items.customenchantments; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfig; +import com.magmaguy.elitemobs.items.ItemTagger; +import com.magmaguy.elitemobs.npcs.NPCEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.AsyncPlayerChatEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.ArrayList; +import java.util.List; + +public class SummonMerchantEnchantment extends CustomEnchantment implements Listener { + + private static final String merchantMessage = EnchantmentsConfig.getEnchantment("summon_merchant.yml").getFileConfiguration().getString("message"); + public static String key = "summon_merchant"; + + public SummonMerchantEnchantment() { + super(key, false); + } + + /** + * If the value is 0, it means that the enchantment isn't present + */ + private static int getEnchantment(ItemMeta itemMeta) { + return ItemTagger.getEnchantment(itemMeta, key); + } + + /** + * Summons the merchant + * + * @param player + */ + public static void doSummonMerchant(Player player, boolean fromMessage, ItemStack itemStack) { + if (itemStack != null) + itemStack.setAmount(itemStack.getAmount() - 1); + if (!fromMessage) { + new NPCEntity(player.getLocation()); + if (!merchantMessage.isEmpty()) + player.chat(ChatColorConverter.convert(merchantMessage)); + return; + } + //pass to a sync task + new BukkitRunnable() { + @Override + public void run() { + new NPCEntity(player.getLocation()); + } + }.runTask(MetadataHandler.PLUGIN); + } + + public static class SummonMerchantEvents implements Listener { + private static final List playerCooldowns = new ArrayList<>(); + + @EventHandler + public void onItemInteract(PlayerInteractEvent event) { + if (!(event.getAction().equals(Action.RIGHT_CLICK_AIR) || event.getAction().equals(Action.RIGHT_CLICK_BLOCK))) + return; + if (getEnchantment(event.getPlayer().getInventory().getItemInMainHand().getItemMeta()) < 1) + return; + if (playerCooldowns.contains(event.getPlayer())) return; + playerCooldowns.add(event.getPlayer()); + new BukkitRunnable() { + @Override + public void run() { + playerCooldowns.remove(event.getPlayer()); + } + }.runTaskLater(MetadataHandler.PLUGIN, 20 * 60); + doSummonMerchant(event.getPlayer(), false, event.getPlayer().getInventory().getItemInMainHand()); + } + + @EventHandler + public void onPlayerChat(AsyncPlayerChatEvent event) { + if (merchantMessage.isEmpty()) return; + if (event.getMessage().equalsIgnoreCase(merchantMessage)) { + if (playerCooldowns.contains(event.getPlayer())) return; + playerCooldowns.add(event.getPlayer()); + new BukkitRunnable() { + @Override + public void run() { + playerCooldowns.remove(event.getPlayer()); + } + }.runTaskLater(MetadataHandler.PLUGIN, 20 * 60); + for (ItemStack itemStack : event.getPlayer().getInventory()) + if (itemStack != null) + if (getEnchantment(itemStack.getItemMeta()) > 0) { + doSummonMerchant(event.getPlayer(), true, itemStack); + return; + } + } + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/items/customenchantments/SummonWolfEnchantment.java b/src/main/java/com/magmaguy/elitemobs/items/customenchantments/SummonWolfEnchantment.java new file mode 100644 index 000000000..496f8e3df --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/items/customenchantments/SummonWolfEnchantment.java @@ -0,0 +1,93 @@ +package com.magmaguy.elitemobs.items.customenchantments; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.items.ItemTagger; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import com.magmaguy.elitemobs.playerdata.ElitePlayerInventory; +import com.magmaguy.elitemobs.utils.WarningMessage; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.entity.Wolf; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +public class SummonWolfEnchantment extends CustomEnchantment { + + public static final String key = "summon_wolf"; + + public SummonWolfEnchantment() { + super(key, false); + } + + public static void summonWolf(Player player, ItemStack itemStack) { + Wolf wolf; + if (itemStack != null) + itemStack.setAmount(itemStack.getAmount() - 1); + if (ThreadLocalRandom.current().nextDouble() < 1D / 1000D) + wolf = summonSnoopy(player); + else + wolf = summonGenericWolf(player); + if (wolf == null) return; + wolf.setAngry(false); + wolf.setOwner(player); + } + + private static Wolf summonGenericWolf(Player player) { + CustomBossEntity customBossEntity = CustomBossEntity.createCustomBossEntity("summonable_wolf.yml"); + customBossEntity.setSpawnLocation(player.getLocation()); + customBossEntity.setLevel(ElitePlayerInventory.playerInventories.get(player.getUniqueId()).getFullPlayerTier(true)); + customBossEntity.spawn(false); + if (customBossEntity.getCustomBossesConfigFields().getEntityType() != EntityType.WOLF) { + new WarningMessage("snoopy.yml boss file was not set to a wolf entity type! It must be a wolf for the summon mechanic to work correctly!"); + return null; + } + return (Wolf) customBossEntity.getLivingEntity(); + } + + private static Wolf summonSnoopy(Player player) { + CustomBossEntity customBossEntity = CustomBossEntity.createCustomBossEntity("summonable_wolf.yml"); + customBossEntity.setSpawnLocation(player.getLocation()); + customBossEntity.setLevel(ElitePlayerInventory.playerInventories.get(player.getUniqueId()).getFullPlayerTier(true)); + if (customBossEntity.getLivingEntity().getType() != EntityType.WOLF) { + new WarningMessage("snoopy.yml boss file was not set to a wolf entity type! It must be a wolf for the summon mechanic to work correctly!"); + return null; + } + return (Wolf) customBossEntity.getLivingEntity(); + } + + private static int getEnchantment(ItemMeta itemMeta) { + return ItemTagger.getEnchantment(itemMeta, key); + } + + public static class SummonWolfEnchantmentEvent implements Listener { + private static final List playerCooldowns = new ArrayList<>(); + + @EventHandler(ignoreCancelled = true) + public void onRightClick(PlayerInteractEvent event) { + if (playerCooldowns.contains(event.getPlayer())) return; + playerCooldowns.add(event.getPlayer()); + new BukkitRunnable() { + @Override + public void run() { + playerCooldowns.remove(event.getPlayer()); + } + }.runTaskLater(MetadataHandler.PLUGIN, 20 * 60L); + if (!(event.getAction().equals(Action.RIGHT_CLICK_AIR) || event.getAction().equals(Action.RIGHT_CLICK_BLOCK))) + return; + if (getEnchantment(event.getPlayer().getInventory().getItemInMainHand().getItemMeta()) > 0) + summonWolf(event.getPlayer(), event.getPlayer().getInventory().getItemInMainHand()); + if (getEnchantment(event.getPlayer().getInventory().getItemInOffHand().getItemMeta()) > 0) + summonWolf(event.getPlayer(), event.getPlayer().getInventory().getItemInOffHand()); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/items/customenchantments/UnbindEnchantment.java b/src/main/java/com/magmaguy/elitemobs/items/customenchantments/UnbindEnchantment.java new file mode 100644 index 000000000..c304f40b8 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/items/customenchantments/UnbindEnchantment.java @@ -0,0 +1,48 @@ +package com.magmaguy.elitemobs.items.customenchantments; + +import com.magmaguy.elitemobs.items.EliteItemLore; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +public class UnbindEnchantment extends CustomEnchantment { + public static String key = "unbind"; + + public UnbindEnchantment() { + super(key, true); + } + + public static ItemStack unbindItem(ItemStack itemStack) { + ItemStack newItemStack = itemStack.clone(); + ItemMeta itemMeta = newItemStack.getItemMeta(); + itemMeta.getPersistentDataContainer().remove(SoulbindEnchantment.SOULBIND_KEY); + itemMeta.getPersistentDataContainer().remove(SoulbindEnchantment.PRESTIGE_KEY); + newItemStack.setItemMeta(itemMeta); + new EliteItemLore(newItemStack, false); + return newItemStack; + } + + /* + public static class UnbindEvents implements Listener { + @EventHandler (ignoreCancelled = true) + public void onItemPlace(PrepareAnvilEvent event) { + if (event.getInventory().getItem(0) == null || + event.getInventory().getItem(0).getType().equals(Material.AIR) || + event.getInventory().getItem(1) == null || + event.getInventory().getItem(1).getType().equals(Material.AIR)) + return; + if (ItemTagger.getEnchantment(event.getInventory().getItem(0).getItemMeta(), key) > 0 && + SoulbindEnchantment.itemHasSoulbindEnchantment(event.getInventory().getItem(1).getItemMeta())) { + event.setResult(unbindItem(event.getInventory().getItem(1))); + event.getInventory().setRepairCost(39); + } else if (ItemTagger.getEnchantment(event.getInventory().getItem(1).getItemMeta(), key) > 0 && + SoulbindEnchantment.itemHasSoulbindEnchantment(event.getInventory().getItem(0).getItemMeta())) { + event.setResult(unbindItem(event.getInventory().getItem(0))); + event.getInventory().setRepairCost(39); + } + + } + } + + */ + +} diff --git a/src/main/java/com/magmaguy/elitemobs/items/customitems/CustomItem.java b/src/main/java/com/magmaguy/elitemobs/items/customitems/CustomItem.java new file mode 100644 index 000000000..2cb993ede --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/items/customitems/CustomItem.java @@ -0,0 +1,478 @@ +package com.magmaguy.elitemobs.items.customitems; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.adventurersguild.GuildRank; +import com.magmaguy.elitemobs.config.AdventurersGuildConfig; +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfig; +import com.magmaguy.elitemobs.config.customitems.CustomItemsConfigFields; +import com.magmaguy.elitemobs.items.ItemTierFinder; +import com.magmaguy.elitemobs.items.LootTables; +import com.magmaguy.elitemobs.items.ScalableItemConstructor; +import com.magmaguy.elitemobs.items.customenchantments.*; +import com.magmaguy.elitemobs.items.itemconstructor.ItemConstructor; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.utils.WarningMessage; +import lombok.Getter; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Item; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.persistence.PersistentDataType; + +import java.util.*; + +public class CustomItem { + + private static final HashMap customItems = new HashMap<>(); + // Used to get loot via commands + private static final ArrayList customItemStackList = new ArrayList<>(); + // Used to get loot via custom shop, used for efficiency (avoids the double calc of the lore) + private static final ArrayList customItemStackShopList = new ArrayList<>(); + // Used to drop static loot using the weighed chance system + private static final HashMap weighedFixedItems = new HashMap<>(); + private static final HashMap> tieredLoot = new HashMap<>(); + private static final HashMap> fixedItems = new HashMap<>(); + private static final List scalableItems = new ArrayList<>(); + private static final HashMap> limitedItems = new HashMap<>(); + private final CustomItemsConfigFields customItemsConfigFields; + private final HashMap enchantments = new HashMap<>(); + private final HashMap customEnchantments = new HashMap<>(); + @Getter + private final String permission; + private String fileName; + private boolean isEnabled = true; + private Material material; + private String name; + private List lore = new ArrayList<>(); + private List potionEffects = new ArrayList<>(); + private int itemTier; + private double dropWeight = 0; + private Scalability scalability; + private ItemType itemType; + + /** + * Generates a CustomItem object. This holds values for limited and dynamic items until a tier is determined for them. + * + * @param customItemsConfigFields Config fields upon which the values are based. + */ + public CustomItem(CustomItemsConfigFields customItemsConfigFields) { + this.customItemsConfigFields = customItemsConfigFields; + this.permission = customItemsConfigFields.getPermission(); + parseFileName(); + if (!parseIsEnabled()) return; + if (!parseMaterial()) return; + parseName(); + parseLore(); + parseEnchantments(); + parsePotionEffects(); + parseItemType(); + parseItemTier(); + //give getloot menu items to work with + addCustomItem(getFileName(), this); + addCustomItem(this); + addTieredLoot(this); + if (parseDropWeight()) { + //item is weighed and fixed + addFixedItem(this); + addWeighedFixedItems(this); + this.scalability = Scalability.FIXED; + return; + } + parseScalability(); + } + + public static HashMap getCustomItems() { + return customItems; + } + + public static CustomItem getCustomItem(String fileName) { + if (!fileName.contains(".yml")) fileName += ".yml"; + if (!customItems.containsKey(fileName)) + return null; + return customItems.get(fileName); + } + + /* + public static Item dropPlayerLoot(Player player, int tier, String customItemFileName, Location location) { + CustomItem customItem = getCustomItem(customItemFileName); + if (customItem == null) return null; + return customItem.dropPlayerLoot(player, tier, location); + } + */ + + private static void addCustomItem(String fileName, CustomItem customItem) { + customItems.put(fileName, customItem); + } + + public static ArrayList getCustomItemStackShopList() { + return customItemStackShopList; + } + + /** + * Returns a full list of custom items using their configuration settings + * + * @return + */ + public static ArrayList getCustomItemStackList() { + return customItemStackList; + } + + // Adds custom items to the list used by the getloot GUI + private static void addCustomItem(CustomItem customItem) { + customItemStackList.add(customItem.generateDefaultsItemStack(null, false, null)); + if (customItem.getItemType().equals(ItemType.UNIQUE)) return; + customItemStackShopList.add(customItem.generateDefaultsItemStack(null, true, null)); + } + + /** + * Returns a full list of weighed static items to be used in the looting process + * + * @return + */ + public static HashMap getWeighedFixedItems() { + return weighedFixedItems; + } + + // Adds weighed static items + private static void addWeighedFixedItems(CustomItem customItem) { + ItemStack itemStack = customItem.generateDefaultsItemStack(null, false, null); + weighedFixedItems.put(itemStack, customItem.getDropWeight()); + } + + public static HashMap> getTieredLoot() { + return tieredLoot; + } + + public static void addTieredLoot(CustomItem customItem) { + ItemStack itemStack = customItem.generateDefaultsItemStack(null, false, null); + int itemTier = customItem.getItemTier(); + + if (tieredLoot.get(itemTier) == null) + tieredLoot.put(itemTier, new ArrayList<>(Collections.singletonList(itemStack))); + + else { + ArrayList list = tieredLoot.get(itemTier); + list.add(itemStack); + tieredLoot.put(itemTier, list); + } + } + + public static HashMap> getFixedItems() { + return fixedItems; + } + + private static void addFixedItem(CustomItem customItem) { + if (fixedItems.get(customItem.getItemTier()) == null || fixedItems.get(customItem.getItemTier()).isEmpty()) + fixedItems.put(customItem.getItemTier(), new ArrayList<>(Collections.singletonList(customItem))); + else + fixedItems.get(customItem.getItemTier()).add(customItem); + } + + public static List getScalableItems() { + return scalableItems; + } + + public static HashMap> getLimitedItem() { + return limitedItems; + } + + private static void addLimitedItem(CustomItem customItem) { + if (limitedItems.get(customItem.getItemTier()) == null || limitedItems.get(customItem.getItemTier()).isEmpty()) + limitedItems.put(customItem.getItemTier(), new ArrayList<>(Collections.singletonList(customItem))); + else + limitedItems.get(customItem.getItemTier()).add(customItem); + } + + /** + * Initializes all config items on startup. Needs to run after the config initialization as it relies on those values. + */ + public static void initializeCustomItems() { + for (CustomItemsConfigFields configFields : CustomItemsConfig.getCustomItems().values()) + try { + new CustomItem(configFields); + } catch (Exception ex) { + new WarningMessage("Failed to generate custom item in file " + configFields.getFilename() + " !"); + ex.printStackTrace(); + } + } + + public Item dropPlayerLoot(Player player, int tier, Location location, EliteEntity eliteEntity) { + if (!permission.isEmpty() && !player.hasPermission(permission)) return null; + Item loot = null; + int itemTier = 0; + + if (AdventurersGuildConfig.isGuildLootLimiter()) { + itemTier = (int) LootTables.setItemTier(tier); + if (itemTier > GuildRank.getActiveGuildRank(player) * 10) + itemTier = GuildRank.getActiveGuildRank(player) * 10; + } else + itemTier = tier + 1; + + switch (getScalability()) { + case LIMITED: + loot = location.getWorld().dropItem(location, + ScalableItemConstructor.constructLimitedItem(itemTier, this, player, eliteEntity)); + break; + case SCALABLE: + loot = location.getWorld().dropItem(location, + ScalableItemConstructor.constructScalableItem(itemTier + 1, this, player, eliteEntity)); + break; + case FIXED: + loot = location.getWorld().dropItem(location, + generateItemStack(itemTier + 1, player, eliteEntity)); + default: + } + + SoulbindEnchantment.addPhysicalDisplay(loot, player); + loot.setCustomName(loot.getItemStack().getItemMeta().getDisplayName()); + loot.setCustomNameVisible(true); + + return loot; + } + + private void parseFileName() { + this.fileName = this.customItemsConfigFields.getFilename(); + } + + private boolean parseIsEnabled() { + return this.isEnabled = this.customItemsConfigFields.isEnabled(); + } + + private boolean parseMaterial() { + this.material = this.customItemsConfigFields.getMaterial(); + return material != null; + } + + private void parseName() { + this.name = this.customItemsConfigFields.getName(); + } + + private void parseLore() { + this.lore = this.customItemsConfigFields.getLore(); + } + + private void parseEnchantments() { + for (String string : this.customItemsConfigFields.getEnchantments()) + try { + String name = string.split(",")[0]; + int level = 1; + try { + level = Integer.parseInt(string.split(",")[1]); + } catch (Exception ex) { + Bukkit.getLogger().warning("[EliteMobs] Custom Item Entry " + this.fileName + " has an invalid enchantment entry."); + Bukkit.getLogger().warning("[EliteMobs} Enchantment " + name + " is missing a level."); + Bukkit.getLogger().warning("[EliteMobs] Reminder - The correct format for these is [enchantmentName],[level]"); + Bukkit.getLogger().warning("[EliteMobs] The name should follow the API names and the level should be above 0."); + Bukkit.getLogger().warning("[EliteMobs] Defaulting " + name + " to level 1."); + } +/* + for (CustomEnchantment customEnchantment : CustomEnchantment.getCustomEnchantments()) + if (customEnchantment.key.equalsIgnoreCase(name)){ + customEnchantments.put(name.toLowerCase(), level); + break; + } +*/ + + if (name.equalsIgnoreCase(HunterEnchantment.key) || + name.equalsIgnoreCase(FlamethrowerEnchantment.key) || + name.equalsIgnoreCase(CriticalStrikesEnchantment.key) || + name.equalsIgnoreCase(MeteorShowerEnchantment.key) || + name.equalsIgnoreCase(SoulbindEnchantment.key) || + name.equalsIgnoreCase(DrillingEnchantment.key) || + name.equalsIgnoreCase(IceBreakerEnchantment.key) || + name.equalsIgnoreCase(SummonMerchantEnchantment.key) || + name.equalsIgnoreCase(SummonWolfEnchantment.key) || + name.equalsIgnoreCase(UnbindEnchantment.key) || + name.equalsIgnoreCase(LightningEnchantment.key) || + name.equalsIgnoreCase(PlasmaBootsEnchantment.key) || + name.equalsIgnoreCase(GrapplingHookEnchantment.key) || + name.equalsIgnoreCase(EarthquakeEnchantment.key)) { + customEnchantments.put(name.toLowerCase(), level); + continue; + } + + + Enchantment enchantment; + + try { + enchantment = Enchantment.getByName(name); + if (enchantment == null) + throw new Exception("Null enchantment"); + } catch (Exception ex) { + Bukkit.getLogger().warning("[EliteMobs] Custom Item Entry " + this.fileName + " has an invalid enchantment entry."); + Bukkit.getLogger().warning("[EliteMobs] Enchantment " + name + " is not a valid enchantment. Check the Spigot API for the correct names!"); + Bukkit.getLogger().warning("[EliteMobs] The invalid entry will be skipped."); + continue; + } + + enchantments.put(enchantment, level); + + } catch (Exception ex) { + Bukkit.getLogger().warning("[EliteMobs] Invalid enchantment entry for item " + this.fileName); + Bukkit.getLogger().warning("[EliteMobs] [" + string + "] is not a valid entry and will be ignored."); + Bukkit.getLogger().warning("[EliteMobs] Reminder - The correct format for these is [enchantmentName],[level]"); + Bukkit.getLogger().warning("[EliteMobs] The name should follow the API names and the level should be above 0."); + } + } + + private void parsePotionEffects() { + this.potionEffects = this.customItemsConfigFields.getPotionEffects(); + } + + private void parseItemType() { + if (this.customItemsConfigFields.getItemType() == null) { + this.itemType = ItemType.CUSTOM; + return; + } + this.itemType = customItemsConfigFields.getItemType(); + } + + private boolean parseDropWeight() { + if (this.customItemsConfigFields.getDropWeight() == null) return false; + if (this.customItemsConfigFields.getDropWeight().equalsIgnoreCase("dynamic")) return false; + try { + this.dropWeight = Double.parseDouble(this.customItemsConfigFields.getDropWeight()); + return true; + } catch (Exception e) { + Bukkit.getLogger().warning("[EliteMobs] Item " + this.fileName + " does not have a valid itemWeight."); + } + return false; + } + + private void parseScalability() { + if (this.customItemsConfigFields.getScalability() == null) { + this.scalability = Scalability.SCALABLE; + return; + } + this.scalability = customItemsConfigFields.getScalability(); + switch (this.customItemsConfigFields.getScalability()) { + case FIXED: + if (!itemType.equals(ItemType.UNIQUE)) + addFixedItem(this); + break; + case LIMITED: + if (!itemType.equals(ItemType.UNIQUE)) + addLimitedItem(this); + break; + case SCALABLE: + if (!itemType.equals(ItemType.UNIQUE)) + scalableItems.add(this); + break; + default: + this.scalability = Scalability.SCALABLE; + if (!itemType.equals(ItemType.UNIQUE)) + scalableItems.add(this); + Bukkit.getLogger().warning("Item " + this.fileName + " does not have a valid scalability type! Defaulting to scalable."); + + } + } + + private void parseItemTier() { + this.itemTier = ItemTierFinder.findBattleTier(generateDefaultsItemStack(null, false, null)); + } + + public ItemStack generateDefaultsItemStack(Player player, boolean showItemWorth, EliteEntity eliteEntity) { + if (player != null && !permission.isEmpty() && !player.hasPermission(permission)) return null; + ItemStack itemStack = + ItemConstructor.constructItem( + getName(), + getMaterial(), + getEnchantments(), + getCustomEnchantments(), + getPotionEffects(), + getLore(), + eliteEntity, + player, + showItemWorth, + customItemsConfigFields.getCustomModelID()); + ItemMeta itemMeta = itemStack.getItemMeta(); + //Adds the filename to the persistent data container, useful for several things but mostly used for tracking quest keys + Objects.requireNonNull(itemMeta).getPersistentDataContainer().set(new NamespacedKey(MetadataHandler.PLUGIN, fileName), PersistentDataType.STRING, fileName); + itemStack.setItemMeta(itemMeta); + return itemStack; + } + + public ItemStack generateItemStack(int itemTier, Player player, EliteEntity eliteEntity) { + ItemStack itemStack = null; + switch (this.scalability) { + case FIXED: + itemStack = generateDefaultsItemStack(player, false, eliteEntity); + break; + case LIMITED: + itemStack = ScalableItemConstructor.constructLimitedItem(itemTier, this, player, eliteEntity); + break; + case SCALABLE: + itemStack = ScalableItemConstructor.constructScalableItem(itemTier, this, player, eliteEntity); + } + return itemStack; + } + + public CustomItemsConfigFields getCustomLootConfigFields() { + return customItemsConfigFields; + } + + public String getFileName() { + return fileName; + } + + public boolean isEnabled() { + return isEnabled; + } + + public Material getMaterial() { + return material; + } + + public String getName() { + return name; + } + + public List getLore() { + return lore; + } + + public HashMap getEnchantments() { + return enchantments; + } + + public HashMap getCustomEnchantments() { + return customEnchantments; + } + + public List getPotionEffects() { + return potionEffects; + } + + public int getItemTier() { + return itemTier; + } + + public double getDropWeight() { + return dropWeight; + } + + public Scalability getScalability() { + return scalability; + } + + public ItemType getItemType() { + return itemType; + } + + public enum ItemType { + CUSTOM, + UNIQUE + } + + public enum Scalability { + FIXED, + LIMITED, + SCALABLE + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/items/customloottable/CurrencyCustomLootEntry.java b/src/main/java/com/magmaguy/elitemobs/items/customloottable/CurrencyCustomLootEntry.java new file mode 100644 index 000000000..19a85307a --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/items/customloottable/CurrencyCustomLootEntry.java @@ -0,0 +1,88 @@ +package com.magmaguy.elitemobs.items.customloottable; + +import com.magmaguy.elitemobs.config.EconomySettingsConfig; +import com.magmaguy.elitemobs.config.ItemSettingsConfig; +import com.magmaguy.elitemobs.economy.EconomyHandler; +import com.magmaguy.elitemobs.items.ItemLootShower; +import lombok.Getter; +import org.bukkit.Location; +import org.bukkit.entity.Player; + +import java.io.Serializable; +import java.util.List; + +public class CurrencyCustomLootEntry extends CustomLootEntry implements Serializable { + @Getter + private int currencyAmount = 0; + + public CurrencyCustomLootEntry(List entries, int currencyAmount) { + this.currencyAmount = currencyAmount; + entries.add(this); + } + + public CurrencyCustomLootEntry(List entries, String rawString, String configFilename) { + for (String string : rawString.split(":")) { + String[] strings = string.split("="); + switch (strings[0].toLowerCase()) { + case "currencyamount": + try { + this.currencyAmount = Integer.parseInt(strings[1]); + } catch (Exception ex) { + errorMessage(rawString, configFilename, "currencyAmount"); + } + break; + case "amount": + try { + super.setAmount(Integer.parseInt(strings[1])); + } catch (Exception ex) { + errorMessage(rawString, configFilename, "amount"); + } + break; + case "chance": + try { + super.setChance(Integer.parseInt(strings[1])); + } catch (Exception ex) { + errorMessage(rawString, configFilename, "chance"); + } + break; + case "permission": + try { + super.setPermission(strings[1]); + } catch (Exception ex) { + errorMessage(rawString, configFilename, "permission"); + } + break; + case "wave": + try { + super.setWave(Integer.parseInt(strings[1])); + } catch (Exception ex) { + errorMessage(rawString, configFilename, "wave"); + } + break; + default: + } + } + if (currencyAmount == 0) { + errorMessage(rawString, configFilename, "currencyAmount"); + return; + } + entries.add(this); + } + + + @Override + public void locationDrop(int itemTier, Player player, Location location) { + for (int i = 0; i < getAmount(); i++) + new ItemLootShower(location, player, currencyAmount); + } + + @Override + public void directDrop(int itemTier, Player player) { + for (int i = 0; i < getAmount(); i++){ + EconomyHandler.addCurrency(player.getUniqueId(), currencyAmount); + player.sendMessage(ItemSettingsConfig.getDirectDropCoinMessage() + .replace("$amount", currencyAmount+"") + .replace("$currencyName", EconomySettingsConfig.getCurrencyName())); + } + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/items/customloottable/CustomLootEntry.java b/src/main/java/com/magmaguy/elitemobs/items/customloottable/CustomLootEntry.java new file mode 100644 index 000000000..c4b037a98 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/items/customloottable/CustomLootEntry.java @@ -0,0 +1,59 @@ +package com.magmaguy.elitemobs.items.customloottable; + +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.utils.WarningMessage; +import lombok.Getter; +import lombok.Setter; +import org.bukkit.Location; +import org.bukkit.entity.Player; + +import java.io.Serializable; +import java.util.concurrent.ThreadLocalRandom; + +public class CustomLootEntry implements Serializable { + @Getter + @Setter + private double chance = 1; + @Getter + @Setter + private int amount = 1; + @Getter + @Setter + private String permission = ""; + @Getter + @Setter + private int wave = -1; + @Getter + @Setter + private int itemLevel = 1; + + public CustomLootEntry() { + } + + public static void errorMessage(String rawString, String configFilename, String reason) { + new WarningMessage("Failed to parse entry " + rawString + " for file " + configFilename + " due to invalid: " + reason); + } + + public boolean willDrop(Player player) { + if (!permission.isEmpty() && !player.hasPermission(permission)) return false; + return ThreadLocalRandom.current().nextDouble() < chance; + } + + public void locationDrop(int itemTier, Player player, Location dropLocation) { + //meant to be overriden by the classes that extend it + } + + public void directDrop(int itemTier, Player player) { + //meant to be overriden by the classes that extend it + } + + //used specifically so loot can be attributed to the right source + public void locationDrop(int itemTier, Player player, Location dropLocation, EliteEntity eliteEntity) { + //meant to be overriden by the classes that extend it + } + + //used specifically so loot can be attributed to the right source + public void directDrop(int itemTier, Player player, EliteEntity eliteEntity) { + //meant to be overriden by the classes that extend it + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/items/customloottable/CustomLootTable.java b/src/main/java/com/magmaguy/elitemobs/items/customloottable/CustomLootTable.java new file mode 100644 index 000000000..97f9229c6 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/items/customloottable/CustomLootTable.java @@ -0,0 +1,117 @@ +package com.magmaguy.elitemobs.items.customloottable; + +import com.magmaguy.elitemobs.config.ItemSettingsConfig; +import com.magmaguy.elitemobs.config.customarenas.CustomArenasConfigFields; +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import com.magmaguy.elitemobs.config.customquests.CustomQuestsConfigFields; +import com.magmaguy.elitemobs.config.customtreasurechests.CustomTreasureChestConfigFields; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import lombok.Getter; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.io.Serializable; +import java.util.*; + +public class CustomLootTable implements Serializable { + + @Getter + private final List entries = new ArrayList<>(); + private Map> waveRewards = new HashMap(); + + public CustomLootTable() { + } + + public CustomLootTable(CustomBossesConfigFields customBossesConfigFields) { + List rawStrings = customBossesConfigFields.getUniqueLootList(); + parseConfig(rawStrings, customBossesConfigFields.getFilename()); + } + + public CustomLootTable(CustomTreasureChestConfigFields treasureChestConfigFields) { + List rawStrings = treasureChestConfigFields.getLootList(); + parseConfig(rawStrings, treasureChestConfigFields.getFilename()); + } + + public CustomLootTable(CustomQuestsConfigFields questsConfigFields) { + List rawStrings = questsConfigFields.getCustomRewardsList(); + parseConfig(rawStrings, questsConfigFields.getFilename()); + } + + public CustomLootTable(CustomArenasConfigFields customArenasConfigFields) { + List rawStrings = customArenasConfigFields.getRawArenaRewards(); + parseConfig(rawStrings, customArenasConfigFields.getFilename()); + } + + private void parseConfig(List lootTable, String filename) { + for (String rawString : lootTable) + switch (rawString.split(":")[0].toLowerCase()) { + case "minecraft": + new VanillaCustomLootEntry(entries, rawString, filename); + break; + case "scrap": + case "upgrade_item": + new SpecialCustomLootEntry(entries, rawString, filename); + break; + default: + if (rawString.toLowerCase(Locale.ROOT).contains("currencyamount=")) + new CurrencyCustomLootEntry(entries, rawString, filename); + else if (rawString.contains("material=")) + new VanillaCustomLootEntry(entries, rawString, filename); + else + new EliteCustomLootEntry(entries, rawString, filename); + } + for (CustomLootEntry customLootEntry : entries) { + if (customLootEntry.getWave() > 0) { + if (this.waveRewards.get(customLootEntry.getWave()) != null) { + List rewards = this.waveRewards.get(customLootEntry.getWave()); + rewards.add(customLootEntry); + this.waveRewards.put(customLootEntry.getWave(), rewards); + } else + waveRewards.put(customLootEntry.getWave(), new ArrayList<>(Arrays.asList(customLootEntry))); + } + } + } + + public void generateCurrencyEntry(int currencyAmount) { + new CurrencyCustomLootEntry(entries, currencyAmount); + } + + public void generateEliteEntry(ItemStack itemStack) { + new ItemStackCustomLootEntry(entries, itemStack); + } + + public void bossDrop(Player player, int level, Location dropLocation, EliteEntity eliteEntity) { + for (CustomLootEntry customLootEntry : entries) + if (customLootEntry.willDrop(player)) + if (ItemSettingsConfig.isPutLootDirectlyIntoPlayerInventory()) + customLootEntry.directDrop(level, player, eliteEntity); + else + customLootEntry.locationDrop(level, player, dropLocation, eliteEntity); + } + + public void treasureChestDrop(Player player, int chestLevel, Location dropLocation) { + for (CustomLootEntry customLootEntry : entries) + if (customLootEntry.willDrop(player)) { + if (ItemSettingsConfig.isPutLootDirectlyIntoPlayerInventory()) { + customLootEntry.directDrop(chestLevel * 10, player); + }else{ + customLootEntry.locationDrop(chestLevel * 10, player, dropLocation); + } + } + } + + public void questDrop(Player player, int questRewardLevel) { + for (CustomLootEntry customLootEntry : entries) + if (customLootEntry.willDrop(player)) + customLootEntry.directDrop(questRewardLevel, player); + } + + public void arenaReward(Player player, int wave) { + if (waveRewards.get(wave) == null) return; + waveRewards.get(wave).forEach(reward -> { + if (reward.willDrop(player)) + reward.directDrop(reward.getItemLevel(), player); + }); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/items/customloottable/EliteCustomLootEntry.java b/src/main/java/com/magmaguy/elitemobs/items/customloottable/EliteCustomLootEntry.java new file mode 100644 index 000000000..25f892e07 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/items/customloottable/EliteCustomLootEntry.java @@ -0,0 +1,154 @@ +package com.magmaguy.elitemobs.items.customloottable; + +import com.magmaguy.elitemobs.config.ItemSettingsConfig; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import lombok.Getter; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.io.Serializable; +import java.util.List; +import java.util.Locale; +import java.util.Objects; + +public class EliteCustomLootEntry extends CustomLootEntry implements Serializable { + @Getter + private String filename = null; + + public EliteCustomLootEntry(List entries, String rawString, String configFilename) { + super(); + //old format + if (!rawString.contains("filename=")) { + parseLegacyFormat(rawString, configFilename); + } + //new format + else { + parseNewFormat(rawString, configFilename); + } + if (filename == null) return; + CustomItem customItem = CustomItem.getCustomItem(filename); + if (customItem == null) { + errorMessage(rawString, configFilename, "filename"); + return; + } + entries.add(this); + } + + //Format: filename.yml:chance:permission + private void parseLegacyFormat(String rawString, String configFilename) { + String[] stringArray = rawString.split(":"); + try { + filename = stringArray[0]; + } catch (Exception ex) { + errorMessage(rawString, configFilename, "filename"); + return; + } + + try { + super.setChance(Double.parseDouble(stringArray[1])); + } catch (Exception ex) { + errorMessage(rawString, configFilename, "chance"); + return; + } + + if (stringArray.length > 2) + try { + super.setPermission(stringArray[2]); + } catch (Exception ex) { + errorMessage(rawString, configFilename, "permission"); + } + } + + //Format: filename=filename.yml:chance=X.Y:amount=X:permission=per.miss.ion + private void parseNewFormat(String rawString, String configFilename) { + for (String string : rawString.split(":")) { + String[] strings = string.split("="); + switch (strings[0].toLowerCase(Locale.ROOT)) { + case "filename": + try { + this.filename = strings[1]; + } catch (Exception ex) { + errorMessage(rawString, configFilename, "filename"); + } + break; + case "amount": + try { + super.setAmount(Integer.parseInt(strings[1])); + } catch (Exception ex) { + errorMessage(rawString, configFilename, "amount"); + } + break; + case "chance": + try { + super.setChance(Double.parseDouble(strings[1])); + } catch (Exception ex) { + errorMessage(rawString, configFilename, "chance"); + } + break; + case "permission": + try { + super.setPermission(strings[1]); + } catch (Exception ex) { + errorMessage(rawString, configFilename, "permission"); + } + break; + case "itemlevel": + try { + super.setItemLevel(Integer.parseInt(strings[1])); + } catch (Exception ex) { + errorMessage(rawString, configFilename, "level"); + } + break; + case "wave": + try { + super.setWave(Integer.parseInt(strings[1])); + } catch (Exception ex) { + errorMessage(rawString, configFilename, "wave"); + } + break; + default: + } + } + } + + private CustomItem generateCustomItem() { + return CustomItem.getCustomItem(filename); + } + + public ItemStack generateItemStack(int level, Player player, EliteEntity eliteEntity) { + return generateCustomItem().generateItemStack(level, player, eliteEntity); + } + + @Override + public void locationDrop(int itemTier, Player player, Location location) { + for (int i = 0; i < getAmount(); i++) + generateCustomItem().dropPlayerLoot(player, itemTier, location, null); + } + + @Override + public void locationDrop(int itemTier, Player player, Location location, EliteEntity eliteEntity) { + for (int i = 0; i < getAmount(); i++) + generateCustomItem().dropPlayerLoot(player, itemTier, location, eliteEntity); + } + + @Override + public void directDrop(int itemTier, Player player) { + for (int i = 0; i < getAmount(); i++){ + ItemStack itemStack = generateCustomItem().generateItemStack(itemTier, player, null); + player.getInventory().addItem(itemStack); + player.sendMessage(ItemSettingsConfig.getDirectDropCustomLootMessage().replace("$itemName", Objects.requireNonNull(itemStack.getItemMeta()).getDisplayName())); + } + } + + @Override + public void directDrop(int itemTier, Player player, EliteEntity eliteEntity) { + for (int i = 0; i < getAmount(); i++){ + ItemStack itemStack = generateCustomItem().generateItemStack(itemTier, player, eliteEntity); + if (itemStack == null) return; + player.getInventory().addItem(itemStack); + player.sendMessage(ItemSettingsConfig.getDirectDropCustomLootMessage().replace("$itemName", Objects.requireNonNull(itemStack.getItemMeta()).getDisplayName())); + } + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/items/customloottable/ItemStackCustomLootEntry.java b/src/main/java/com/magmaguy/elitemobs/items/customloottable/ItemStackCustomLootEntry.java new file mode 100644 index 000000000..e906d7075 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/items/customloottable/ItemStackCustomLootEntry.java @@ -0,0 +1,36 @@ +package com.magmaguy.elitemobs.items.customloottable; + +import com.magmaguy.elitemobs.utils.ObjectSerializer; +import com.magmaguy.elitemobs.utils.WarningMessage; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.io.Serializable; +import java.util.List; + +public class ItemStackCustomLootEntry extends CustomLootEntry implements Serializable { + private final String serializedItemStack; + + public ItemStackCustomLootEntry(List entries, ItemStack itemStack) { + super(); + this.serializedItemStack = ObjectSerializer.itemStackArrayToBase64(itemStack); + entries.add(this); + } + + public ItemStack generateItemStack() { + try { + return ObjectSerializer.itemStackArrayFromBase64(serializedItemStack); + } catch (Exception ex) { + new WarningMessage("Failed to serialize item stack from Custom Loot Table"); + return null; + } + } + + @Override + public void directDrop(int itemTier, Player player) { + ItemStack itemStack = generateItemStack(); + if (itemStack == null) return; + for (int i = 0; i < getAmount(); i++) + player.getInventory().addItem(itemStack); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/items/customloottable/SpecialCustomLootEntry.java b/src/main/java/com/magmaguy/elitemobs/items/customloottable/SpecialCustomLootEntry.java new file mode 100644 index 000000000..4dcf007f2 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/items/customloottable/SpecialCustomLootEntry.java @@ -0,0 +1,58 @@ +package com.magmaguy.elitemobs.items.customloottable; + +import com.magmaguy.elitemobs.config.ItemSettingsConfig; +import com.magmaguy.elitemobs.items.itemconstructor.SpecialLoot; +import lombok.Getter; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.io.Serializable; +import java.util.List; + +public class SpecialCustomLootEntry extends CustomLootEntry implements Serializable { + @Getter + private String rawString; + private String configFilename; + + public SpecialCustomLootEntry(List entries, String rawString, String configFilename) { + this.rawString = rawString; + this.configFilename = configFilename; + //todo: Integrate Special Loot in its entirety to this class to make it mesh with how the rest of the loot works + for (String processedString : rawString.split(":")) { + String[] strings = processedString.split("="); + switch (strings[0].toLowerCase()) { + case "wave": + try { + super.setWave(Integer.parseInt(strings[1])); + } catch (Exception ex) { + errorMessage(rawString, configFilename, "wave"); + } + break; + } + } + entries.add(this); + } + + private SpecialLoot generateSpecialLoot() { + return new SpecialLoot(rawString, configFilename); + } + + public ItemStack generateItemStack(Player player) { + return generateSpecialLoot().generateItemStack(player); + } + + @Override + public void locationDrop(int itemTier, Player player, Location location) { + location.getWorld().dropItem(location, generateSpecialLoot().generateItemStack(player)); + } + + @Override + public void directDrop(int itemTier, Player player) { + ItemStack itemStack = generateSpecialLoot().generateItemStack(player); + player.getInventory().addItem(itemStack); + player.sendMessage(ItemSettingsConfig.getDirectDropSpecialMessage() + .replace("$amount", itemStack.getAmount() + "") + .replace("$name", itemStack.getItemMeta().getDisplayName())); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/items/customloottable/VanillaCustomLootEntry.java b/src/main/java/com/magmaguy/elitemobs/items/customloottable/VanillaCustomLootEntry.java new file mode 100644 index 000000000..225ad5573 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/items/customloottable/VanillaCustomLootEntry.java @@ -0,0 +1,79 @@ +package com.magmaguy.elitemobs.items.customloottable; + +import com.magmaguy.elitemobs.config.ItemSettingsConfig; +import lombok.Getter; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.io.Serializable; +import java.util.List; +import java.util.Objects; + +public class VanillaCustomLootEntry extends CustomLootEntry implements Serializable { + @Getter + private Material material = null; + + public VanillaCustomLootEntry(List entries, String rawString, String configFilename) { + parseAllFormats(rawString, configFilename); + if (this.material == null) return; + entries.add(this); + } + + private void parseAllFormats(String rawString, String configFilename) { + for (String processedString : rawString.split(":")) { + String[] strings = processedString.split("="); + switch (strings[0].toLowerCase()) { + case "type": + case "material": + try { + this.material = Material.valueOf(strings[1]); + } catch (Exception ex) { + errorMessage(rawString, configFilename, "material"); + } + break; + case "amount": + try { + super.setAmount(Integer.parseInt(strings[1])); + } catch (Exception ex) { + errorMessage(rawString, configFilename, "amount"); + } + break; + case "chance": + try { + super.setChance(Double.parseDouble(strings[1])); + } catch (Exception ex) { + errorMessage(rawString, configFilename, "chance"); + } + break; + case "wave": + try { + super.setWave(Integer.parseInt(strings[1])); + } catch (Exception ex) { + errorMessage(rawString, configFilename, "wave"); + } + break; + } + } + } + + public ItemStack generateItemStack() { + return new ItemStack(material, 1); + } + + @Override + public void locationDrop(int itemTier, Player player, Location location) { + for (int i = 0; i < getAmount(); i++) + location.getWorld().dropItem(location, generateItemStack()); + } + + @Override + public void directDrop(int itemTier, Player player) { + for (int i = 0; i < getAmount(); i++){ + ItemStack itemStack = generateItemStack(); + player.getInventory().addItem(itemStack); + player.sendMessage(ItemSettingsConfig.getDirectDropMinecraftLootMessage().replace("$itemName", Objects.requireNonNull(itemStack.getItemMeta()).getDisplayName())); + } + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/DropWeightHandler.java b/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/DropWeightHandler.java deleted file mode 100644 index 5edf9efd1..000000000 --- a/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/DropWeightHandler.java +++ /dev/null @@ -1,113 +0,0 @@ -package com.magmaguy.elitemobs.items.itemconstructor; - -import com.magmaguy.elitemobs.items.CustomItemConstructor; -import com.magmaguy.elitemobs.items.ItemTierFinder; -import com.magmaguy.elitemobs.items.uniqueitems.UniqueItemInitializer; -import org.bukkit.Bukkit; -import org.bukkit.inventory.ItemStack; - -import java.util.ArrayList; -import java.util.List; - - -public class DropWeightHandler { - - public static void process(String dropType, ItemStack itemStack) { - - /* - This field is not mandatory, all parent keys missing this key will be considered dynamic - */ - if (dropType == null || dropType.isEmpty()) { - - rankedItemMapCreator(itemStack); - return; - - } - - /* - Code doesn't check for "dynamic" as it's the same behavior as nothing being in this key - */ - if (dropType.equalsIgnoreCase("dynamic")) { - - rankedItemMapCreator(itemStack); - return; - - } - - /* - Unique items only ever drop from specific bosses - */ - if (dropType.equalsIgnoreCase("unique")) { - - UniqueItemInitializer.uniqueItemsList.add(itemStack); - return; - - } - - - /* - Static items can drop at any point - */ - try { - - Double dropWeight = Double.valueOf(dropType); - CustomItemConstructor.staticCustomItemHashMap.put(itemStack, dropWeight); - - } catch (NumberFormatException e) { - - Bukkit.getLogger().info("[EliteMobs] Your item " + itemStack.getItemMeta().getDisplayName() + - " contains an invalid drop weight value (" + dropType + ")"); - - } - - } - - private static void rankedItemMapCreator(ItemStack itemStack) { - - int itemTier = (int) ItemTierFinder.findBattleTier(itemStack); - - if (CustomItemConstructor.dynamicRankedItemStacks.get(itemTier) == null) { - - List list = new ArrayList<>(); - - list.add(itemStack); - - CustomItemConstructor.dynamicRankedItemStacks.put(itemTier, list); - - } else { - - List list = CustomItemConstructor.dynamicRankedItemStacks.get(itemTier); - - list.add(itemStack); - - CustomItemConstructor.dynamicRankedItemStacks.put(itemTier, list); - - } - - } - - public static boolean isDynamic(String dropType){ - - /* - This field is not mandatory, all parent keys missing this key will be considered dynamic - */ - if (dropType == null || dropType.isEmpty()) { - - return true; - - } - - /* - Code doesn't check for "dynamic" as it's the same behavior as nothing being in this key - */ - if (dropType.equalsIgnoreCase("dynamic")) { - - return true; - - } - - return false; - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/EnchantmentGenerator.java b/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/EnchantmentGenerator.java index a56401bdf..5d67ae59e 100644 --- a/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/EnchantmentGenerator.java +++ b/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/EnchantmentGenerator.java @@ -1,8 +1,13 @@ package com.magmaguy.elitemobs.items.itemconstructor; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.ItemsDropSettingsConfig; -import com.magmaguy.elitemobs.config.ItemsProceduralSettingsConfig; +import com.magmaguy.elitemobs.config.ItemSettingsConfig; +import com.magmaguy.elitemobs.config.ProceduralItemGenerationSettingsConfig; +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfig; +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfigFields; +import com.magmaguy.elitemobs.items.EliteEnchantments; +import com.magmaguy.elitemobs.items.ItemTierFinder; +import com.magmaguy.elitemobs.items.customenchantments.CriticalStrikesEnchantment; +import com.magmaguy.elitemobs.items.customenchantments.HunterEnchantment; import com.magmaguy.elitemobs.utils.VersionChecker; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; @@ -17,12 +22,23 @@ public class EnchantmentGenerator { public static ItemMeta generateEnchantments(ItemMeta itemMeta, HashMap enchantmentMap) { - for (Enchantment enchantment : enchantmentMap.keySet()) - if (enchantmentMap.get(enchantment) > 5 && ConfigValues.itemsDropSettingsConfig.getBoolean(ItemsDropSettingsConfig.ENABLE_CUSTOM_ENCHANTMENT_SYSTEM)) - itemMeta.addEnchant(enchantment, 5, true); - else - itemMeta.addEnchant(enchantment, enchantmentMap.get(enchantment), true); + for (Enchantment enchantment : enchantmentMap.keySet()) { + if (enchantment != null) + if (enchantmentMap.get(enchantment) > enchantment.getMaxLevel() && ItemSettingsConfig.isUseEliteEnchantments()) { + if (EliteEnchantments.isPotentialEliteEnchantment(enchantment)) { + if (enchantmentMap.get(enchantment) > enchantment.getMaxLevel()) { + itemMeta.addEnchant(enchantment, enchantment.getMaxLevel(), true); + } else + itemMeta.addEnchant(enchantment, enchantmentMap.get(enchantment), true); + } else + itemMeta.addEnchant(enchantment, enchantmentMap.get(enchantment), true); + } else { + itemMeta.addEnchant(enchantment, enchantmentMap.get(enchantment), true); + } + + + } return itemMeta; } @@ -31,10 +47,12 @@ public static ItemMeta generateEnchantments(ItemMeta itemMeta, HashMap generateEnchantments(double itemTier, Material material) { + public static HashMap generateEnchantments(double itemTier, Material material, ItemMeta itemMeta) { HashMap enchantmentMap = new HashMap<>(); + itemTier -= ItemTierFinder.getMaterialTier(material); + /* No enchantments for items too low tier to have one */ @@ -47,11 +65,18 @@ public static HashMap generateEnchantments(double itemTier Secondary enchantments get added to a common pool to be randomized later */ switch (material) { + case TRIDENT: + if (ThreadLocalRandom.current().nextDouble() < 0.5) + validSecondaryEnchantments.putAll(validateSecondaryEnchantments("LOYALTY")); + else + validSecondaryEnchantments.putAll(validateSecondaryEnchantments("CHANNELING")); + validSecondaryEnchantments.putAll(validateSecondaryEnchantments("RIPTIDE")); + validSecondaryEnchantments.putAll(validateSecondaryEnchantments("IMPALING")); case DIAMOND_SWORD: - case GOLD_SWORD: + case GOLDEN_SWORD: case IRON_SWORD: case STONE_SWORD: - case WOOD_SWORD: + case WOODEN_SWORD: enchantmentMap.putAll(validateAndApplyPrimaryEnchantment("DAMAGE_ALL", itemTier)); validSecondaryEnchantments.putAll(validateSecondaryEnchantments("DAMAGE_ARTHROPODS")); validSecondaryEnchantments.putAll(validateSecondaryEnchantments("DAMAGE_UNDEAD")); @@ -72,11 +97,20 @@ public static HashMap generateEnchantments(double itemTier validSecondaryEnchantments.putAll(validateSecondaryEnchantments("MENDING")); validSecondaryEnchantments.putAll(validateSecondaryEnchantments("VANISHING_CURSE")); break; + case CROSSBOW: + enchantmentMap.putAll(validateAndApplyPrimaryEnchantment("ARROW_DAMAGE", itemTier)); + validSecondaryEnchantments.putAll(validateSecondaryEnchantments("QUICK_CHARGE")); + validSecondaryEnchantments.putAll(validateSecondaryEnchantments("MULTISHOT")); + validSecondaryEnchantments.putAll(validateSecondaryEnchantments("PIERCING")); + validSecondaryEnchantments.putAll(validateSecondaryEnchantments("DURABILITY")); + validSecondaryEnchantments.putAll(validateSecondaryEnchantments("MENDING")); + validSecondaryEnchantments.putAll(validateSecondaryEnchantments("VANISHING_CURSE")); + break; case DIAMOND_PICKAXE: - case GOLD_PICKAXE: + case GOLDEN_PICKAXE: case IRON_PICKAXE: case STONE_PICKAXE: - case WOOD_PICKAXE: + case WOODEN_PICKAXE: enchantmentMap.putAll(validateAndApplyPrimaryEnchantment("DIG_SPEED", itemTier)); validSecondaryEnchantments.putAll(validateSecondaryEnchantments("DURABILITY")); validSecondaryEnchantments.putAll(validateSecondaryEnchantments("MENDING")); @@ -88,11 +122,11 @@ public static HashMap generateEnchantments(double itemTier validSecondaryEnchantments.putAll(validateSecondaryEnchantments("SILK_TOUCH")); } break; - case DIAMOND_SPADE: - case GOLD_SPADE: - case IRON_SPADE: - case STONE_SPADE: - case WOOD_SPADE: + case DIAMOND_SHOVEL: + case GOLDEN_SHOVEL: + case IRON_SHOVEL: + case STONE_SHOVEL: + case WOODEN_SHOVEL: enchantmentMap.putAll(validateAndApplyPrimaryEnchantment("DIG_SPEED", itemTier)); validSecondaryEnchantments.putAll(validateSecondaryEnchantments("DURABILITY")); validSecondaryEnchantments.putAll(validateSecondaryEnchantments("MENDING")); @@ -104,20 +138,32 @@ public static HashMap generateEnchantments(double itemTier } break; case DIAMOND_HOE: - case GOLD_HOE: + case GOLDEN_HOE: case IRON_HOE: case STONE_HOE: - case WOOD_HOE: + case WOODEN_HOE: + if (ItemSettingsConfig.isUseHoesAsWeapons()) + enchantmentMap.putAll(validateAndApplyPrimaryEnchantment("DAMAGE_ALL", itemTier)); + enchantmentMap.putAll(validateAndApplyPrimaryEnchantment("DIG_SPEED", itemTier)); + validSecondaryEnchantments.putAll(validateSecondaryEnchantments("DURABILITY")); + validSecondaryEnchantments.putAll(validateSecondaryEnchantments("MENDING")); + validSecondaryEnchantments.putAll(validateSecondaryEnchantments("VANISHING_CURSE")); + if (ThreadLocalRandom.current().nextDouble() < 0.5) { + validSecondaryEnchantments.putAll(validateSecondaryEnchantments("LOOT_BONUS_BLOCKS")); + } else { + validSecondaryEnchantments.putAll(validateSecondaryEnchantments("SILK_TOUCH")); + } + break; case SHIELD: enchantmentMap.putAll(validateAndApplyPrimaryEnchantment("DURABILITY", itemTier)); validSecondaryEnchantments.putAll(validateSecondaryEnchantments("MENDING")); validSecondaryEnchantments.putAll(validateSecondaryEnchantments("VANISHING_CURSE")); break; case DIAMOND_AXE: - case GOLD_AXE: + case GOLDEN_AXE: case IRON_AXE: case STONE_AXE: - case WOOD_AXE: + case WOODEN_AXE: enchantmentMap.putAll(validateAndApplyPrimaryEnchantment("DAMAGE_ALL", itemTier)); validSecondaryEnchantments.putAll(validateSecondaryEnchantments("DAMAGE_ARTHROPODS")); validSecondaryEnchantments.putAll(validateSecondaryEnchantments("DAMAGE_UNDEAD")); @@ -129,9 +175,10 @@ public static HashMap generateEnchantments(double itemTier break; case CHAINMAIL_HELMET: case DIAMOND_HELMET: - case GOLD_HELMET: + case GOLDEN_HELMET: case IRON_HELMET: case LEATHER_HELMET: + case TURTLE_HELMET: enchantmentMap.putAll(validateAndApplyPrimaryEnchantment("PROTECTION_ENVIRONMENTAL", itemTier)); validSecondaryEnchantments.putAll(validateSecondaryEnchantments("BINDING_CURSE")); validSecondaryEnchantments.putAll(validateSecondaryEnchantments("DURABILITY")); @@ -146,7 +193,7 @@ public static HashMap generateEnchantments(double itemTier break; case CHAINMAIL_CHESTPLATE: case DIAMOND_CHESTPLATE: - case GOLD_CHESTPLATE: + case GOLDEN_CHESTPLATE: case IRON_CHESTPLATE: case LEATHER_CHESTPLATE: enchantmentMap.putAll(validateAndApplyPrimaryEnchantment("PROTECTION_ENVIRONMENTAL", itemTier)); @@ -160,7 +207,7 @@ public static HashMap generateEnchantments(double itemTier break; case CHAINMAIL_LEGGINGS: case DIAMOND_LEGGINGS: - case GOLD_LEGGINGS: + case GOLDEN_LEGGINGS: case IRON_LEGGINGS: case LEATHER_LEGGINGS: enchantmentMap.putAll(validateAndApplyPrimaryEnchantment("PROTECTION_ENVIRONMENTAL", itemTier)); @@ -175,7 +222,7 @@ public static HashMap generateEnchantments(double itemTier break; case CHAINMAIL_BOOTS: case DIAMOND_BOOTS: - case GOLD_BOOTS: + case GOLDEN_BOOTS: case IRON_BOOTS: case LEATHER_BOOTS: enchantmentMap.putAll(validateAndApplyPrimaryEnchantment("PROTECTION_ENVIRONMENTAL", itemTier)); @@ -213,29 +260,25 @@ public static HashMap generateEnchantments(double itemTier int maxSecondaryEnchantmentLevel = (secondaryEnchantmentTotalParsedLevel < itemTier - 2) ? secondaryEnchantmentTotalParsedLevel : (int) itemTier; int secondaryEnchantmentCount = ThreadLocalRandom.current().nextInt(maxSecondaryEnchantmentLevel + 1); - if (itemTier < 2 || secondaryEnchantmentCount < 1 || validSecondaryEnchantments.size() == 0) + if (itemTier < 2 || secondaryEnchantmentCount < 1 || validSecondaryEnchantments.size() == 0) { + generateEnchantments(itemMeta, enchantmentMap); return enchantmentMap; + } HashMap validEnchantmentsClone = (HashMap) validSecondaryEnchantments.clone(); while (secondaryEnchantmentCount != 0) { - if (validSecondaryEnchantments.size() < 1) { - + if (validSecondaryEnchantments.size() < 1) break; - } - int randomIndex = ThreadLocalRandom.current().nextInt(validSecondaryEnchantments.size()); List enchantmentList = new ArrayList(); - for (Enchantment enchantment : validSecondaryEnchantments.keySet()) { - + for (Enchantment enchantment : validSecondaryEnchantments.keySet()) enchantmentList.add(enchantment); - } - Enchantment enchantment = enchantmentList.get(randomIndex); validSecondaryEnchantments.put(enchantment, validSecondaryEnchantments.get(enchantment) - 1); @@ -251,11 +294,14 @@ public static HashMap generateEnchantments(double itemTier } + //this applies the vanilla enchants + generateEnchantments(itemMeta, enchantmentMap); + return enchantmentMap; } - public static HashMap generateCustomEnchantments(double itemTier, Material material){ + public static HashMap generateCustomEnchantments(double itemTier, Material material) { HashMap enchantmentMap = new HashMap<>(); @@ -272,65 +318,70 @@ public static HashMap generateCustomEnchantments(double itemTie */ switch (material) { case DIAMOND_SWORD: - case GOLD_SWORD: + case GOLDEN_SWORD: case IRON_SWORD: case STONE_SWORD: - case WOOD_SWORD: + case WOODEN_SWORD: + case TRIDENT: + validSecondaryEnchantments.putAll(validateSecondaryCustomEnchantments(CriticalStrikesEnchantment.key)); break; case BOW: + case CROSSBOW: + validSecondaryEnchantments.putAll(validateSecondaryCustomEnchantments(CriticalStrikesEnchantment.key)); break; case DIAMOND_PICKAXE: - case GOLD_PICKAXE: + case GOLDEN_PICKAXE: case IRON_PICKAXE: case STONE_PICKAXE: - case WOOD_PICKAXE: + case WOODEN_PICKAXE: break; - case DIAMOND_SPADE: - case GOLD_SPADE: - case IRON_SPADE: - case STONE_SPADE: - case WOOD_SPADE: + case DIAMOND_SHOVEL: + case GOLDEN_SHOVEL: + case IRON_SHOVEL: + case STONE_SHOVEL: + case WOODEN_SHOVEL: break; case DIAMOND_HOE: - case GOLD_HOE: + case GOLDEN_HOE: case IRON_HOE: case STONE_HOE: - case WOOD_HOE: + case WOODEN_HOE: case SHIELD: break; case DIAMOND_AXE: - case GOLD_AXE: + case GOLDEN_AXE: case IRON_AXE: case STONE_AXE: - case WOOD_AXE: + case WOODEN_AXE: + validSecondaryEnchantments.putAll(validateSecondaryCustomEnchantments(CriticalStrikesEnchantment.key)); break; case CHAINMAIL_HELMET: case DIAMOND_HELMET: - case GOLD_HELMET: + case GOLDEN_HELMET: case IRON_HELMET: case LEATHER_HELMET: - validSecondaryEnchantments.putAll(validateSecondaryCustomEnchantments("HUNTER")); + validSecondaryEnchantments.putAll(validateSecondaryCustomEnchantments(HunterEnchantment.key)); break; case CHAINMAIL_CHESTPLATE: case DIAMOND_CHESTPLATE: - case GOLD_CHESTPLATE: + case GOLDEN_CHESTPLATE: case IRON_CHESTPLATE: case LEATHER_CHESTPLATE: - validSecondaryEnchantments.putAll(validateSecondaryCustomEnchantments("HUNTER")); + validSecondaryEnchantments.putAll(validateSecondaryCustomEnchantments(HunterEnchantment.key)); break; case CHAINMAIL_LEGGINGS: case DIAMOND_LEGGINGS: - case GOLD_LEGGINGS: + case GOLDEN_LEGGINGS: case IRON_LEGGINGS: case LEATHER_LEGGINGS: - validSecondaryEnchantments.putAll(validateSecondaryCustomEnchantments("HUNTER")); + validSecondaryEnchantments.putAll(validateSecondaryCustomEnchantments(HunterEnchantment.key)); break; case CHAINMAIL_BOOTS: case DIAMOND_BOOTS: - case GOLD_BOOTS: + case GOLDEN_BOOTS: case IRON_BOOTS: case LEATHER_BOOTS: - validSecondaryEnchantments.putAll(validateSecondaryCustomEnchantments("HUNTER")); + validSecondaryEnchantments.putAll(validateSecondaryCustomEnchantments(HunterEnchantment.key)); break; case FISHING_ROD: break; @@ -346,7 +397,7 @@ public static HashMap generateCustomEnchantments(double itemTie if (itemTier < 2 || secondaryEnchantmentTotalParsedLevel < 1 || validSecondaryEnchantments.size() == 0) return enchantmentMap; - if (ThreadLocalRandom.current().nextDouble() > ConfigValues.itemsProceduralSettingsConfig.getDouble(ItemsProceduralSettingsConfig.CUSTOM_ENCHANTMENT_CHANCE)) + if (ThreadLocalRandom.current().nextDouble() > ProceduralItemGenerationSettingsConfig.getCustomEnchantmentChance()) return enchantmentMap; /* @@ -358,30 +409,15 @@ public static HashMap generateCustomEnchantments(double itemTie private static HashMap validateAndApplyPrimaryEnchantment(String string, double itemTier) { - HashMap enchantmentMap = new HashMap<>(); - - String mainString = "Valid Enchantments." + string; - - if (ConfigValues.itemsProceduralSettingsConfig.getBoolean(mainString + ".Allow")) { + EnchantmentsConfigFields enchantmentsConfigFields = EnchantmentsConfig.getEnchantment(string.toLowerCase() + ".yml"); - int maxEnchantmentLevel; - - if (ConfigValues.itemsProceduralSettingsConfig.contains(mainString + ".Max Level")) { - - maxEnchantmentLevel = ConfigValues.itemsProceduralSettingsConfig.getInt(mainString + ".Max Level"); - - } else { - - maxEnchantmentLevel = 1; - - } - - int enchantmentLevel = (maxEnchantmentLevel < itemTier) ? maxEnchantmentLevel : (int) itemTier; - - //index for random getting - - enchantmentMap.put(Enchantment.getByName(string), enchantmentLevel); + HashMap enchantmentMap = new HashMap<>(); + if (enchantmentsConfigFields != null && enchantmentsConfigFields.isEnabled()) { + Enchantment enchantment = enchantmentsConfigFields.getEnchantment(); + int enchantmentLevel = Math.min(enchantmentsConfigFields.getMaxLevel(), (int) itemTier); + if (enchantmentLevel < 0) enchantmentLevel = 0; + enchantmentMap.put(enchantment, enchantmentLevel); } return enchantmentMap; @@ -390,67 +426,34 @@ private static HashMap validateAndApplyPrimaryEnchantment( private static HashMap validateSecondaryEnchantments(String string) { - HashMap hashMap = new HashMap(); - - if (enchantmentBackwardsCompatibility(7, 0, string, "LURE")) return hashMap; - if (enchantmentBackwardsCompatibility(7, 0, string, "LUCK")) return hashMap; - if (enchantmentBackwardsCompatibility(8, 0, string, "DEPTH_STRIDER")) return hashMap; - if (enchantmentBackwardsCompatibility(9, 0, string, "MENDING")) return hashMap; - if (enchantmentBackwardsCompatibility(9, 0, string, "FROST_WALKER")) return hashMap; - if (enchantmentBackwardsCompatibility(11, 0, string, "VANISHING_CURSE")) return hashMap; - if (enchantmentBackwardsCompatibility(11, 0, string, "BINDING_CURSE")) return hashMap; - if (enchantmentBackwardsCompatibility(11, 1, string, "SWEEP")) return hashMap; - - String mainString = "Valid Enchantments." + string; - - if (ConfigValues.itemsProceduralSettingsConfig.getBoolean(mainString + ".Allow")) { - - int enchantmentLevel; - - if (ConfigValues.itemsProceduralSettingsConfig.contains(mainString + ".Max Level")) { - - enchantmentLevel = ConfigValues.itemsProceduralSettingsConfig.getInt(mainString + ".Max Level"); + EnchantmentsConfigFields enchantmentsConfigFields = EnchantmentsConfig.getEnchantment(string.toLowerCase() + ".yml"); - } else { - - enchantmentLevel = 1; - - } + HashMap enchantmentMap = new HashMap<>(); - hashMap.put(Enchantment.getByName(string), enchantmentLevel); + //Make sure vanishing and binding curses aren't always there + if (string.equalsIgnoreCase("VANISHING_CURSE") || string.equalsIgnoreCase("BINDING_CURSE")) + if (ThreadLocalRandom.current().nextDouble() < 0.5) + return enchantmentMap; + if (enchantmentsConfigFields != null && enchantmentsConfigFields.isEnabled()) { + Enchantment enchantment = enchantmentsConfigFields.getEnchantment(); + enchantmentMap.put(enchantment, enchantmentsConfigFields.getMaxLevel()); } - return hashMap; + return enchantmentMap; } private static HashMap validateSecondaryCustomEnchantments(String string) { - HashMap hashMap = new HashMap(); - - String mainString = "Valid Enchantments." + string; - - if (ConfigValues.itemsProceduralSettingsConfig.getBoolean(mainString + ".Allow")) { - - int enchantmentLevel; - - if (ConfigValues.itemsProceduralSettingsConfig.contains(mainString + ".Max Level")) { + EnchantmentsConfigFields enchantmentsConfigFields = EnchantmentsConfig.getEnchantment(string.toLowerCase() + ".yml"); - //TODO: actually implement this properly - enchantmentLevel = ThreadLocalRandom.current().nextInt(ConfigValues.itemsProceduralSettingsConfig.getInt(mainString + ".Max Level")) + 1; - - } else { - - enchantmentLevel = 1; - - } - - hashMap.put(string, enchantmentLevel); + HashMap enchantmentMap = new HashMap<>(); - } + if (enchantmentsConfigFields != null && enchantmentsConfigFields.isEnabled()) + enchantmentMap.put(string, ThreadLocalRandom.current().nextInt(enchantmentsConfigFields.getMaxLevel()) + 1); - return hashMap; + return enchantmentMap; } @@ -477,9 +480,10 @@ private static int totalSecondaryCustomEnchantmentCount(HashMap } //Version and subVersion should be set to the update at which the enchantment was introduced - private static boolean enchantmentBackwardsCompatibility(int version, int subVersion, String actualEnchantement, String enchantmentToAvoid) { + private static boolean enchantmentBackwardsCompatibility(int version, int subVersion, String + actualEnchantement, String enchantmentToAvoid) { - return !VersionChecker.currentVersionIsUnder(version, subVersion) && actualEnchantement.equalsIgnoreCase(enchantmentToAvoid); + return !VersionChecker.serverVersionOlderThan(version, subVersion) && actualEnchantement.equalsIgnoreCase(enchantmentToAvoid); } diff --git a/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/ItemConstructor.java b/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/ItemConstructor.java index e4bebbff2..ec8055838 100644 --- a/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/ItemConstructor.java +++ b/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/ItemConstructor.java @@ -1,92 +1,82 @@ package com.magmaguy.elitemobs.items.itemconstructor; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.ItemsDropSettingsConfig; -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.config.ItemUpgradeSystemConfig; +import com.magmaguy.elitemobs.items.EliteItemLore; +import com.magmaguy.elitemobs.items.ItemTagger; +import com.magmaguy.elitemobs.items.customenchantments.SoulbindEnchantment; +import com.magmaguy.elitemobs.items.potioneffects.ElitePotionEffectContainer; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; import org.bukkit.Material; import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; +import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class ItemConstructor { - /* - For custom and unique items - */ - public static ItemStack constructItem(String rawName, Material material, HashMap enchantments, HashMap customEnchantments, List potionEffects, - List lore, String dropType, String scalabilityType) { + public static ItemStack constructItem(String rawName, + Material material, + HashMap enchantments, + HashMap customEnchantments, + List potionEffects, + List lore, + EliteEntity eliteEntity, + Player player, + boolean showItemWorth, + int customModelID) { ItemStack itemStack; ItemMeta itemMeta; - /* - Generate material - */ - Material itemMaterial = MaterialGenerator.generateMaterial(material); - /* Construct initial item */ itemStack = ItemStackGenerator.generateItemStack(material); itemMeta = itemStack.getItemMeta(); + itemMeta.setDisplayName(ChatColorConverter.convert(rawName)); + /* Generate item enchantments Note: This only applies enchantments up to a certain level, above that threshold item enchantments only exist in the item lore and get interpreted by the combat system */ if (!enchantments.isEmpty()) - itemMeta = EnchantmentGenerator.generateEnchantments(itemMeta, enchantments); + EnchantmentGenerator.generateEnchantments(itemMeta, enchantments); - /* - Generate item lore - */ - itemMeta = LoreGenerator.generateLore(itemMeta, itemMaterial, enchantments, customEnchantments, potionEffects, lore); + itemStack.setItemMeta(itemMeta); /* - Remove vanilla enchantments + Generate item lore */ - if (ConfigValues.itemsDropSettingsConfig.getBoolean(ItemsDropSettingsConfig.ENABLE_CUSTOM_ENCHANTMENT_SYSTEM)) - itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); + if (!lore.isEmpty()) + ItemTagger.registerCustomLore(itemMeta, lore); - /* - Generate item name last as it relies on material type and quality - */ - itemMeta.setDisplayName(NameGenerator.generateName(rawName)); + //Tag the potion effects + new ElitePotionEffectContainer(itemMeta, potionEffects); - /* - Colorize with MMO colors - */ itemStack.setItemMeta(itemMeta); - ItemQualityColorizer.dropQualityColorizer(itemStack); - /* - Add item to relevant loot lists - */ - DropWeightHandler.process(dropType, itemStack); - - /* - Handle item scalability - */ - ScalabilityAssigner.assign(itemStack, rawName, material, enchantments, customEnchantments, potionEffects, lore, - dropType, scalabilityType); - - return itemStack; + //Apply custom model id + if (customModelID > 0) { + itemMeta.setCustomModelData(customModelID); + itemStack.setItemMeta(itemMeta); + } + return commonFeatures(itemStack, eliteEntity, player, enchantments, customEnchantments, showItemWorth); } /* - For scalable items + For procedurally generated items */ - - public static ItemStack constructItem(String rawName, Material material, HashMap enchantments, HashMap customEnchantments, List potionEffects, - List lore) { + public static ItemStack constructItem(double itemTier, EliteEntity killedMob, Player player, boolean showItemWorth) { ItemStack itemStack; ItemMeta itemMeta; @@ -94,103 +84,185 @@ public static ItemStack constructItem(String rawName, Material material, HashMap /* Generate material */ - Material itemMaterial = MaterialGenerator.generateMaterial(material); + Material itemMaterial = MaterialGenerator.generateMaterial(itemTier); /* Construct initial item */ - itemStack = ItemStackGenerator.generateItemStack(material); + itemStack = ItemStackGenerator.generateItemStack(itemMaterial); itemMeta = itemStack.getItemMeta(); - /* + /* Generate item enchantments - Note: This only applies enchantments up to a certain level, above that threshold item enchantments only exist - in the item lore and get interpreted by the combat system + Note: This only gets a list of enchantments to be applied later at the lore stage */ - if (!enchantments.isEmpty()) - itemMeta = EnchantmentGenerator.generateEnchantments(itemMeta, enchantments); + HashMap enchantmentMap = EnchantmentGenerator.generateEnchantments(itemTier, itemMaterial, itemMeta); /* - Generate item lore + Generate custom enchantments + Note: This only gets a list of enchantments to be applied later at the lore stage */ - itemMeta = LoreGenerator.generateLore(itemMeta, itemMaterial, enchantments, customEnchantments, potionEffects, lore); + HashMap customEnchantmentMap = EnchantmentGenerator.generateCustomEnchantments(itemTier, itemMaterial); /* - Remove vanilla enchantments + Generate item name */ - if (ConfigValues.itemsDropSettingsConfig.getBoolean(ItemsDropSettingsConfig.ENABLE_CUSTOM_ENCHANTMENT_SYSTEM)) - itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); + itemMeta.setDisplayName(NameGenerator.generateName(itemMaterial)); /* - Generate item name last as it relies on material type and quality + Colorize with MMO colors */ - itemMeta.setDisplayName(NameGenerator.generateName(rawName)); + itemStack.setItemMeta(itemMeta); + ItemQualityColorizer.dropQualityColorizer(itemStack); + + return commonFeatures(itemStack, killedMob, player, enchantmentMap, customEnchantmentMap, showItemWorth); + + } + + private static ItemStack commonFeatures(ItemStack itemStack, + EliteEntity eliteEntity, + Player player, + HashMap enchantments, + HashMap customEnchantments, + boolean showItemWorth) { + + ItemMeta itemMeta = itemStack.getItemMeta(); + + //hide default lore + itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); /* - Colorize with MMO colors + Register elite item */ + ItemTagger.registerEliteItem(itemMeta); + + /* + Register item source for lore redraw + */ + ItemTagger.registerItemSource(eliteEntity, itemMeta); + + //Tag the item + ItemTagger.registerEnchantments(itemMeta, enchantments); + ItemTagger.registerCustomEnchantments(itemMeta, customEnchantments); + itemStack.setItemMeta(itemMeta); - ItemQualityColorizer.dropQualityColorizer(itemStack); + + /* + Add soulbind if applicable + */ + SoulbindEnchantment.addEnchantment(itemStack, player); + + /* + Update lore + */ + new EliteItemLore(itemStack, showItemWorth); return itemStack; + } - /* - For procedurally generated items - */ - public static ItemStack constructItem(double itemTier, EliteMobEntity killedMob) { + public static ItemStack constructScrapItem(int scrapLevel, + Player player, + boolean showItemWorth) { ItemStack itemStack; ItemMeta itemMeta; - /* - Generate material - */ - Material itemMaterial = MaterialGenerator.generateMaterial(itemTier); - /* Construct initial item */ - itemStack = ItemStackGenerator.generateItemStack(itemMaterial); + itemStack = ItemStackGenerator.generateItemStack(getScrapMaterial(scrapLevel)); itemMeta = itemStack.getItemMeta(); - /* - Generate item enchantments - Note: This only gets a list of enchantments to be applied later at the lore stage - */ - HashMap enchantmentMap = EnchantmentGenerator.generateEnchantments(itemTier, itemMaterial); + itemMeta.setDisplayName(ChatColorConverter.convert(ItemUpgradeSystemConfig.getScrapItemName().replace("$level", scrapLevel + ""))); /* - Generate custom enchantments - Note: This only gets a list of enchantments to be applied later at the lore stage + Register the elite scrap level */ - HashMap customEnchantmentMap = EnchantmentGenerator.generateCustomEnchantments(itemTier, itemMaterial); + ItemTagger.registerCustomEnchantment(itemMeta, "EliteScrap", scrapLevel); + + itemStack.setItemMeta(itemMeta); /* Generate item lore */ - itemMeta = LoreGenerator.generateLore(itemMeta, itemMaterial, enchantmentMap, customEnchantmentMap, killedMob); + ItemTagger.registerCustomLore(itemMeta, ItemUpgradeSystemConfig.getScrapItemLore()); + + itemStack.setItemMeta(itemMeta); + + return commonFeatures(itemStack, null, player, new HashMap<>(), new HashMap<>(), showItemWorth); + } + + public static ItemStack constructUpgradeItem(int upgradeLevel, + Player player, + boolean showItemWorth) { + + ItemStack itemStack; + ItemMeta itemMeta; /* - Remove vanilla enchantments + Construct initial item */ - if (ConfigValues.itemsDropSettingsConfig.getBoolean(ItemsDropSettingsConfig.ENABLE_CUSTOM_ENCHANTMENT_SYSTEM)) - itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); + itemStack = ItemStackGenerator.generateItemStack(Material.HEART_OF_THE_SEA); + itemMeta = itemStack.getItemMeta(); + + itemMeta.setDisplayName(ChatColorConverter.convert(ItemUpgradeSystemConfig.getUpgradeItemName().replace("$level", upgradeLevel + ""))); /* - Generate item name + Register the elite scrap level */ - itemMeta.setDisplayName(NameGenerator.generateName(itemMaterial)); + ItemTagger.registerCustomEnchantment(itemMeta, "EliteUpgradeItem", upgradeLevel); + + itemStack.setItemMeta(itemMeta); /* - Colorize with MMO colors + Generate item lore */ - itemStack.setItemMeta(itemMeta); - ItemQualityColorizer.dropQualityColorizer(itemStack); + List parsedLore = new ArrayList<>(); + for (String string : ItemUpgradeSystemConfig.getUpgradeItemLore()) + parsedLore.add(string.replace("$orbLevel", upgradeLevel + "").replace("$itemLevel", (upgradeLevel - 1) + "")); + ItemTagger.registerCustomLore(itemMeta, parsedLore); - return itemStack; + itemStack.setItemMeta(itemMeta); + return commonFeatures(itemStack, null, player, new HashMap<>(), new HashMap<>(), showItemWorth); } + private static Material getScrapMaterial(int scrapLevel) { + int dyeTier = (int) Math.floor(scrapLevel / 13.0); + switch (dyeTier) { + case 0: + return Material.WHITE_DYE; + case 1: + return Material.LIGHT_GRAY_DYE; + case 2: + return Material.GRAY_DYE; + case 3: + return Material.GREEN_DYE; + case 4: + return Material.LIGHT_BLUE_DYE; + case 5: + return Material.BLUE_DYE; + case 6: + return Material.CYAN_DYE; + case 7: + return Material.YELLOW_DYE; + case 8: + return Material.ORANGE_DYE; + case 9: + return Material.RED_DYE; + case 10: + return Material.PINK_DYE; + case 11: + return Material.MAGENTA_DYE; + case 12: + return Material.PURPLE_DYE; + case 13: + return Material.BROWN_DYE; + case 14: + default: + return Material.BLACK_DYE; + } + } } diff --git a/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/ItemQualityColorizer.java b/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/ItemQualityColorizer.java index b8b7190be..bcfdf8fd2 100644 --- a/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/ItemQualityColorizer.java +++ b/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/ItemQualityColorizer.java @@ -1,26 +1,9 @@ -/* - * 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 . - */ - package com.magmaguy.elitemobs.items.itemconstructor; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.DefaultConfig; -import com.magmaguy.elitemobs.config.ItemsProceduralSettingsConfig; +import com.magmaguy.elitemobs.config.ItemSettingsConfig; +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfig; import org.bukkit.ChatColor; import org.bukkit.Material; -import org.bukkit.configuration.Configuration; import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; @@ -30,50 +13,9 @@ public class ItemQualityColorizer { - public enum ItemQuality { - LIGHT_BLUE, - GOLD, - PURPLE, - BLUE, - GREEN, - WHITE, - GRAY - } - - /* - item quality: light blue (above max config enchant level) > gold > purple > blue > green > white > gray - */ - private static final int ARROW_DAMAGE = enchantMaxValueGetter(ItemsProceduralSettingsConfig.ARROW_DAMAGE_BOOL, ItemsProceduralSettingsConfig.ARROW_DAMAGE_MAX_LEVEL); - private static final int ARROW_FIRE = enchantMaxValueGetter(ItemsProceduralSettingsConfig.ARROW_FIRE_BOOL, ItemsProceduralSettingsConfig.ARROW_FIRE_MAX_LEVEL); - private static final int ARROW_INFINITE = enchantMaxValueGetter(ItemsProceduralSettingsConfig.ARROW_INFINITE_BOOL); - private static final int ARROW_KNOCKBACK = enchantMaxValueGetter(ItemsProceduralSettingsConfig.ARROW_KNOCKBACK_BOOL, ItemsProceduralSettingsConfig.ARROW_KNOCKBACK_MAX_LEVEL); - private static final int BINDING_CURSE = enchantMaxValueGetter(ItemsProceduralSettingsConfig.BINDING_CURSE_BOOL); - private static final int DAMAGE_ALL = enchantMaxValueGetter(ItemsProceduralSettingsConfig.DAMAGE_ALL_BOOL, ItemsProceduralSettingsConfig.DAMAGE_ALL_MAX_LEVEL); - private static final int DAMAGE_ARTHROPODS = enchantMaxValueGetter(ItemsProceduralSettingsConfig.DAMAGE_ARTHROPODS_BOOL, ItemsProceduralSettingsConfig.DAMAGE_ARTHROPODS_MAX_LEVEL); - private static final int DAMAGE_UNDEAD = enchantMaxValueGetter(ItemsProceduralSettingsConfig.DAMAGE_UNDEAD_BOOL, ItemsProceduralSettingsConfig.DAMAGE_UNDEAD_MAX_LEVEL); - private static final int DEPTH_STRIDER = enchantMaxValueGetter(ItemsProceduralSettingsConfig.DEPTH_STRIDER_BOOL, ItemsProceduralSettingsConfig.DEPTH_STRIDER_MAX_LEVEL); - private static final int DIG_SPEED = enchantMaxValueGetter(ItemsProceduralSettingsConfig.DIG_SPEED_BOOL, ItemsProceduralSettingsConfig.DIG_SPEED_MAX_LEVEL); - private static final int DURABILITY = enchantMaxValueGetter(ItemsProceduralSettingsConfig.DURABILITY_BOOL, ItemsProceduralSettingsConfig.DURABILITY_MAX_LEVEL); - private static final int FIRE_ASPECT = enchantMaxValueGetter(ItemsProceduralSettingsConfig.FIRE_ASPECT_BOOL, ItemsProceduralSettingsConfig.FIRE_ASPECT_MAX_LEVEL); - private static final int FROST_WALKER = enchantMaxValueGetter(ItemsProceduralSettingsConfig.FROST_WALKER_BOOL, ItemsProceduralSettingsConfig.FROST_WALKER_MAX_LEVEL); - private static final int KNOCKBACK = enchantMaxValueGetter(ItemsProceduralSettingsConfig.KNOCKBACK_BOOL, ItemsProceduralSettingsConfig.KNOCKBACK_MAX_LEVEL); - private static final int LOOT_BONUS_BLOCKS = enchantMaxValueGetter(ItemsProceduralSettingsConfig.LOOT_BONUS_BLOCKS_BOOL, ItemsProceduralSettingsConfig.LOOT_BONUS_BLOCKS_MAX_LEVEL); - private static final int LOOT_BONUS_MOBS = enchantMaxValueGetter(ItemsProceduralSettingsConfig.LOOT_BONUS_MOBS_BOOL, ItemsProceduralSettingsConfig.LOOT_BONUS_MOBS_MAX_LEVEL); - private static final int LUCK = enchantMaxValueGetter(ItemsProceduralSettingsConfig.LUCK_BOOL, ItemsProceduralSettingsConfig.LUCK_MAX_LEVEL); - private static final int LURE = enchantMaxValueGetter(ItemsProceduralSettingsConfig.LURE_BOOL, ItemsProceduralSettingsConfig.LURE_MAX_LEVEL); - private static final int MENDING = enchantMaxValueGetter(ItemsProceduralSettingsConfig.MENDING_BOOL); - private static final int OXYGEN = enchantMaxValueGetter(ItemsProceduralSettingsConfig.OXYGEN_BOOL, ItemsProceduralSettingsConfig.OXYGEN_MAX_LEVEL); - private static final int PROTECTION_ENVIRONMENTAL = enchantMaxValueGetter(ItemsProceduralSettingsConfig.PROTECTION_ENVIRONMENTAL_BOOL, ItemsProceduralSettingsConfig.PROTECTION_ENVIRONMENTAL_MAX_LEVEL); - private static final int PROTECTION_EXPLOSIONS = enchantMaxValueGetter(ItemsProceduralSettingsConfig.PROTECTION_EXPLOSIONS_BOOL, ItemsProceduralSettingsConfig.PROTECTION_EXPLOSIONS_MAX_LEVEL); - private static final int PROTECTION_FALL = enchantMaxValueGetter(ItemsProceduralSettingsConfig.PROTECTION_FALL_BOOL, ItemsProceduralSettingsConfig.PROTECTION_FALL_MAX_LEVEL); - private static final int PROTECTION_FIRE = enchantMaxValueGetter(ItemsProceduralSettingsConfig.PROTECTION_FIRE_BOOL, ItemsProceduralSettingsConfig.PROTECTION_FIRE_MAX_LEVEL); - private static final int PROTECTION_PROJECTILE = enchantMaxValueGetter(ItemsProceduralSettingsConfig.PROTECTION_PROJECTILE_BOOL, ItemsProceduralSettingsConfig.PROTECTION_PROJECTILE_MAX_LEVEL); - private static final int SILK_TOUCH = enchantMaxValueGetter(ItemsProceduralSettingsConfig.SILK_TOUCH_BOOL); - private static final int SWEEPING_EDGE = enchantMaxValueGetter(ItemsProceduralSettingsConfig.SWEEPING_EDGE_BOOL, ItemsProceduralSettingsConfig.SWEEPING_EDGE_MAX_LEVEL); - private static final int THORNS = enchantMaxValueGetter(ItemsProceduralSettingsConfig.THORNS_BOOL, ItemsProceduralSettingsConfig.THORNS_MAX_LEVEL); - private static final int VANISHING_CURSE = enchantMaxValueGetter(ItemsProceduralSettingsConfig.VANISHING_CURSE_BOOL); - private static final int WATER_WORKER = enchantMaxValueGetter(ItemsProceduralSettingsConfig.WATER_WORKER_BOOL, ItemsProceduralSettingsConfig.WATER_WORKER_MAX_LEVEL); - + // /* +// item quality: light blue (above max config enchant level) > gold > purple > blue > green > white > gray +// */ public static ItemQuality getItemQuality(ItemStack itemStack) { ItemMeta itemMeta = itemStack.getItemMeta(); @@ -94,9 +36,7 @@ public static ItemQuality getItemQuality(ItemStack itemStack) { //get percentage of max enchants it could have if (maxRankCalculator(itemStack) > 0) { - enchantPercentage = enchantmentCount * 100 / maxRankCalculator(itemStack); - } if (enchantPercentage > 100) @@ -118,7 +58,7 @@ else if (enchantPercentage > 100 / 6 * 1) public static void dropQualityColorizer(ItemStack itemStack) { - if (ConfigValues.defaultConfig.getBoolean(DefaultConfig.MMORPG_COLORS)) { + if (ItemSettingsConfig.isDoMmorpgColors()) { ItemMeta itemMeta = itemStack.getItemMeta(); @@ -216,7 +156,7 @@ Cancel colorization in case item already has a color (for custom and unique item List list = new ArrayList(); - if (!itemMeta.getLore().isEmpty()) { + if (itemMeta.getLore() != null && !itemMeta.getLore().isEmpty()) { for (String string : itemMeta.getLore()) { @@ -243,156 +183,144 @@ private static int maxRankCalculator(ItemStack itemStack) { Material material = itemStack.getType(); - if (material.equals(Material.DIAMOND_SWORD) || material.equals(Material.GOLD_SWORD) || - material.equals(Material.IRON_SWORD) || material.equals(Material.STONE_SWORD) || - material.equals(Material.WOOD_SWORD)) { - - maxRank += DAMAGE_ARTHROPODS; - maxRank += VANISHING_CURSE; - maxRank += FIRE_ASPECT; - maxRank += KNOCKBACK; - maxRank += LOOT_BONUS_MOBS; - maxRank += MENDING; - maxRank += DAMAGE_ALL; - maxRank += DAMAGE_UNDEAD; - maxRank += SWEEPING_EDGE; - maxRank += DURABILITY; - - } else if (material.equals(Material.BOW)) { - - maxRank += VANISHING_CURSE; - maxRank += ARROW_FIRE; - maxRank += ARROW_INFINITE; - maxRank += MENDING; - maxRank += ARROW_DAMAGE; - maxRank += ARROW_KNOCKBACK; - maxRank += DURABILITY; - - } else if (material.equals(Material.DIAMOND_PICKAXE) || material.equals(Material.GOLD_PICKAXE) || - material.equals(Material.IRON_PICKAXE) || material.equals(Material.STONE_PICKAXE) || - material.equals(Material.WOOD_PICKAXE)) { - - maxRank += VANISHING_CURSE; - maxRank += DIG_SPEED; - maxRank += LOOT_BONUS_BLOCKS; - maxRank += MENDING; - maxRank += SILK_TOUCH; - maxRank += DURABILITY; - - } else if (material.equals(Material.DIAMOND_SPADE) || material.equals(Material.GOLD_SPADE) || - material.equals(Material.IRON_SPADE) || material.equals(Material.STONE_SPADE) || - material.equals(Material.WOOD_SPADE)) { - - maxRank += VANISHING_CURSE; - maxRank += DIG_SPEED; - maxRank += LOOT_BONUS_BLOCKS; - maxRank += MENDING; - maxRank += SILK_TOUCH; - maxRank += DURABILITY; - - } else if (material.equals(Material.DIAMOND_HOE) || material.equals(Material.GOLD_HOE) || - material.equals(Material.IRON_HOE) || material.equals(Material.STONE_HOE) || - material.equals(Material.WOOD_HOE)) { - - maxRank += VANISHING_CURSE; - maxRank += MENDING; - maxRank += DURABILITY; - - } else if (material.equals(Material.DIAMOND_AXE) || material.equals(Material.GOLD_AXE) || - material.equals(Material.IRON_AXE) || material.equals(Material.STONE_AXE) || - material.equals(Material.WOOD_AXE)) { - - maxRank += DAMAGE_ARTHROPODS; - maxRank += VANISHING_CURSE; - maxRank += DIG_SPEED; - maxRank += LOOT_BONUS_BLOCKS; - maxRank += MENDING; - maxRank += DAMAGE_ALL; - maxRank += SILK_TOUCH; - maxRank += DAMAGE_UNDEAD; - maxRank += DURABILITY; - - } else if (material.equals(Material.CHAINMAIL_HELMET) || material.equals(Material.DIAMOND_HELMET) || - material.equals(Material.GOLD_HELMET) || material.equals(Material.IRON_HELMET) || - material.equals(Material.LEATHER_HELMET)) { - - maxRank += BINDING_CURSE; - maxRank += DURABILITY; - maxRank += MENDING; - maxRank += OXYGEN; - maxRank += PROTECTION_ENVIRONMENTAL; - maxRank += PROTECTION_EXPLOSIONS; - maxRank += PROTECTION_FIRE; - maxRank += PROTECTION_PROJECTILE; - maxRank += THORNS; - maxRank += VANISHING_CURSE; - maxRank += WATER_WORKER; - - } else if (material.equals(Material.CHAINMAIL_CHESTPLATE) || material.equals(Material.DIAMOND_CHESTPLATE) || - material.equals(Material.GOLD_CHESTPLATE) || material.equals(Material.IRON_CHESTPLATE) || - material.equals(Material.LEATHER_CHESTPLATE)) { - - maxRank += BINDING_CURSE; - maxRank += DURABILITY; - maxRank += MENDING; - maxRank += PROTECTION_ENVIRONMENTAL; - maxRank += PROTECTION_EXPLOSIONS; - maxRank += PROTECTION_FIRE; - maxRank += PROTECTION_PROJECTILE; - maxRank += THORNS; - maxRank += VANISHING_CURSE; - - } else if (material.equals(Material.CHAINMAIL_LEGGINGS) || material.equals(Material.DIAMOND_LEGGINGS) || - material.equals(Material.GOLD_LEGGINGS) || material.equals(Material.IRON_LEGGINGS) || + switch (material) { + case DIAMOND_SWORD: + case GOLDEN_SWORD: + case IRON_SWORD: + case STONE_SWORD: + case WOODEN_SWORD: + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.DAMAGE_ARTHROPODS).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.FIRE_ASPECT).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.KNOCKBACK).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.LOOT_BONUS_BLOCKS).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.MENDING).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.DAMAGE_ALL).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.DAMAGE_UNDEAD).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.SWEEPING_EDGE).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.DURABILITY).getMaxLevel(); + break; + case BOW: + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.ARROW_FIRE).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.ARROW_INFINITE).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.MENDING).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.ARROW_DAMAGE).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.ARROW_KNOCKBACK).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.DURABILITY).getMaxLevel(); + break; + case DIAMOND_PICKAXE: + case GOLDEN_PICKAXE: + case IRON_PICKAXE: + case STONE_PICKAXE: + case WOODEN_PICKAXE: + case DIAMOND_SHOVEL: + case GOLDEN_SHOVEL: + case IRON_SHOVEL: + case STONE_SHOVEL: + case WOODEN_SHOVEL: + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.DIG_SPEED).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.LOOT_BONUS_BLOCKS).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.MENDING).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.SILK_TOUCH).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.DURABILITY).getMaxLevel(); + break; + case DIAMOND_HOE: + case GOLDEN_HOE: + case IRON_HOE: + case STONE_HOE: + case WOODEN_HOE: + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.MENDING).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.DURABILITY).getMaxLevel(); + break; + case DIAMOND_AXE: + case GOLDEN_AXE: + case IRON_AXE: + case STONE_AXE: + case WOODEN_AXE: + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.DAMAGE_ARTHROPODS).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.DIG_SPEED).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.LOOT_BONUS_BLOCKS).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.MENDING).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.DAMAGE_ALL).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.SILK_TOUCH).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.DAMAGE_UNDEAD).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.DURABILITY).getMaxLevel(); + break; + case CHAINMAIL_HELMET: + case DIAMOND_HELMET: + case GOLDEN_HELMET: + case IRON_HELMET: + case LEATHER_HELMET: + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.DURABILITY).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.MENDING).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.OXYGEN).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.PROTECTION_EXPLOSIONS).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.PROTECTION_FIRE).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.PROTECTION_PROJECTILE).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.THORNS).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.WATER_WORKER).getMaxLevel(); + break; + case CHAINMAIL_CHESTPLATE: + case DIAMOND_CHESTPLATE: + case GOLDEN_CHESTPLATE: + case IRON_CHESTPLATE: + case LEATHER_CHESTPLATE: + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.DURABILITY).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.MENDING).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.PROTECTION_EXPLOSIONS).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.PROTECTION_FIRE).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.PROTECTION_PROJECTILE).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.THORNS).getMaxLevel(); + break; + + } + + + if (material.equals(Material.CHAINMAIL_LEGGINGS) || material.equals(Material.DIAMOND_LEGGINGS) || + material.equals(Material.GOLDEN_LEGGINGS) || material.equals(Material.IRON_LEGGINGS) || material.equals(Material.LEATHER_LEGGINGS)) { - maxRank += BINDING_CURSE; - maxRank += DURABILITY; - maxRank += MENDING; - maxRank += PROTECTION_ENVIRONMENTAL; - maxRank += PROTECTION_EXPLOSIONS; - maxRank += PROTECTION_FIRE; - maxRank += PROTECTION_PROJECTILE; - maxRank += THORNS; - maxRank += VANISHING_CURSE; + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.DURABILITY).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.MENDING).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.PROTECTION_EXPLOSIONS).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.PROTECTION_FIRE).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.PROTECTION_PROJECTILE).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.THORNS).getMaxLevel(); } else if (material.equals(Material.CHAINMAIL_BOOTS) || material.equals(Material.DIAMOND_BOOTS) || - material.equals(Material.GOLD_BOOTS) || material.equals(Material.IRON_BOOTS) || + material.equals(Material.GOLDEN_BOOTS) || material.equals(Material.IRON_BOOTS) || material.equals(Material.LEATHER_BOOTS)) { - maxRank += BINDING_CURSE; - maxRank += DURABILITY; - maxRank += MENDING; - maxRank += PROTECTION_ENVIRONMENTAL; - maxRank += PROTECTION_EXPLOSIONS; - maxRank += PROTECTION_FALL; - maxRank += PROTECTION_FIRE; - maxRank += PROTECTION_PROJECTILE; - maxRank += THORNS; - maxRank += VANISHING_CURSE; - maxRank += DEPTH_STRIDER; - maxRank += FROST_WALKER; + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.DURABILITY).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.MENDING).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.PROTECTION_ENVIRONMENTAL).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.PROTECTION_EXPLOSIONS).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.PROTECTION_FALL).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.PROTECTION_FIRE).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.PROTECTION_PROJECTILE).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.THORNS).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.DEPTH_STRIDER).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.FROST_WALKER).getMaxLevel(); } else if (material.equals(Material.SHEARS)) { - maxRank += VANISHING_CURSE; - maxRank += DIG_SPEED; - maxRank += MENDING; - maxRank += DURABILITY; + EnchantmentsConfig.getEnchantment(Enchantment.DIG_SPEED).getMaxLevel(); + EnchantmentsConfig.getEnchantment(Enchantment.MENDING).getMaxLevel(); + EnchantmentsConfig.getEnchantment(Enchantment.DURABILITY).getMaxLevel(); } else if (material.equals(Material.FISHING_ROD)) { - maxRank += VANISHING_CURSE; - maxRank += DURABILITY; - maxRank += MENDING; - maxRank += LUCK; - maxRank += LURE; + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.DURABILITY).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.MENDING).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.LUCK).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.LURE).getMaxLevel(); } else if (material.equals(Material.SHIELD)) { - maxRank += VANISHING_CURSE; - maxRank += DURABILITY; - maxRank += MENDING; + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.DURABILITY).getMaxLevel(); + maxRank += EnchantmentsConfig.getEnchantment(Enchantment.MENDING).getMaxLevel(); } @@ -400,32 +328,14 @@ private static int maxRankCalculator(ItemStack itemStack) { } - private static int enchantMaxValueGetter(String boolString) { - - Configuration configuration = ConfigValues.itemsProceduralSettingsConfig; - - if (configuration.getBoolean(boolString)) { - - return 1; - - } - - return 0; - - } - - private static int enchantMaxValueGetter(String boolString, String maxLevelString) { - - Configuration configuration = ConfigValues.itemsProceduralSettingsConfig; - - if (configuration.getBoolean(boolString)) { - - return configuration.getInt(maxLevelString); - - } - - return 0; - + public enum ItemQuality { + LIGHT_BLUE, + GOLD, + PURPLE, + BLUE, + GREEN, + WHITE, + GRAY } } diff --git a/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/ItemStackGenerator.java b/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/ItemStackGenerator.java deleted file mode 100644 index 31c1e97b4..000000000 --- a/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/ItemStackGenerator.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.magmaguy.elitemobs.items.itemconstructor; - -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; - -public class ItemStackGenerator { - - public static ItemStack generateItemStack (Material material){ - - return new ItemStack(material); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/LoreGenerator.java b/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/LoreGenerator.java deleted file mode 100644 index 98647772e..000000000 --- a/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/LoreGenerator.java +++ /dev/null @@ -1,374 +0,0 @@ -package com.magmaguy.elitemobs.items.itemconstructor; - -import com.magmaguy.elitemobs.ChatColorConverter; -import com.magmaguy.elitemobs.config.*; -import com.magmaguy.elitemobs.items.ItemTierFinder; -import com.magmaguy.elitemobs.items.ItemWorthCalculator; -import com.magmaguy.elitemobs.items.ObfuscatedSignatureLoreData; -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.entity.LivingEntity; -import org.bukkit.inventory.meta.ItemMeta; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public class LoreGenerator { - - public static ItemMeta generateLore(ItemMeta itemMeta, Material material, HashMap enchantmentMap, - HashMap customEnchantments, List potionList, List loreList) { - - List lore = new ArrayList<>(); - - for (Object object : ConfigValues.itemsCustomLootSettingsConfig.getList(ItemsCustomLootSettingsConfig.LORE_STRUCTURE)) { - - String string = (String) object; - - if (string.contains("$enchantments")) { - if (ConfigValues.itemsDropSettingsConfig.getBoolean(ItemsDropSettingsConfig.ENABLE_CUSTOM_ENCHANTMENT_SYSTEM)) { - if (!enchantmentMap.isEmpty()) { - lore.addAll(enchantmentLore(enchantmentMap)); - lore.addAll(customEnchantmentLore(customEnchantments)); - } - } - } else if (string.contains("$potionEffect")) - lore.addAll(potionsLore(potionList)); - else if (string.contains("$itemValue")) - lore.add(itemWorth(material, enchantmentMap, potionList)); - else if (string.contains("$tier")) - lore.add(string.replace("$tier", ItemTierFinder.findGenericTier(material, enchantmentMap) + "")); - else if (string.contains("$customLore")) { - if (loreList != null) - lore.addAll(colorizedLore(loreList)); - } else - lore.add(string); - - } - - /* - Obfuscate potion and enchantment info - */ - lore = generateObfuscatedLore(lore, getObfuscatedLoreString(enchantmentMap, customEnchantments, potionList)); - itemMeta.setLore(lore); - - return itemMeta; - - } - - public static ItemMeta generateLore(ItemMeta itemMeta, Material material, HashMap enchantmentMap, - HashMap customEnchantments, EliteMobEntity eliteMobEntity) { - - List lore = new ArrayList<>(); - - itemMeta = applyVanillaEnchantments(enchantmentMap, itemMeta); - - for (Object object : ConfigValues.itemsProceduralSettingsConfig.getList(ItemsProceduralSettingsConfig.LORE_STRUCTURE)) { - - String string = (String) object; - - if (string.contains("$potionEffect")) { - //TODO: Add potion effects to dynamic items - } else if (string.contains("$enchantments")) { - if (ConfigValues.itemsDropSettingsConfig.getBoolean(ItemsDropSettingsConfig.ENABLE_CUSTOM_ENCHANTMENT_SYSTEM)) { - lore.addAll(enchantmentLore(enchantmentMap)); - lore.addAll(customEnchantmentLore(customEnchantments)); - } - } else if (string.contains("$itemValue")) - lore.add(itemWorth(material, enchantmentMap)); - else if (string.contains("$tier")) - lore.add(string.replace("$tier", ItemTierFinder.findGenericTier(material, enchantmentMap) + "")); - else if (string.equals("$itemSource")) - lore.add(itemSource(eliteMobEntity)); - else - lore.add(string); - - } - - /* - Obfuscate potion and enchantment info - */ - lore = generateObfuscatedLore(lore, getObfuscatedLoreString(enchantmentMap, customEnchantments)); - itemMeta.setLore(lore); - - return itemMeta; - - } - - - private static List generateObfuscatedLore(List loreList, String obfuscatedLoreString) { - - List newList = new ArrayList<>(); - - int counter = 0; - - for (String string : loreList) { - - if (counter == 0) - newList.add(string + obfuscatedLoreString); - else - newList.add(string); - - counter++; - - } - - return newList; - - } - - public static final String OBFUSCATED_ENCHANTMENTS = "EliteEnchantments"; - public static final String OBFUSCATED_CUSTOM_ENCHANTMENTS = "EliteCustomEnchantments"; - public static final String OBFUSCATED_POTIONS = "ElitePotions"; - - private static String getObfuscatedLoreString(HashMap enchantmentMap, HashMap customEnchantments, List potionList) { - - StringBuilder obfuscatedString = new StringBuilder(); - - obfuscatedString.append(ObfuscatedSignatureLoreData.ITEM_SIGNATURE).append(","); - - if (!enchantmentMap.isEmpty()) { - obfuscatedString.append(OBFUSCATED_ENCHANTMENTS).append(","); - for (Enchantment enchantment : enchantmentMap.keySet()) - if (enchantment != null) - obfuscatedString.append(enchantment.getName()).append(":").append(enchantmentMap.get(enchantment)).append(","); - } - - if (!customEnchantments.isEmpty()) { - obfuscatedString.append(OBFUSCATED_CUSTOM_ENCHANTMENTS).append(","); - for (String string : customEnchantments.keySet()) - obfuscatedString.append(string).append(":").append(customEnchantments.get(string)).append(","); - } - - if (potionList != null && !potionList.isEmpty()) { - obfuscatedString.append(OBFUSCATED_POTIONS).append(","); - for (String string : potionList) - obfuscatedString.append(string.replace(",", ":")).append(","); - } - - String finalString = stringObfuscator(obfuscatedString); - - return finalString; - - } - - private static String getObfuscatedLoreString(HashMap enchantmentMap, HashMap customEnchantments) { - - StringBuilder obfuscatedString = new StringBuilder(); - - obfuscatedString.append(ObfuscatedSignatureLoreData.ITEM_SIGNATURE); - - if (!enchantmentMap.isEmpty()) { - obfuscatedString.append(OBFUSCATED_ENCHANTMENTS).append(","); - for (Enchantment enchantment : enchantmentMap.keySet()) - obfuscatedString.append(enchantment.getName()).append(":").append(enchantmentMap.get(enchantment)).append(","); - } - - if (!customEnchantments.isEmpty()){ - obfuscatedString.append(OBFUSCATED_CUSTOM_ENCHANTMENTS).append(","); - for (String string: customEnchantments.keySet()) - obfuscatedString.append(string).append(":").append(customEnchantments.get(string)).append(","); - } - - String finalString = stringObfuscator(obfuscatedString); - - return finalString; - - } - - private static String stringObfuscator(StringBuilder originalString) { - - String insert = "§"; - int period = 1; - - StringBuilder stringBuilder = new StringBuilder(originalString.length() + insert.length() * (originalString.length() / period)); - - int index = 0; - String prefix = ""; - - while (index < originalString.length()) { - - stringBuilder.append(prefix); - prefix = insert; - stringBuilder.append(originalString, index, Math.min(index + period, originalString.length())); - index += period; - - } - - String finalString = stringBuilder.toString(); - - finalString = "§" + finalString; - - return finalString; - - } - - private static List enchantmentLore(HashMap enchantmentMap) { - - List enchantmentsLore = new ArrayList<>(); - - for (Enchantment enchantment : enchantmentMap.keySet()) { - String loreLine; - if (enchantment.getName().contains("CURSE")) - loreLine = ChatColorConverter.convert("&c" + getEnchantmentName(enchantment) + " " + enchantmentMap.get(enchantment)); - else - loreLine = ChatColorConverter.convert("&7" + getEnchantmentName(enchantment) + " " + enchantmentMap.get(enchantment)); - enchantmentsLore.add(loreLine); - } - - return enchantmentsLore; - - } - - private static String getEnchantmentName(Enchantment enchantment) { - - if (!ConfigValues.itemsDropSettingsConfig.getKeys(true).contains(ItemsDropSettingsConfig.ENCHANTMENT_NAME + enchantment.getName())) { - Bukkit.getLogger().warning("[EliteMobs] Missing enchantment name " + enchantment.getName()); - Bukkit.getLogger().warning("[EliteMobs] Report this to the dev!"); - return enchantment.getName(); - } - - return ConfigValues.itemsDropSettingsConfig.getString(ItemsDropSettingsConfig.ENCHANTMENT_NAME + enchantment.getName()); - - } - - private static List customEnchantmentLore(HashMap customEnchantments) { - - List customEnchantmentLore = new ArrayList<>(); - - for (String string : customEnchantments.keySet()) { - - String loreLine; - loreLine = ChatColorConverter.convert("&6" + getCustomEnchantmentName(string) + " " + customEnchantments.get(string)); - customEnchantmentLore.add(loreLine); - - } - - return customEnchantmentLore; - - } - - private static String getCustomEnchantmentName(String customEnchantmentKey) { - - if (!ConfigValues.itemsDropSettingsConfig.getKeys(true).contains(ItemsDropSettingsConfig.ENCHANTMENT_NAME + customEnchantmentKey)) { - - Bukkit.getLogger().warning("[EliteMobs] Missing enchantment name " + customEnchantmentKey); - Bukkit.getLogger().warning("[EliteMobs] Report this to the dev!"); - return customEnchantmentKey; - - } - - return ConfigValues.itemsDropSettingsConfig.getString(ItemsDropSettingsConfig.ENCHANTMENT_NAME + customEnchantmentKey); - - } - - private static ItemMeta applyVanillaEnchantments(HashMap enchantmentMap, ItemMeta itemMeta) { - - for (Enchantment enchantment : enchantmentMap.keySet()) { - if (enchantmentMap.get(enchantment) > 5) - itemMeta.addEnchant(enchantment, 5, true); - else - itemMeta.addEnchant(enchantment, enchantmentMap.get(enchantment), true); - } - - return itemMeta; - - } - - private static List potionsLore(List potionList) { - - List potionsLore = new ArrayList<>(); - - - if (potionList == null || potionList.isEmpty()) return potionsLore; - - for (String string : potionList) { - String loreLine = ChatColorConverter.convert("&2" + getPotionName(string.split(",")[0]) + " " + string.split(",")[1]); - potionsLore.add(loreLine); - } - - return potionsLore; - - } - - private static String getPotionName(String string) { - - if (!ConfigValues.itemsDropSettingsConfig.getKeys(true).contains(ItemsDropSettingsConfig.POTION_EFFECT_NAME + string)) { - Bukkit.getLogger().warning("[EliteMobs] Missing potion name " + string); - Bukkit.getLogger().warning("[EliteMobs] Report this to the dev!"); - return string; - } - - return ConfigValues.itemsDropSettingsConfig.getString(ItemsDropSettingsConfig.POTION_EFFECT_NAME + string); - - } - - private static String itemWorth(Material material, HashMap enchantmentMap, List potionList) { - - return ConfigValues.itemsDropSettingsConfig.getString(ItemsDropSettingsConfig.LORE_WORTH) - .replace("$worth", ItemWorthCalculator.determineItemWorth(material, enchantmentMap, potionList) + "") - .replace("$currencyName", ConfigValues.economyConfig.getString(EconomySettingsConfig.CURRENCY_NAME)); - - } - - private static String itemWorth(Material material, HashMap enchantmentMap) { - - return ConfigValues.itemsDropSettingsConfig.getString(ItemsDropSettingsConfig.LORE_WORTH) - .replace("$worth", ItemWorthCalculator.determineItemWorth(material, enchantmentMap) + "") - .replace("$currencyName", ConfigValues.economyConfig.getString(EconomySettingsConfig.CURRENCY_NAME)); - - } - - private static String itemSource(EliteMobEntity eliteMobEntity) { - - LivingEntity livingEntity = eliteMobEntity.getLivingEntity(); - - String itemSource; - - if (livingEntity != null) { - - itemSource = ConfigValues.itemsProceduralSettingsConfig.getString(ItemsProceduralSettingsConfig.LORE_MOB_LEVEL_SOURCE).replace("$level", - eliteMobEntity.getLevel() + ""); - - String newName = ""; - - if (livingEntity.getType().name().contains("_")) { - - String[] tempSubList = livingEntity.getType().name().split("_"); - - for (String string : tempSubList) { - - string = string.toLowerCase().substring(0, 1).toUpperCase() + " "; - newName += string; - - } - - } else - newName = livingEntity.getType().name().substring(0, 1) + livingEntity.getType().name().substring(1).toLowerCase(); - - - itemSource = itemSource.replace("$mob", newName); - - - } else - itemSource = ConfigValues.itemsProceduralSettingsConfig.getString(ItemsProceduralSettingsConfig.LORE_SHOP_SOURCE); - - - return itemSource; - - } - - private static List colorizedLore(List rawLore) { - - List colorizedLore = new ArrayList<>(); - - for (String string : rawLore) - colorizedLore.add(ChatColorConverter.convert(string)); - - return colorizedLore; - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/MaterialGenerator.java b/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/MaterialGenerator.java index 7c40f3703..d64251773 100644 --- a/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/MaterialGenerator.java +++ b/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/MaterialGenerator.java @@ -1,8 +1,9 @@ package com.magmaguy.elitemobs.items.itemconstructor; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.ItemsProceduralSettingsConfig; -import com.magmaguy.elitemobs.mobconstructor.CombatSystem; +import com.magmaguy.elitemobs.combatsystem.CombatSystem; +import com.magmaguy.elitemobs.config.ItemSettingsConfig; +import com.magmaguy.elitemobs.config.ProceduralItemGenerationSettingsConfig; +import com.magmaguy.elitemobs.utils.WarningMessage; import org.bukkit.Bukkit; import org.bukkit.Material; @@ -14,53 +15,51 @@ public class MaterialGenerator { - public static Material generateMaterial(Material material){ + private static final ArrayList validProceduralMaterials = new ArrayList(); + + public static Material generateMaterial(Material material) { return material; } - public static Material generateMaterial(double itemTier){ + public static Material generateMaterial(double itemTier) { - List localValidMaterials = intializeValidProceduralMaterials(); + List localValidMaterials = (List) validProceduralMaterials.clone(); - if (localValidMaterials.isEmpty()) intializeValidProceduralMaterials(); + if (localValidMaterials.isEmpty()) initializeValidProceduralMaterials(); - if (itemTier < CombatSystem.DIAMOND_TIER_LEVEL) { + if (itemTier < CombatSystem.TRIDENT_TIER_LEVEL + ItemSettingsConfig.getMinimumProcedurallyGeneratedDiamondLootLevelPlusSeven()) + localValidMaterials.remove(TRIDENT); - localValidMaterials.remove(DIAMOND); + if (itemTier < CombatSystem.DIAMOND_TIER_LEVEL + ItemSettingsConfig.getMinimumProcedurallyGeneratedDiamondLootLevelPlusSeven()) { localValidMaterials.remove(DIAMOND_AXE); - localValidMaterials.remove(DIAMOND_BARDING); - localValidMaterials.remove(DIAMOND_BLOCK); + localValidMaterials.remove(DIAMOND_HORSE_ARMOR); localValidMaterials.remove(DIAMOND_CHESTPLATE); localValidMaterials.remove(DIAMOND_HELMET); localValidMaterials.remove(DIAMOND_HOE); localValidMaterials.remove(DIAMOND_LEGGINGS); - localValidMaterials.remove(DIAMOND_ORE); localValidMaterials.remove(DIAMOND_PICKAXE); - localValidMaterials.remove(DIAMOND_SPADE); + localValidMaterials.remove(DIAMOND_SHOVEL); localValidMaterials.remove(DIAMOND_SWORD); localValidMaterials.remove(DIAMOND_BOOTS); - } if (itemTier < CombatSystem.IRON_TIER_LEVEL) { localValidMaterials.remove(IRON_AXE); - localValidMaterials.remove(IRON_BARDING); - localValidMaterials.remove(IRON_BLOCK); + localValidMaterials.remove(IRON_HORSE_ARMOR); localValidMaterials.remove(IRON_BOOTS); localValidMaterials.remove(IRON_CHESTPLATE); localValidMaterials.remove(IRON_HELMET); localValidMaterials.remove(IRON_HOE); - localValidMaterials.remove(IRON_INGOT); localValidMaterials.remove(IRON_LEGGINGS); - localValidMaterials.remove(IRON_NUGGET); - localValidMaterials.remove(IRON_ORE); localValidMaterials.remove(IRON_PICKAXE); - localValidMaterials.remove(IRON_SPADE); + localValidMaterials.remove(IRON_SHOVEL); localValidMaterials.remove(IRON_SWORD); - + localValidMaterials.remove(BOW); + localValidMaterials.remove(CROSSBOW); + localValidMaterials.remove(TURTLE_HELMET); } if (itemTier < CombatSystem.STONE_CHAIN_TIER_LEVEL) { @@ -71,42 +70,49 @@ public static Material generateMaterial(double itemTier){ localValidMaterials.remove(CHAINMAIL_LEGGINGS); localValidMaterials.remove(STONE_SWORD); localValidMaterials.remove(STONE_HOE); - localValidMaterials.remove(STONE_SPADE); + localValidMaterials.remove(STONE_SHOVEL); localValidMaterials.remove(STONE_PICKAXE); localValidMaterials.remove(STONE_AXE); } - int index = ThreadLocalRandom.current().nextInt(localValidMaterials.size()); - - Material material = localValidMaterials.get(index); + if (itemTier < CombatSystem.GOLD_WOOD_LEATHER_TIER_LEVEL) { + localValidMaterials.remove(GOLDEN_BOOTS); + localValidMaterials.remove(GOLDEN_CHESTPLATE); + localValidMaterials.remove(GOLDEN_HELMET); + localValidMaterials.remove(GOLDEN_LEGGINGS); + localValidMaterials.remove(GOLDEN_SWORD); + localValidMaterials.remove(GOLDEN_HOE); + localValidMaterials.remove(GOLDEN_SHOVEL); + localValidMaterials.remove(GOLDEN_PICKAXE); + localValidMaterials.remove(GOLDEN_AXE); + } - return material; + return localValidMaterials.get(ThreadLocalRandom.current().nextInt(localValidMaterials.size())); } - private static List intializeValidProceduralMaterials(){ + public static void initializeValidProceduralMaterials() { - List validMaterials = new ArrayList<>(); + validProceduralMaterials.clear(); - for (Object object : ConfigValues.itemsProceduralSettingsConfig.getList(ItemsProceduralSettingsConfig.PROCEDURAL_ITEM_VALID_MATERIALS)) { + if (ProceduralItemGenerationSettingsConfig.getValidMaterials().isEmpty()) { + ProceduralItemGenerationSettingsConfig.cacheMaterials(); + if (ProceduralItemGenerationSettingsConfig.getValidMaterials().isEmpty()) { + new WarningMessage("No valid materials detected for the procedural item settings. If you are trying to disable" + + " them, use the 'dropProcedurallyGeneratedItems' option instead. Warn the developer."); + return; + } + } + for (String string : ProceduralItemGenerationSettingsConfig.getValidMaterials()) { try { - - Material parsedMaterial = getMaterial(object.toString()); - validMaterials.add(parsedMaterial); - + validProceduralMaterials.add(getMaterial(string)); } catch (Exception e) { - - Bukkit.getLogger().info("Invalid material type detected: " + object.toString()); - + Bukkit.getLogger().info("Invalid material type detected: " + string); } - - } - return validMaterials; - } } diff --git a/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/NameGenerator.java b/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/NameGenerator.java index b56ee8c6c..229bee784 100644 --- a/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/NameGenerator.java +++ b/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/NameGenerator.java @@ -1,33 +1,32 @@ package com.magmaguy.elitemobs.items.itemconstructor; import com.magmaguy.elitemobs.ChatColorConverter; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.ItemsProceduralSettingsConfig; +import com.magmaguy.elitemobs.config.ProceduralItemGenerationSettingsConfig; +import com.magmaguy.elitemobs.utils.WarningMessage; import org.bukkit.Bukkit; import org.bukkit.Material; -import java.util.ArrayList; +import java.util.List; import java.util.concurrent.ThreadLocalRandom; public class NameGenerator { + private static final List nouns = ProceduralItemGenerationSettingsConfig.getNouns(); + private static final List adjectives = ProceduralItemGenerationSettingsConfig.getAdjectives(); + private static final List verbs = ProceduralItemGenerationSettingsConfig.getVerbs(); + private static final List verbers = ProceduralItemGenerationSettingsConfig.getVerbers(); - public static String generateName(String rawName) { + private NameGenerator() { + } + public static String generateName(String rawName) { return ChatColorConverter.convert(rawName); - } - private static ArrayList nouns = (ArrayList) ConfigValues.itemsProceduralSettingsConfig.getList("Valid nouns"); - private static ArrayList adjectives = (ArrayList) ConfigValues.itemsProceduralSettingsConfig.getList("Valid adjectives"); - private static ArrayList verbs = (ArrayList) ConfigValues.itemsProceduralSettingsConfig.getList("Valid verbs"); - private static ArrayList verbers = (ArrayList) ConfigValues.itemsProceduralSettingsConfig.getList("Valid verb-er (noun)"); - public static String generateName(Material material) { - int nounConstructorSelector = ThreadLocalRandom.current().nextInt(ConfigValues.itemsProceduralSettingsConfig.getList(ItemsProceduralSettingsConfig.ITEM_NAME_FORMAT).size()); + int nounConstructorSelector = ThreadLocalRandom.current().nextInt(ProceduralItemGenerationSettingsConfig.getNameFormat().size()); - return ((String) ConfigValues.itemsProceduralSettingsConfig.getList(ItemsProceduralSettingsConfig.ITEM_NAME_FORMAT) - .get(nounConstructorSelector)) + return (ProceduralItemGenerationSettingsConfig.getNameFormat().get(nounConstructorSelector)) .replace("$noun", nouns.get(ThreadLocalRandom.current().nextInt(nouns.size()))) .replace("$verb-er", verbers.get(ThreadLocalRandom.current().nextInt(verbers.size()))) .replace("$verb", verbs.get(ThreadLocalRandom.current().nextInt(verbs.size()))) @@ -40,72 +39,80 @@ private static String materialStringParser(Material material) { switch (material) { case DIAMOND_SWORD: - case GOLD_SWORD: + case GOLDEN_SWORD: case IRON_SWORD: case STONE_SWORD: - case WOOD_SWORD: - return ConfigValues.itemsProceduralSettingsConfig.getString(ItemsProceduralSettingsConfig.SWORD_MATERIAL_NAME); + case WOODEN_SWORD: + return ProceduralItemGenerationSettingsConfig.getSwordName(); case BOW: - return ConfigValues.itemsProceduralSettingsConfig.getString(ItemsProceduralSettingsConfig.BOW_MATERIAL_NAME); + return ProceduralItemGenerationSettingsConfig.getBowName(); case DIAMOND_PICKAXE: - case GOLD_PICKAXE: + case GOLDEN_PICKAXE: case IRON_PICKAXE: case STONE_PICKAXE: - case WOOD_PICKAXE: - return ConfigValues.itemsProceduralSettingsConfig.getString(ItemsProceduralSettingsConfig.PICKAXE_MATERIAL_NAME); - case DIAMOND_SPADE: - case GOLD_SPADE: - case IRON_SPADE: - case STONE_SPADE: - case WOOD_SPADE: - return ConfigValues.itemsProceduralSettingsConfig.getString(ItemsProceduralSettingsConfig.SPADE_MATERIAL_NAME); + case WOODEN_PICKAXE: + return ProceduralItemGenerationSettingsConfig.getPickaxeName(); + case DIAMOND_SHOVEL: + case GOLDEN_SHOVEL: + case IRON_SHOVEL: + case STONE_SHOVEL: + case WOODEN_SHOVEL: + return ProceduralItemGenerationSettingsConfig.getSpadeName(); case DIAMOND_HOE: - case GOLD_HOE: + case GOLDEN_HOE: case IRON_HOE: case STONE_HOE: - case WOOD_HOE: - return ConfigValues.itemsProceduralSettingsConfig.getString(ItemsProceduralSettingsConfig.HOE_MATERIAL_NAME); + case WOODEN_HOE: + return ProceduralItemGenerationSettingsConfig.getHoeName(); case DIAMOND_AXE: - case GOLD_AXE: + case GOLDEN_AXE: case IRON_AXE: case STONE_AXE: - case WOOD_AXE: - return ConfigValues.itemsProceduralSettingsConfig.getString(ItemsProceduralSettingsConfig.AXE_MATERIAL_NAME); + case WOODEN_AXE: + return ProceduralItemGenerationSettingsConfig.getAxeName(); case CHAINMAIL_HELMET: case DIAMOND_HELMET: - case GOLD_HELMET: + case GOLDEN_HELMET: case IRON_HELMET: case LEATHER_HELMET: - return ConfigValues.itemsProceduralSettingsConfig.getString(ItemsProceduralSettingsConfig.HELMET_MATERIAL_NAME); + case TURTLE_HELMET: + return ProceduralItemGenerationSettingsConfig.getHelmetName(); case CHAINMAIL_CHESTPLATE: case DIAMOND_CHESTPLATE: - case GOLD_CHESTPLATE: + case GOLDEN_CHESTPLATE: case IRON_CHESTPLATE: case LEATHER_CHESTPLATE: - return ConfigValues.itemsProceduralSettingsConfig.getString(ItemsProceduralSettingsConfig.CHESTPLATE_MATERIAL_NAME); + return ProceduralItemGenerationSettingsConfig.getChestplateName(); case CHAINMAIL_LEGGINGS: case DIAMOND_LEGGINGS: - case GOLD_LEGGINGS: + case GOLDEN_LEGGINGS: case IRON_LEGGINGS: case LEATHER_LEGGINGS: - return ConfigValues.itemsProceduralSettingsConfig.getString(ItemsProceduralSettingsConfig.LEGGINGS_MATERIAL_NAME); + return ProceduralItemGenerationSettingsConfig.getLeggingsName(); case CHAINMAIL_BOOTS: case DIAMOND_BOOTS: - case GOLD_BOOTS: + case GOLDEN_BOOTS: case IRON_BOOTS: case LEATHER_BOOTS: - return ConfigValues.itemsProceduralSettingsConfig.getString(ItemsProceduralSettingsConfig.BOOTS_MATERIAL_NAME); + return ProceduralItemGenerationSettingsConfig.getBootsName(); case SHEARS: - return ConfigValues.itemsProceduralSettingsConfig.getString(ItemsProceduralSettingsConfig.SHEARS_MATERIAL_NAME); + return ProceduralItemGenerationSettingsConfig.getShearsName(); case FISHING_ROD: - return ConfigValues.itemsProceduralSettingsConfig.getString(ItemsProceduralSettingsConfig.FISHING_ROD_MATERIAL_NAME); + return ProceduralItemGenerationSettingsConfig.getFishingRodName(); case SHIELD: - return ConfigValues.itemsProceduralSettingsConfig.getString(ItemsProceduralSettingsConfig.SHIELD_MATERIAL_NAME); + return ProceduralItemGenerationSettingsConfig.getShieldName(); + case TRIDENT: + return ProceduralItemGenerationSettingsConfig.getTridentName(); + case CROSSBOW: + return ProceduralItemGenerationSettingsConfig.getCrossbowName(); } + if (ProceduralItemGenerationSettingsConfig.getFileConfiguration().getString("materialNames." + material.toString().toLowerCase()) != null) + return ProceduralItemGenerationSettingsConfig.getFileConfiguration().getString("materialNames." + material.toString().toLowerCase()); Bukkit.getLogger().warning("[EliteMobs] Found unexpected material type in procedurally generated loot. Can't generate item type name."); - Bukkit.getLogger().warning("[EliteMobs] Material name: " + material.toString()); + Bukkit.getLogger().warning("[EliteMobs] Material name: " + material); + new WarningMessage("If you're trying to set a non-default item type, you need to add the name format like this under materialNames: " + material.toString().toLowerCase() + ": Name"); return ""; } diff --git a/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/ScalabilityAssigner.java b/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/ScalabilityAssigner.java deleted file mode 100644 index 073ce21a5..000000000 --- a/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/ScalabilityAssigner.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.magmaguy.elitemobs.items.itemconstructor; - -import com.magmaguy.elitemobs.items.ItemTierFinder; -import com.magmaguy.elitemobs.items.ScalableItemConstructor; -import org.bukkit.Material; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.ItemStack; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; - -public class ScalabilityAssigner { - - public static void assign(ItemStack itemStack, String rawName, Material material, HashMap enchantments, HashMap customEnchantments, List potionEffects, - List lore, String dropType, String scalabilityType) { - - /* - For the sake of clarity for the users and just overall reliability scalability will only be assigned to dynamic - items, and all static items will be considered statically scalable - */ - if (!DropWeightHandler.isDynamic(dropType)) return; - if (!isScalable(scalabilityType)) return; - - ScallableItemObject scalableItemObject = new ScallableItemObject(); - scalableItemObject.initializeItemObject(rawName, material, enchantments, customEnchantments, potionEffects, - lore); - - if (scalabilityType == null || scalabilityType.equalsIgnoreCase("dynamic")) { - ScalableItemConstructor.dynamicallyScalableItems.add(scalableItemObject); - return; - } - - if (scalabilityType.equalsIgnoreCase("limited")) { - - int itemTier = (int) ItemTierFinder.findBattleTier(itemStack); - - if (!ScalableItemConstructor.limitedScalableItems.containsKey(itemTier)) - ScalableItemConstructor.limitedScalableItems.put((int) ItemTierFinder.findBattleTier(itemStack), new ArrayList<>(Arrays.asList(scalableItemObject))); - else { - List existingList = ScalableItemConstructor.limitedScalableItems.get(itemTier); - existingList.add(scalableItemObject); - ScalableItemConstructor.limitedScalableItems.put((int) ItemTierFinder.findBattleTier(itemStack), existingList); - } - - } - - if (scalabilityType.equalsIgnoreCase("static")) { - - int itemTier = (int) ItemTierFinder.findBattleTier(itemStack); - - if (!ScalableItemConstructor.staticItems.containsKey(itemTier)) - ScalableItemConstructor.staticItems.put((int) ItemTierFinder.findBattleTier(itemStack), new ArrayList<>(Arrays.asList(itemStack))); - else { - List existingList = ScalableItemConstructor.staticItems.get(itemTier); - existingList.add(itemStack); - ScalableItemConstructor.staticItems.put((int) ItemTierFinder.findBattleTier(itemStack), existingList); - } - - } - - } - - public static boolean isScalable(String scalabilityType) { - - return scalabilityType == null || scalabilityType.equalsIgnoreCase("dynamic") || scalabilityType.equalsIgnoreCase("dynamic_full"); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/ScallableItemObject.java b/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/ScallableItemObject.java deleted file mode 100644 index f9bbfb947..000000000 --- a/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/ScallableItemObject.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.magmaguy.elitemobs.items.itemconstructor; - -import org.bukkit.Material; -import org.bukkit.enchantments.Enchantment; - -import java.util.HashMap; -import java.util.List; - -public class ScallableItemObject { - - public String rawName; - public Material material; - public HashMap enchantments; - public HashMap customEnchantments; - public List potionEffects; - public List lore; - - /* - Stores fields for later use - */ - public void initializeItemObject(String rawName, Material material, HashMap enchantments, HashMap customEnchantments, List potionEffects, - List lore) { - - this.rawName = rawName; - this.material = material; - this.enchantments = enchantments; - this.customEnchantments = customEnchantments; - this.potionEffects = potionEffects; - this.lore = lore; - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/SpecialLoot.java b/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/SpecialLoot.java new file mode 100644 index 000000000..705e045c7 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/items/itemconstructor/SpecialLoot.java @@ -0,0 +1,125 @@ +package com.magmaguy.elitemobs.items.itemconstructor; + +import com.magmaguy.elitemobs.adventurersguild.GuildRank; +import com.magmaguy.elitemobs.config.AdventurersGuildConfig; +import com.magmaguy.elitemobs.utils.WarningMessage; +import lombok.Getter; +import lombok.Setter; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.concurrent.ThreadLocalRandom; + +public class SpecialLoot { + + private SpecialLootType specialLootType = null; + private int minAmount = 0, maxAmount; + @Getter + @Setter + private int minLevel = 0, maxLevel; + private boolean ignorePlayerLevel = false; + @Getter + private double chance = 1; + @Getter + private boolean dynamicLevel = false; + + //format: scrap/upgrade_item:level=x-y:amount=x-y:ignorePlayerLevel=x:chance=1 + public SpecialLoot(String rawConfigurationString, String filename) { + String[] configSubstrings = rawConfigurationString.split(":"); + try { + specialLootType = SpecialLootType.valueOf(configSubstrings[0].toUpperCase()); + } catch (Exception ex) { + new WarningMessage("Failed to load Special Item for file " + filename + "!"); + new WarningMessage("Invalid entry for " + rawConfigurationString); + } + + for (String option : configSubstrings) + try { + if (option.contains("level")) { + String finalOption = option.split("=")[1]; + if (finalOption.contains("-")) { + String[] minMax = finalOption.split("-"); + minLevel = Integer.parseInt(minMax[0]); + maxLevel = Integer.parseInt(minMax[1]); + } else if (finalOption.equalsIgnoreCase("dynamic")) { + //this get set elsewhere when it is dynamic + minLevel = maxLevel = 1; + dynamicLevel = true; + } else { + minLevel = Integer.parseInt(finalOption); + maxLevel = Integer.parseInt(finalOption); + } + } else if (option.contains("amount")) { + String finalOption = option.split("=")[1]; + if (finalOption.contains("-")) { + String[] minMax = finalOption.split("-"); + minAmount = Integer.parseInt(minMax[0]); + maxAmount = Integer.parseInt(minMax[1]); + } else { + minAmount = Integer.parseInt(finalOption); + maxAmount = Integer.parseInt(finalOption); + } + } else if (option.contains("ignorePlayerLevel")) { + String finalOption = option.split("=")[1]; + ignorePlayerLevel = Boolean.parseBoolean(finalOption); + } else if (option.contains("chance")) { + String finalOption = option.split("=")[1]; + chance = Double.parseDouble(finalOption); + } + } catch (Exception exception) { + new WarningMessage("Failed to load Special Item for file " + filename + "! Problematic entry: " + option); + } + } + + public static boolean isSpecialLootEntry(String rawConfigEntry) { + if (rawConfigEntry.isEmpty()) return false; + String configSection = rawConfigEntry.split(":")[0]; + if (configSection.isEmpty()) return false; + return configSection.equalsIgnoreCase("SCRAP") || configSection.equalsIgnoreCase("UPGRADE_ITEM"); + } + + public ItemStack generateItemStack(Player player) { + if (specialLootType == null) return null; + + int amount; + if (minAmount == maxAmount) + amount = minAmount; + else + amount = Math.min(ThreadLocalRandom.current().nextInt(minAmount, maxAmount), 64); + + int level; + if (!dynamicLevel) { + if (this.minLevel == this.maxLevel) + level = this.minLevel; + else + level = ThreadLocalRandom.current().nextInt(this.minLevel, this.maxLevel); + } else { + if (minLevel == maxLevel) + level = minLevel; + else + level = ThreadLocalRandom.current().nextInt(minLevel, maxLevel); + } + if (!ignorePlayerLevel) + if (AdventurersGuildConfig.isGuildLootLimiter()) + level = Math.min(level, GuildRank.getMaxGuildRank(player) * 10); + ItemStack itemStack; + switch (specialLootType) { + case SCRAP: + itemStack = ItemConstructor.constructScrapItem(level, player, false); + break; + case UPGRADE_ITEM: + default: + itemStack = ItemConstructor.constructUpgradeItem(level, player, false); + break; + } + + itemStack.setAmount(amount); + return itemStack; + } + + public enum SpecialLootType { + SCRAP, + UPGRADE_ITEM + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/items/parserutil/ConfigPathBuilder.java b/src/main/java/com/magmaguy/elitemobs/items/parserutil/ConfigPathBuilder.java deleted file mode 100644 index 03d03ef4f..000000000 --- a/src/main/java/com/magmaguy/elitemobs/items/parserutil/ConfigPathBuilder.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.magmaguy.elitemobs.items.parserutil; - -public class ConfigPathBuilder { - - public static String automatedStringBuilder(String previousPath, String append) { - - StringBuilder automatedStringBuilder = new StringBuilder(); - - automatedStringBuilder.append(previousPath); - automatedStringBuilder.append("."); - automatedStringBuilder.append(append); - - String path = automatedStringBuilder.toString(); - - return path; - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/items/parserutil/CustomEnchantmentConfigParser.java b/src/main/java/com/magmaguy/elitemobs/items/parserutil/CustomEnchantmentConfigParser.java deleted file mode 100644 index 016c06cda..000000000 --- a/src/main/java/com/magmaguy/elitemobs/items/parserutil/CustomEnchantmentConfigParser.java +++ /dev/null @@ -1,50 +0,0 @@ -package com.magmaguy.elitemobs.items.parserutil; - -import com.magmaguy.elitemobs.items.customenchantments.CustomEnchantmentCache; -import org.bukkit.configuration.Configuration; - -import java.util.HashMap; -import java.util.List; - -import static com.magmaguy.elitemobs.items.parserutil.ConfigPathBuilder.automatedStringBuilder; - -public class CustomEnchantmentConfigParser { - - public static HashMap parseCustomEnchantments(Configuration configuration, String previousPath) { - - String path = automatedStringBuilder(previousPath, "Enchantments"); - List enchantments = configuration.getList(path); - HashMap customEnchantmentMap = new HashMap(); - - try { - for (Object object : enchantments) { - - String string = (String) object; - -// Avoid parsing a regular enchantment - if (!CustomEnchantmentConfigParser.isCustomEnchantment(string)) continue; - - String customEnchantment = string.split(",")[0]; - - customEnchantmentMap.put(customEnchantment, Integer.parseInt(string.split(",")[1])); - - } - - } catch (Exception e) { -// Already handled in the normal enchantment parser - } - - return customEnchantmentMap; - - } - - public static boolean isCustomEnchantment(String string) { - - if (string.contains(CustomEnchantmentCache.hunterEnchantment.getKey())) return true; - if (string.contains(CustomEnchantmentCache.flamethrowerEnchantment.getKey())) return true; - - return false; - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/items/parserutil/DropWeightConfigParser.java b/src/main/java/com/magmaguy/elitemobs/items/parserutil/DropWeightConfigParser.java deleted file mode 100644 index 439f7b885..000000000 --- a/src/main/java/com/magmaguy/elitemobs/items/parserutil/DropWeightConfigParser.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.magmaguy.elitemobs.items.parserutil; - - -import org.bukkit.configuration.Configuration; - -import static com.magmaguy.elitemobs.items.parserutil.ConfigPathBuilder.automatedStringBuilder; - -public class DropWeightConfigParser { - - public static String getDropType(Configuration configuration, String previousPath) { - - String dropType = automatedStringBuilder(previousPath, "Drop Weight"); - - return configuration.getString(dropType); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/items/parserutil/EnchantmentConfigParser.java b/src/main/java/com/magmaguy/elitemobs/items/parserutil/EnchantmentConfigParser.java deleted file mode 100644 index 061403af9..000000000 --- a/src/main/java/com/magmaguy/elitemobs/items/parserutil/EnchantmentConfigParser.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.magmaguy.elitemobs.items.parserutil; - -import org.bukkit.Bukkit; -import org.bukkit.configuration.Configuration; -import org.bukkit.enchantments.Enchantment; - -import java.util.HashMap; -import java.util.List; - -import static com.magmaguy.elitemobs.items.parserutil.ConfigPathBuilder.automatedStringBuilder; - -public class EnchantmentConfigParser { - - public static HashMap parseEnchantments(Configuration configuration, String previousPath) { - - String path = automatedStringBuilder(previousPath, "Enchantments"); - List enchantments = configuration.getList(path); - HashMap enchantmentMap = new HashMap(); - - try { - for (Object object : enchantments) { - - String string = (String) object; - -// Custom enchantments have their own parser - if (CustomEnchantmentConfigParser.isCustomEnchantment(string)) continue; - - Enchantment enchantment = Enchantment.getByName(string.split(",")[0]); - - if (enchantment != null) - enchantmentMap.put(enchantment, Integer.parseInt(string.split(",")[1])); - - } - - } catch (Exception e) { - Bukkit.getLogger().warning("Warning: something on ItemsCustomLootList.yml is invalid."); - Bukkit.getLogger().warning("Make sure you add a valid enchantment type and a valid level for it!"); - } - - return enchantmentMap; - - } - - -} diff --git a/src/main/java/com/magmaguy/elitemobs/items/parserutil/PotionEffectConfigParser.java b/src/main/java/com/magmaguy/elitemobs/items/parserutil/PotionEffectConfigParser.java deleted file mode 100644 index d53ac0487..000000000 --- a/src/main/java/com/magmaguy/elitemobs/items/parserutil/PotionEffectConfigParser.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.magmaguy.elitemobs.items.parserutil; - -import org.bukkit.configuration.Configuration; - -import java.util.List; - -import static com.magmaguy.elitemobs.items.parserutil.ConfigPathBuilder.automatedStringBuilder; - -public class PotionEffectConfigParser { - - public static List itemPotionEffectHandler(Configuration configuration, String previousPath) { - - String path = automatedStringBuilder(previousPath, "Potion Effects"); - - List potionEffects = configuration.getList(path); - - return potionEffects; - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/items/parserutil/ScalabilityConfigParser.java b/src/main/java/com/magmaguy/elitemobs/items/parserutil/ScalabilityConfigParser.java deleted file mode 100644 index dcf69e771..000000000 --- a/src/main/java/com/magmaguy/elitemobs/items/parserutil/ScalabilityConfigParser.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.magmaguy.elitemobs.items.parserutil; - - -import org.bukkit.configuration.Configuration; - -import static com.magmaguy.elitemobs.items.parserutil.ConfigPathBuilder.automatedStringBuilder; - -public class ScalabilityConfigParser { - - public static String parseItemScalability(Configuration configuration, String previousPath) { - - String path = automatedStringBuilder(previousPath, "Scalability"); - - return configuration.getString(path); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/items/potioneffects/ElitePotionEffect.java b/src/main/java/com/magmaguy/elitemobs/items/potioneffects/ElitePotionEffect.java new file mode 100644 index 000000000..7f9af9c9d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/items/potioneffects/ElitePotionEffect.java @@ -0,0 +1,74 @@ +package com.magmaguy.elitemobs.items.potioneffects; + +import com.magmaguy.elitemobs.config.potioneffects.PotionEffectsConfig; +import com.magmaguy.elitemobs.utils.WarningMessage; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +public class ElitePotionEffect { + + private PotionEffect potionEffect; + private Target target; + private ApplicationMethod applicationMethod; + private double value; + + public ElitePotionEffect(String string) { + try { + String[] stringObject = string.split(","); + int duration = 2 * 20; + if (PotionEffectType.getByName(stringObject[0].toLowerCase()).equals(PotionEffectType.NIGHT_VISION)) + duration = 15 * 20; + this.potionEffect = new PotionEffect(PotionEffectType.getByName(stringObject[0].toLowerCase()), duration, Integer.parseInt(stringObject[1])); + this.value = PotionEffectsConfig.getPotionEffect(potionEffect.getType().getName()).getValue(); + if (stringObject.length < 3) { + this.target = Target.SELF; + this.applicationMethod = ApplicationMethod.CONTINUOUS; + return; + } + + this.target = Target.valueOf(stringObject[2].toUpperCase()); + + if (stringObject.length < 4) { + applicationMethod = ApplicationMethod.CONTINUOUS; + return; + } + + this.applicationMethod = ApplicationMethod.valueOf(stringObject[3].toUpperCase()); + + if (this.applicationMethod.equals(ApplicationMethod.ONHIT)) + this.potionEffect = new PotionEffect(PotionEffectType.getByName(stringObject[0].toLowerCase()), + PotionEffectsConfig.getPotionEffect(potionEffect.getType().getName()).getOnHitDuration() * 20, + Integer.parseInt(stringObject[1])); + + } catch (Exception ex) { + new WarningMessage("Detected invalid potion effect entry: " + string); + ex.printStackTrace(); + } + } + + public PotionEffect getPotionEffect() { + return potionEffect; + } + + public Target getTarget() { + return target; + } + + public ApplicationMethod getApplicationMethod() { + return applicationMethod; + } + + public double getValue() { + return value; + } + + public enum Target { + SELF, + TARGET + } + + public enum ApplicationMethod { + ONHIT, + CONTINUOUS + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/items/potioneffects/ElitePotionEffectContainer.java b/src/main/java/com/magmaguy/elitemobs/items/potioneffects/ElitePotionEffectContainer.java new file mode 100644 index 000000000..fd5355e8e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/items/potioneffects/ElitePotionEffectContainer.java @@ -0,0 +1,96 @@ +package com.magmaguy.elitemobs.items.potioneffects; + +import com.magmaguy.elitemobs.items.ItemTagger; +import org.bukkit.NamespacedKey; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.tags.ItemTagType; +import org.bukkit.persistence.PersistentDataType; + +import java.util.ArrayList; +import java.util.List; + +public class ElitePotionEffectContainer { + + /** + * Tags an item with the potion effects + * + * @param itemMeta + * @param potionEffects + */ + public ElitePotionEffectContainer(ItemMeta itemMeta, List potionEffects) { + + if (potionEffects.isEmpty()) return; + + StringBuilder onHit = new StringBuilder(); + StringBuilder continuous = new StringBuilder(); + + for (String substring : potionEffects) { + ElitePotionEffect elitePotionEffect = new ElitePotionEffect(substring); + switch (elitePotionEffect.getApplicationMethod()) { + case ONHIT: + onHit.append(substring).append(":"); + break; + case CONTINUOUS: + default: + continuous.append(substring).append(":"); + break; + } + } + + if (onHit.length() > 0) + itemMeta.getPersistentDataContainer().set(ItemTagger.onHitPotionEffectKey, PersistentDataType.STRING, onHit.toString()); + if (continuous.length() > 0) + itemMeta.getPersistentDataContainer().set(ItemTagger.continuousPotionEffectKey, PersistentDataType.STRING, continuous.toString()); + + } + + public static ArrayList getElitePotionEffectContainer(ItemMeta itemMeta, NamespacedKey namespacedKey) { + if (itemMeta == null) return new ArrayList<>(); + //for legacy items + if (itemMeta.getCustomTagContainer().hasCustomTag(namespacedKey, ItemTagType.STRING)) { + ArrayList elitePotionEffects = new ArrayList<>(); + for (String string : itemMeta.getCustomTagContainer().getCustomTag(namespacedKey, ItemTagType.STRING).split(":")) + if (string.length() > 0) + elitePotionEffects.add(new ElitePotionEffect(string)); + + return elitePotionEffects; + } + + + if (!itemMeta.getPersistentDataContainer().has(namespacedKey, PersistentDataType.STRING)) + return new ArrayList<>(); + ArrayList elitePotionEffects = new ArrayList<>(); + for (String string : itemMeta.getPersistentDataContainer().get(namespacedKey, PersistentDataType.STRING).split(":")) + if (string.length() > 0) + elitePotionEffects.add(new ElitePotionEffect(string)); + + return elitePotionEffects; + } + + public static ArrayList getElitePotionEffects(ItemMeta itemMeta, ElitePotionEffect.ApplicationMethod applicationMethod) { + String elitePotionEfects = ""; + switch (applicationMethod) { + case CONTINUOUS: + //do legacy items first, default to current items + if (itemMeta.getCustomTagContainer().hasCustomTag(ItemTagger.eliteMobsItemNamespacedKey, ItemTagType.BYTE)) + elitePotionEfects = itemMeta.getCustomTagContainer().getCustomTag(ItemTagger.continuousPotionEffectKey, ItemTagType.STRING); + else + elitePotionEfects = itemMeta.getPersistentDataContainer().get(ItemTagger.continuousPotionEffectKey, PersistentDataType.STRING); + break; + case ONHIT: + if (itemMeta.getCustomTagContainer().hasCustomTag(ItemTagger.eliteMobsItemNamespacedKey, ItemTagType.BYTE)) + elitePotionEfects = itemMeta.getCustomTagContainer().getCustomTag(ItemTagger.onHitPotionEffectKey, ItemTagType.STRING); + else + elitePotionEfects = itemMeta.getPersistentDataContainer().get(ItemTagger.onHitPotionEffectKey, PersistentDataType.STRING); + break; + } + ArrayList elitePotionEffects = new ArrayList<>(); + if (elitePotionEfects == null || elitePotionEfects.isEmpty()) + return elitePotionEffects; + for (String subString : elitePotionEfects.split(":")) + elitePotionEffects.add(new ElitePotionEffect(subString)); + return elitePotionEffects; + } + + +} diff --git a/src/main/java/com/magmaguy/elitemobs/items/potioneffects/PlayerPotionEffects.java b/src/main/java/com/magmaguy/elitemobs/items/potioneffects/PlayerPotionEffects.java new file mode 100644 index 000000000..9ed9200c6 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/items/potioneffects/PlayerPotionEffects.java @@ -0,0 +1,136 @@ +package com.magmaguy.elitemobs.items.potioneffects; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.items.potioneffects.custom.Harm; +import com.magmaguy.elitemobs.items.potioneffects.custom.Heal; +import com.magmaguy.elitemobs.items.potioneffects.custom.Saturation; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.playerdata.ElitePlayerInventory; +import com.magmaguy.elitemobs.utils.EntityFinder; +import org.bukkit.Bukkit; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.HashSet; + +/** + * Created by MagmaGuy on 14/03/2017. + */ +public class PlayerPotionEffects implements Listener { + + public PlayerPotionEffects() { + new BukkitRunnable() { + @Override + public void run() { + //scan through what players are wearing + for (Player player : Bukkit.getOnlinePlayers()) + if (ElitePlayerInventory.playerInventories.get(player.getUniqueId()) != null) + for (ElitePotionEffect elitePotionEffect : ElitePlayerInventory.playerInventories.get(player.getUniqueId()).getContinuousPotionEffects(true)) + doContinuousPotionEffect(elitePotionEffect, player); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 20L, 20L); + } + + public static void addOnHitCooldown(HashSet cooldownList, Player player, long delay) { + cooldownList.add(player); + new BukkitRunnable() { + @Override + public void run() { + cooldownList.remove(player); + } + }.runTaskLater(MetadataHandler.PLUGIN, delay); + } + + private void doContinuousPotionEffect(ElitePotionEffect elitePotionEffect, Player player) { + + //if the player has a higher amplifier potion effect, ignore. If it's the same, reapply to refresh the effect + if (player.hasPotionEffect(elitePotionEffect.getPotionEffect().getType()) && + player.getPotionEffect(elitePotionEffect.getPotionEffect().getType()).getAmplifier() > elitePotionEffect.getPotionEffect().getAmplifier()) + return; + + if (elitePotionEffect.getPotionEffect().getType().equals(PotionEffectType.HEAL)) { + Heal.doHeal(player, elitePotionEffect); + return; + } + + if (elitePotionEffect.getPotionEffect().getType().equals(PotionEffectType.SATURATION)) { + Saturation.doSaturation(player, elitePotionEffect); + return; + } + + if (elitePotionEffect.getPotionEffect().getType().equals(PotionEffectType.HARM)) { + Harm.doHarm(player, elitePotionEffect); + return; + } + + if (player.hasPotionEffect(elitePotionEffect.getPotionEffect().getType())) + player.removePotionEffect(elitePotionEffect.getPotionEffect().getType()); + player.addPotionEffect(elitePotionEffect.getPotionEffect()); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGHEST) + public void onPlayerHitWithPotionEffect(EntityDamageByEntityEvent event) { + LivingEntity damager = EntityFinder.getRealDamager(event); + if (damager == null || !damager.getType().equals(EntityType.PLAYER)) return; + Player player = (Player) damager; + + //citizens + if (player.hasMetadata("NPC")) + return; + + if (ElitePlayerInventory.playerInventories.get(player.getUniqueId()) == null) return; + + LivingEntity damagee; + if (event.getEntity() instanceof LivingEntity) + damagee = (LivingEntity) event.getEntity(); + else + return; + + for (ElitePotionEffect elitePotionEffect : ElitePlayerInventory.playerInventories.get(player.getUniqueId()).getOnHitPotionEffects(true)) + doOnHitPotionEffect(elitePotionEffect, player, damagee); + } + + private void doOnHitPotionEffect(ElitePotionEffect elitePotionEffect, Player player, LivingEntity damagee) { + switch (elitePotionEffect.getTarget()) { + case SELF: + + if (elitePotionEffect.getPotionEffect().getType().equals(PotionEffectType.HEAL)) { + Heal.doHeal(player, elitePotionEffect); + break; + } + + if (elitePotionEffect.getPotionEffect().getType().equals(PotionEffectType.SATURATION)) { + Saturation.doSaturation(player, elitePotionEffect); + break; + } + + if (elitePotionEffect.getPotionEffect().getType().equals(PotionEffectType.HARM)) { + Harm.doHarm(player, elitePotionEffect); + return; + } + if (elitePotionEffect.getPotionEffect().getType().equals(PotionEffectType.LEVITATION)) { + EliteEntity eliteEntity = EntityTracker.getEliteMobEntity(damagee); + if (eliteEntity != null && eliteEntity.getHealthMultiplier() > 1) + return; + if (damagee.getType().equals(EntityType.PLAYER)) + return; + } + + player.addPotionEffect(elitePotionEffect.getPotionEffect()); + break; + case TARGET: + damagee.addPotionEffect(elitePotionEffect.getPotionEffect()); + break; + } + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/items/potioneffects/custom/Harm.java b/src/main/java/com/magmaguy/elitemobs/items/potioneffects/custom/Harm.java new file mode 100644 index 000000000..cc1aae1cc --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/items/potioneffects/custom/Harm.java @@ -0,0 +1,20 @@ +package com.magmaguy.elitemobs.items.potioneffects.custom; + +import com.magmaguy.elitemobs.items.potioneffects.ElitePotionEffect; +import com.magmaguy.elitemobs.items.potioneffects.PlayerPotionEffects; +import org.bukkit.entity.Player; + +import java.util.HashSet; + +public class Harm { + + private static final HashSet harmCooldown = new HashSet<>(); + + public static void doHarm(Player player, ElitePotionEffect elitePotionEffect) { + if (harmCooldown.contains(player)) return; + PlayerPotionEffects.addOnHitCooldown(harmCooldown, player, 20 * 5); + double harmAmount = (elitePotionEffect.getPotionEffect().getAmplifier() + 1); + player.damage(harmAmount); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/items/potioneffects/custom/Heal.java b/src/main/java/com/magmaguy/elitemobs/items/potioneffects/custom/Heal.java new file mode 100644 index 000000000..89f244070 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/items/potioneffects/custom/Heal.java @@ -0,0 +1,23 @@ +package com.magmaguy.elitemobs.items.potioneffects.custom; + +import com.magmaguy.elitemobs.items.potioneffects.ElitePotionEffect; +import com.magmaguy.elitemobs.items.potioneffects.PlayerPotionEffects; +import org.bukkit.attribute.Attribute; +import org.bukkit.entity.Player; + +import java.util.HashSet; + +public class Heal { + + private static final HashSet healCooldown = new HashSet<>(); + + public static void doHeal(Player player, ElitePotionEffect elitePotionEffect) { + if (healCooldown.contains(player)) return; + PlayerPotionEffects.addOnHitCooldown(healCooldown, player, 20 * 5); + double healedAmount = (elitePotionEffect.getPotionEffect().getAmplifier() + 1); + healedAmount = healedAmount + player.getHealth() > player.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue() ? + 0 : healedAmount; + player.setHealth(player.getHealth() + healedAmount); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/items/potioneffects/custom/Saturation.java b/src/main/java/com/magmaguy/elitemobs/items/potioneffects/custom/Saturation.java new file mode 100644 index 000000000..92d47aafc --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/items/potioneffects/custom/Saturation.java @@ -0,0 +1,22 @@ +package com.magmaguy.elitemobs.items.potioneffects.custom; + +import com.magmaguy.elitemobs.items.potioneffects.ElitePotionEffect; +import com.magmaguy.elitemobs.items.potioneffects.PlayerPotionEffects; +import org.bukkit.entity.Player; + +import java.util.HashSet; + +public class Saturation { + + private static final HashSet saturationCooldown = new HashSet<>(); + + public static void doSaturation(Player player, ElitePotionEffect elitePotionEffect) { + if (saturationCooldown.contains(player)) return; + PlayerPotionEffects.addOnHitCooldown(saturationCooldown, player, 20 * 5); + double foodRestoredAmount = (elitePotionEffect.getPotionEffect().getAmplifier() + 1); + foodRestoredAmount = foodRestoredAmount + player.getFoodLevel() > 20 ? + 20 : foodRestoredAmount; + player.setFoodLevel((int) (player.getFoodLevel() + foodRestoredAmount)); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/ConfigAssembler.java b/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/ConfigAssembler.java deleted file mode 100644 index b1e697730..000000000 --- a/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/ConfigAssembler.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.magmaguy.elitemobs.items.uniqueitems; - -import org.bukkit.configuration.Configuration; - -import java.util.List; - -public class ConfigAssembler { - - public static void assemble(Configuration configuration, String path, String itemType, String itemName, - List itemLore, List enchantments, - List potionEffects, String itemWeight, String itemScalability) { - - configuration.addDefault("Items." + path + ".Item Type", itemType); - configuration.addDefault("Items." + path + ".Item Name", itemName); - configuration.addDefault("Items." + path + ".Item Lore", itemLore); - configuration.addDefault("Items." + path + ".Enchantments", enchantments); - configuration.addDefault("Items." + path + ".Potion Effects", potionEffects); - configuration.addDefault("Items." + path + ".Drop Weight", itemWeight); - configuration.addDefault("Items." + path + ".Scalability", itemScalability); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/DepthsSeeker.java b/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/DepthsSeeker.java deleted file mode 100644 index ce0746fa7..000000000 --- a/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/DepthsSeeker.java +++ /dev/null @@ -1,64 +0,0 @@ -package com.magmaguy.elitemobs.items.uniqueitems; - -import org.bukkit.Material; - -import java.util.Arrays; -import java.util.List; - -public class DepthsSeeker extends UniqueItem{ - - @Override - public String definePath() { - return "Depths Seeker"; - } - - @Override - public String defineType() { - return Material.FISHING_ROD.toString(); - } - - @Override - public String defineName() { - return "&9Depths Seeker"; - } - - @Override - public List defineLore() { - return Arrays.asList( - "&9Come from depths immeasurable", - "&9and looted from monster most vile,", - "&9there is no telling what horrors", - "&9this fishing rod has seen." - ); - } - - @Override - public List defineEnchantments() { - return Arrays.asList( - "LURE,3", - "LUCK,3", - "DURABILITY,10", - "FIRE_ASPECT,1", - "VANISHING_CURSE,1" - ); - } - - @Override - public List definePotionEffects() { - return Arrays.asList( - "WATER_BREATHING,1,self,continuous", - "LUCK,1,self,continuous" - ); - } - - @Override - public String defineDropWeight() { - return "unique"; - } - - @Override - public String defineScalability() { - return "dynamic"; - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/DwarvenGreed.java b/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/DwarvenGreed.java deleted file mode 100644 index d4f34ba39..000000000 --- a/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/DwarvenGreed.java +++ /dev/null @@ -1,62 +0,0 @@ -package com.magmaguy.elitemobs.items.uniqueitems; - -import org.bukkit.Material; - -import java.util.Arrays; -import java.util.List; - -public class DwarvenGreed extends UniqueItem { - @Override - public String definePath() { - return "Dwarven Greed"; - } - - @Override - public String defineType() { - return Material.DIAMOND_PICKAXE.toString(); - } - - @Override - public String defineName() { - return "&4Dwarven Greed"; - } - - @Override - public List defineLore() { - return Arrays.asList( - "&cThose who delve too greedily", - "&cand too deep may wake ancient", - "&chorrors of shadow and flame", - "&cbest left undisturbed." - ); - } - - @Override - public List defineEnchantments() { - return Arrays.asList( - "LOOT_BONUS_BLOCKS,4", - "DURABILITY,6", - "DIG_SPEED,6", - "VANISHING_CURSE,1" - ); - } - - @Override - public List definePotionEffects() { - return Arrays.asList( - "FAST_DIGGING,2,self,continuous", - "NIGHT_VISION,1,self,continuous" - ); - } - - @Override - public String defineDropWeight() { - return "unique"; - } - - @Override - public String defineScalability() { - return "dynamic"; - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/HuntingBoots.java b/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/HuntingBoots.java deleted file mode 100644 index 9c5d0dbf4..000000000 --- a/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/HuntingBoots.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.magmaguy.elitemobs.items.uniqueitems; - -import com.magmaguy.elitemobs.items.customenchantments.CustomEnchantmentCache; -import org.bukkit.Material; -import org.bukkit.configuration.Configuration; - -import java.util.Arrays; -import java.util.List; - -public class HuntingBoots extends UniqueItem { - - @Override - public String definePath() { - return "Hunting Boots"; - } - - @Override - public String defineType() { - return Material.DIAMOND_BOOTS.toString(); - } - - @Override - public String defineName() { - return "&4Elite Mob Hunting Boots"; - } - - - @Override - public List defineLore() { - return Arrays.asList("Only for those fleetest of foot."); - } - - @Override - public List defineEnchantments() { - return Arrays.asList("VANISHING_CURSE,1", "PROTECTION_ENVIRONMENTAL,1", CustomEnchantmentCache.hunterEnchantment.assembleConfigString(2)); - } - - @Override - public List definePotionEffects() { - return Arrays.asList("SPEED,2,self,continuous"); - } - - @Override - public String defineDropWeight() { - return "dynamic"; - } - - @Override - public String defineScalability() { - return "dynamic"; - } - - @Override - public void assembleConfigItem(Configuration configuration) { - super.assembleConfigItem(configuration); - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/HuntingBow.java b/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/HuntingBow.java deleted file mode 100644 index 65f77e73f..000000000 --- a/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/HuntingBow.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.magmaguy.elitemobs.items.uniqueitems; - -import org.bukkit.Material; -import org.bukkit.configuration.Configuration; - -import java.util.Arrays; -import java.util.List; - -public class HuntingBow extends UniqueItem { - - @Override - public String definePath() { - return "Hunting Bow"; - } - - @Override - public String defineType() { - return Material.BOW.toString(); - } - - @Override - public String defineName() { - return "&4Elite Mob Hunting Bow"; - } - - - @Override - public List defineLore() { - return Arrays.asList("Only for natural-born hunters."); - } - - @Override - public List defineEnchantments() { - return Arrays.asList("VANISHING_CURSE,1", "DAMAGE_ARROW,1"); - } - - @Override - public List definePotionEffects() { - return Arrays.asList("SATURATION,1,self,continuous"); - } - - @Override - public String defineDropWeight() { - return "dynamic"; - } - - @Override - public String defineScalability() { - return "dynamic"; - } - - @Override - public void assembleConfigItem(Configuration configuration) { - super.assembleConfigItem(configuration); - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/HuntingChestplate.java b/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/HuntingChestplate.java deleted file mode 100644 index cc675fb8e..000000000 --- a/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/HuntingChestplate.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.magmaguy.elitemobs.items.uniqueitems; - -import com.magmaguy.elitemobs.items.customenchantments.CustomEnchantmentCache; -import org.bukkit.Material; -import org.bukkit.configuration.Configuration; - -import java.util.Arrays; -import java.util.List; - -public class HuntingChestplate extends UniqueItem { - - @Override - public String definePath() { - return "Hunting Chestplate"; - } - - @Override - public String defineType() { - return Material.DIAMOND_CHESTPLATE.toString(); - } - - @Override - public String defineName() { - return "&4Elite Mob Hunting Chestplate"; - } - - - @Override - public List defineLore() { - return Arrays.asList("Only for the bravest souls."); - } - - @Override - public List defineEnchantments() { - return Arrays.asList("VANISHING_CURSE,1", "PROTECTION_ENVIRONMENTAL,1", CustomEnchantmentCache.hunterEnchantment.assembleConfigString(2)); - } - - @Override - public List definePotionEffects() { - return Arrays.asList("SATURATION,1,self,continuous"); - } - - @Override - public String defineDropWeight() { - return "dynamic"; - } - - @Override - public void assembleConfigItem(Configuration configuration) { - super.assembleConfigItem(configuration); - } - - @Override - public String defineScalability() { - return "dynamic"; - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/HuntingHelmet.java b/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/HuntingHelmet.java deleted file mode 100644 index 6a0007c6b..000000000 --- a/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/HuntingHelmet.java +++ /dev/null @@ -1,59 +0,0 @@ -package com.magmaguy.elitemobs.items.uniqueitems; - -import com.magmaguy.elitemobs.items.customenchantments.CustomEnchantmentCache; -import org.bukkit.Material; -import org.bukkit.configuration.Configuration; - -import java.util.Arrays; -import java.util.List; - -public class HuntingHelmet extends UniqueItem { - - @Override - public String definePath() { - return "Hunting Helmet"; - } - - @Override - public String defineType() { - return Material.DIAMOND_HELMET.toString(); - } - - @Override - public String defineName() { - return "&4Elite Mob Hunting Helmet"; - } - - - @Override - public List defineLore() { - return Arrays.asList("Only for the sharpest of eyes."); - } - - @Override - public List defineEnchantments() { - return Arrays.asList("VANISHING_CURSE,1", "PROTECTION_ENVIRONMENTAL,1", CustomEnchantmentCache.hunterEnchantment.assembleConfigString(2)); - } - - @Override - public List definePotionEffects() { - return Arrays.asList("NIGHT_VISION,1,self,continuous"); - } - - @Override - public String defineDropWeight() { - return "dynamic"; - } - - @Override - public String defineScalability() { - return "dynamic"; - } - - @Override - public void assembleConfigItem(Configuration configuration) { - super.assembleConfigItem(configuration); - } - - -} diff --git a/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/HuntingLeggings.java b/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/HuntingLeggings.java deleted file mode 100644 index 910129f22..000000000 --- a/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/HuntingLeggings.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.magmaguy.elitemobs.items.uniqueitems; - -import com.magmaguy.elitemobs.items.customenchantments.CustomEnchantmentCache; -import org.bukkit.Material; -import org.bukkit.configuration.Configuration; - -import java.util.Arrays; -import java.util.List; - -public class HuntingLeggings extends UniqueItem { - - @Override - public String definePath() { - return "Hunting Leggings"; - } - - @Override - public String defineType() { - return Material.DIAMOND_LEGGINGS.toString(); - } - - @Override - public String defineName() { - return "&4Elite Mob Hunting Leggings"; - } - - - @Override - public List defineLore() { - return Arrays.asList("Only for those who aim the highest."); - } - - @Override - public List defineEnchantments() { - return Arrays.asList("VANISHING_CURSE,1", "PROTECTION_ENVIRONMENTAL,1", CustomEnchantmentCache.hunterEnchantment.assembleConfigString(2)); - } - - @Override - public List definePotionEffects() { - return Arrays.asList("JUMP,2,self,continuous"); - } - - @Override - public String defineDropWeight() { - return "dynamic"; - } - - @Override - public String defineScalability() { - return "dynamic"; - } - - @Override - public void assembleConfigItem(Configuration configuration) { - super.assembleConfigItem(configuration); - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/TheFeller.java b/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/TheFeller.java deleted file mode 100644 index e26a3f2be..000000000 --- a/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/TheFeller.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.magmaguy.elitemobs.items.uniqueitems; - -import org.bukkit.Material; - -import java.util.Arrays; -import java.util.List; - -public class TheFeller extends UniqueItem { - - @Override - public String definePath() { - return "The Feller"; - } - - @Override - public String defineType() { - return Material.DIAMOND_AXE.toString(); - } - - @Override - public String defineName() { - return "&2The Feller"; - } - - @Override - public List defineLore() { - return Arrays.asList( - "&aEven in your sleep,", - "&aYou can feel this axe's", - "&9saplust" - ); - } - - @Override - public List defineEnchantments() { - return Arrays.asList( - "LOOT_BONUS_BLOCKS,4", - "SILK_TOUCH,1", - "DURABILITY,6", - "DIG_SPEED,6", - "VANISHING_CURSE,1" - ); - } - - @Override - public List definePotionEffects() { - return Arrays.asList( - "FAST_DIGGING,2,self,continuous", - "NIGHT_VISION,1,self,continuous" - ); - } - - @Override - public String defineDropWeight() { - return "unique"; - } - - @Override - public String defineScalability() { - return "dynamic"; - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/UniqueItem.java b/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/UniqueItem.java deleted file mode 100644 index 0dc291e10..000000000 --- a/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/UniqueItem.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.magmaguy.elitemobs.items.uniqueitems; - -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.items.itemconstructor.ItemConstructor; -import com.magmaguy.elitemobs.items.parserutil.*; -import org.bukkit.Material; -import org.bukkit.configuration.Configuration; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.ItemStack; - -import java.util.HashMap; -import java.util.List; - -public abstract class UniqueItem { - - public abstract String definePath(); - - public abstract String defineType(); - - public abstract String defineName(); - - public abstract List defineLore(); - - /* - #defineEnchantments() also defines custom enchantments as they are written the same way into config files - */ - public abstract List defineEnchantments(); - - public abstract List definePotionEffects(); - - public abstract String defineDropWeight(); - - public abstract String defineScalability(); - - public void assembleConfigItem(Configuration configuration) { - ConfigAssembler.assemble(configuration, definePath(), defineType(), defineName(), defineLore(), - defineEnchantments(), definePotionEffects(), defineDropWeight(), defineScalability()); - } - - public ItemStack constructItemStack() { - HashMap enchantments = EnchantmentConfigParser.parseEnchantments(ConfigValues.itemsUniqueConfig, - "Items." + definePath()); - HashMap customEnchantments = CustomEnchantmentConfigParser.parseCustomEnchantments(ConfigValues.itemsUniqueConfig, - "Items." + definePath()); - List potionEffects = PotionEffectConfigParser.itemPotionEffectHandler(ConfigValues.itemsUniqueConfig, - "Items." + definePath()); - String dropType = DropWeightConfigParser.getDropType(ConfigValues.itemsUniqueConfig, "Items." + definePath()); - String scalability = ScalabilityConfigParser.parseItemScalability(ConfigValues.itemsUniqueConfig, "Items." + definePath()); - - return ItemConstructor.constructItem(defineName(), Material.getMaterial(defineType()), enchantments, customEnchantments, - potionEffects, defineLore(), dropType, scalability); - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/UniqueItemInitializer.java b/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/UniqueItemInitializer.java deleted file mode 100644 index a8eadb521..000000000 --- a/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/UniqueItemInitializer.java +++ /dev/null @@ -1,70 +0,0 @@ -package com.magmaguy.elitemobs.items.uniqueitems; - -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.ItemsUniqueConfig; -import org.bukkit.inventory.ItemStack; - -import java.util.ArrayList; -import java.util.List; - -public class UniqueItemInitializer { - - /* - Elements are added to the list during the construction process - */ - public static List uniqueItemsList = new ArrayList(); - - public static void initialize() { - - if (!ConfigValues.itemsUniqueConfig.getBoolean(ItemsUniqueConfig.ENABLE_UNIQUE_ITEMS)) return; - - if (ConfigValues.itemsUniqueConfig.getBoolean(ItemsUniqueConfig.ENABLE_HUNTING_SET)) { - - HuntingHelmet huntingHelmet = new HuntingHelmet(); - huntingHelmet.constructItemStack(); - - HuntingChestplate huntingChestplate = new HuntingChestplate(); - huntingChestplate.constructItemStack(); - - HuntingLeggings huntingLeggings = new HuntingLeggings(); - huntingLeggings.constructItemStack(); - - HuntingBoots huntingBoots = new HuntingBoots(); - huntingBoots.constructItemStack(); - - HuntingBow huntingBow = new HuntingBow(); - huntingBow.constructItemStack(); - - } - - if (ConfigValues.itemsUniqueConfig.getBoolean(ItemsUniqueConfig.ENABLE_ZOMBIE_KING_AXE)) { - - ZombieKingsAxe zombieKingsAxe = new ZombieKingsAxe(); - zombieKingsAxe.constructItemStack(); - - } - - if (ConfigValues.itemsUniqueConfig.getBoolean(ItemsUniqueConfig.ENABLE_KRAKEN_FISHING_ROD)) { - - DepthsSeeker depthsSeeker = new DepthsSeeker(); - depthsSeeker.constructItemStack(); - - } - - if (ConfigValues.itemsUniqueConfig.getBoolean(ItemsUniqueConfig.ENABLE_GREED)) { - - DwarvenGreed dwarvenGreed = new DwarvenGreed(); - dwarvenGreed.constructItemStack(); - - } - - if (ConfigValues.itemsUniqueConfig.getBoolean(ItemsUniqueConfig.ENABLE_THE_FELLER)) { - - TheFeller theFeller = new TheFeller(); - theFeller.constructItemStack(); - - } - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/ZombieKingsAxe.java b/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/ZombieKingsAxe.java deleted file mode 100644 index 980913584..000000000 --- a/src/main/java/com/magmaguy/elitemobs/items/uniqueitems/ZombieKingsAxe.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.magmaguy.elitemobs.items.uniqueitems; - -import com.magmaguy.elitemobs.items.customenchantments.CustomEnchantmentCache; -import org.bukkit.Material; - -import java.util.Arrays; -import java.util.List; - -public class ZombieKingsAxe extends UniqueItem { - - @Override - public String definePath() { - return "Zombie Kings Axe"; - } - - @Override - public String defineType() { - return Material.GOLD_AXE.toString(); - } - - @Override - public String defineName() { - return "&4Zombie King's Axe"; - } - - @Override - public List defineLore() { - return Arrays.asList("The axe of the one Zombies", "call their king.", "The bloodlust is palpable."); - } - - @Override - public List defineEnchantments() { - return Arrays.asList( - "DAMAGE_ALL,10", - "DAMAGE_UNDEAD,5", - "DIG_SPEED,5", - "DURABILITY,5", - "KNOCKBACK,3", - "FIRE_ASPECT,4", - "LOOT_BONUS_MOBS,5", - "WATER_WORKER,5", - CustomEnchantmentCache.flamethrowerEnchantment.assembleConfigString(1) - ); - } - - @Override - public List definePotionEffects() { - return Arrays.asList( - "FAST_DIGGING,1,self,onHit", - "POISON,1,target,onHit", - "GLOWING,1,target,onHit", - "NIGHT_VISION,1,target,continuous", - "WITHER,1,target,onHit" - ); - } - - @Override - public String defineDropWeight() { - return "unique"; - } - - @Override - public String defineScalability() { - return "dynamic"; - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/menus/ArenaMenu.java b/src/main/java/com/magmaguy/elitemobs/menus/ArenaMenu.java new file mode 100644 index 000000000..7a9fcb9e9 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/menus/ArenaMenu.java @@ -0,0 +1,69 @@ +package com.magmaguy.elitemobs.menus; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.config.menus.premade.ArenaMenuConfig; +import com.magmaguy.elitemobs.instanced.ArenaInstance; +import lombok.Getter; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.inventory.Inventory; + +import java.util.HashMap; +import java.util.Map; + +public class ArenaMenu { + public void constructArenaMenu(Player player, String arenaFilename) { + ArenaInstance arenaInstance = ArenaInstance.getArenaInstances().get(arenaFilename); + if (arenaFilename == null) { + player.sendMessage(ChatColorConverter.convert("&4[EliteMobs] &cInvalid arena name!")); + return; + } + Inventory shopInventory = Bukkit.createInventory(player, 9, arenaInstance.getCustomArenasConfigFields().getArenaName()); + shopInventory.setItem(ArenaMenuConfig.getPlayerItemSlot(), ArenaMenuConfig.getPlayerItem()); + shopInventory.setItem(ArenaMenuConfig.getSpectatorItemSlot(), ArenaMenuConfig.getSpectatorItem()); + player.openInventory(shopInventory); + ArenaMenuEvents.menus.put(player, new MenuContainer(shopInventory, arenaInstance)); + } + + public static class ArenaMenuEvents implements Listener { + private static final Map menus = new HashMap<>(); + + @EventHandler(ignoreCancelled = true) + public void onInventoryClick(InventoryClickEvent event) { + Player player = ((Player) event.getWhoClicked()).getPlayer(); + if (!menus.containsKey(player)) return; + event.setCancelled(true); + if (event.getSlot() == ArenaMenuConfig.getPlayerItemSlot()) { + menus.get(player).getArenaInstance().addPlayer(player); + player.closeInventory(); + return; + } + if (event.getSlot() == ArenaMenuConfig.getSpectatorItemSlot()) { + menus.get(player).getArenaInstance().addSpectator(player); + player.closeInventory(); + return; + } + } + + @EventHandler + public void onInventoryClose(InventoryCloseEvent event) { + menus.remove(event.getPlayer()); + } + } + + private class MenuContainer { + @Getter + private Inventory inventory; + @Getter + private ArenaInstance arenaInstance; + + private MenuContainer(Inventory inventory, ArenaInstance arenaInstance) { + this.inventory = inventory; + this.arenaInstance = arenaInstance; + } + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/menus/BuyOrSellMenu.java b/src/main/java/com/magmaguy/elitemobs/menus/BuyOrSellMenu.java new file mode 100644 index 000000000..af06e30e1 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/menus/BuyOrSellMenu.java @@ -0,0 +1,67 @@ +package com.magmaguy.elitemobs.menus; + +import com.magmaguy.elitemobs.config.menus.premade.BuyOrSellMenuConfig; +import com.magmaguy.elitemobs.utils.ObfuscatedStringHandler; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +public class BuyOrSellMenu implements Listener { + + private static final String SHOP_KEY = ObfuscatedStringHandler.obfuscateString("/"); + public static final String SHOP_NAME = BuyOrSellMenuConfig.SHOP_NAME + SHOP_KEY; + + public static void constructBuyOrSellMenu(Player player, ItemStack buyItemStack) { + + Inventory shopInventory = Bukkit.createInventory(player, 18, SHOP_NAME); + + //information item + shopInventory.setItem(BuyOrSellMenuConfig.INFORMATION_SLOT, BuyOrSellMenuConfig.INFORMATION_ITEM); + + //sell item + shopInventory.setItem(BuyOrSellMenuConfig.SELL_SLOT, BuyOrSellMenuConfig.SELL_ITEM); + + //buy item + shopInventory.setItem(BuyOrSellMenuConfig.BUY_SLOT, buyItemStack); + + player.openInventory(shopInventory); + + } + + @EventHandler + public void onInventoryInteraction(InventoryClickEvent event) { + + if (!SharedShopElements.sellMenuNullPointPreventer(event)) return; + if (!event.getView().getTitle().equals(SHOP_NAME)) return; + event.setCancelled(true); + + //info button + if (event.getCurrentItem().equals(BuyOrSellMenuConfig.INFORMATION_ITEM)) { + return; + } + + //buy custom items button + if (event.getCurrentItem().getItemMeta().getDisplayName().equals(BuyOrSellMenuConfig.BUY_CUSTOM_ITEM.getItemMeta().getDisplayName())) { + CustomShopMenu.customShopConstructor((Player) event.getWhoClicked()); + return; + } + + //buy procedural items button + if (event.getCurrentItem().getItemMeta().getDisplayName().equals(BuyOrSellMenuConfig.BUY_PROCEDURAL_ITEM.getItemMeta().getDisplayName())) { + ProceduralShopMenu.shopConstructor((Player) event.getWhoClicked()); + return; + } + + //sell items button + if (event.getCurrentItem().getItemMeta().getDisplayName().equals(BuyOrSellMenuConfig.SELL_ITEM.getItemMeta().getDisplayName())) { + SellMenu sellMenu = new SellMenu(); + sellMenu.constructSellMenu((Player) event.getWhoClicked()); + } + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/menus/CustomShopMenu.java b/src/main/java/com/magmaguy/elitemobs/menus/CustomShopMenu.java new file mode 100644 index 000000000..135c907d9 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/menus/CustomShopMenu.java @@ -0,0 +1,160 @@ +package com.magmaguy.elitemobs.menus; + +import com.magmaguy.elitemobs.config.EconomySettingsConfig; +import com.magmaguy.elitemobs.config.menus.premade.BuyOrSellMenuConfig; +import com.magmaguy.elitemobs.config.menus.premade.CustomShopMenuConfig; +import com.magmaguy.elitemobs.economy.EconomyHandler; +import com.magmaguy.elitemobs.items.EliteItemLore; +import com.magmaguy.elitemobs.items.ItemTagger; +import com.magmaguy.elitemobs.items.ItemWorthCalculator; +import com.magmaguy.elitemobs.items.customenchantments.SoulbindEnchantment; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import com.magmaguy.elitemobs.utils.ObfuscatedStringHandler; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +import java.util.Random; + +/** + * Created by MagmaGuy on 20/06/2017. + */ +public class CustomShopMenu implements Listener { + + /** + * Fixed shop name, used to track if an event is happening within it + */ + private static final String SHOP_KEY = ObfuscatedStringHandler.obfuscateString("//"); + public static final String SHOP_NAME = CustomShopMenuConfig.shopName + SHOP_KEY; + + /** + * Creates a new instance of a BuyOrSellMenu + * + * @param player Player for whom the new menu will show up + */ + public static void customShopInitializer(Player player) { + + if (!EconomySettingsConfig.isEnableEconomy()) return; + BuyOrSellMenu.constructBuyOrSellMenu(player, BuyOrSellMenuConfig.BUY_CUSTOM_ITEM); + + } + + /** + * Creates a new instance of a custom shop + * + * @param player Player for whom the new menu will show up + */ + public static void customShopConstructor(Player player) { + + Inventory shopInventory = Bukkit.createInventory(player, 54, SHOP_NAME); + populateShop(shopInventory, player); + player.openInventory(shopInventory); + + } + + /** + * Preliminary shop fill + * + * @param shopInventory Inventory to be filled + */ + private static void populateShop(Inventory shopInventory, Player player) { + + shopInventory.setItem(CustomShopMenuConfig.rerollSlot, CustomShopMenuConfig.rerollItem); + shopContents(shopInventory, player); + + } + + /** + * Fills with the items to be sold in the shop + * + * @param shopInventory Inventory to be filled + */ + private static void shopContents(Inventory shopInventory, Player player) { + + //Anything after 8 is populated + Random random = new Random(); + + for (int i : CustomShopMenuConfig.storeSlots) { + + int itemEntryIndex = random.nextInt(CustomItem.getCustomItemStackShopList().size()); + + ItemStack itemStack = CustomItem.getCustomItemStackShopList().get(itemEntryIndex).clone(); + SoulbindEnchantment.addEnchantment(itemStack, player); + new EliteItemLore(itemStack, true); + + shopInventory.setItem(i, itemStack); + + } + + } + + @EventHandler + public void onClick(InventoryClickEvent event) { + + if (!event.getView().getTitle().equals(SHOP_NAME)) return; + if (event.getClickedInventory() == null || !event.getClickedInventory().getType().equals(InventoryType.CHEST)) { + event.setCancelled(true); + return; + } + event.setCancelled(true); + if (!SharedShopElements.inventoryNullPointerPreventer(event)) return; + + //reroll loot button + if (event.getCurrentItem().getItemMeta().getDisplayName().equals(CustomShopMenuConfig.rerollItem.getItemMeta().getDisplayName())) { + populateShop(event.getInventory(), Bukkit.getPlayer(event.getWhoClicked().getUniqueId())); + event.setCancelled(true); + return; + } + + if (!ItemTagger.isEliteItem(event.getCurrentItem())) { + event.setCancelled(true); + return; + } + + Player player = (Player) event.getWhoClicked(); + ItemStack itemStack = event.getCurrentItem(); + String itemDisplayName = event.getCurrentItem().getItemMeta().getDisplayName(); + + double itemValue = ItemWorthCalculator.determineItemWorth(itemStack, player); + + //These slots are for buying items + if (CustomShopMenuConfig.storeSlots.contains(event.getSlot()) && event.getView().getTitle().equalsIgnoreCase(SHOP_NAME)) { + + boolean inventoryHasFreeSlots = false; + for (ItemStack iteratedStack : player.getInventory()) + if (iteratedStack == null) { + inventoryHasFreeSlots = true; + break; + } + + if (!inventoryHasFreeSlots) { + + player.sendMessage(CustomShopMenuConfig.messageFullInventory); + player.closeInventory(); + + } else if (EconomyHandler.checkCurrency(player.getUniqueId()) >= itemValue) { + //player has enough money + EconomyHandler.subtractCurrency(player.getUniqueId(), itemValue); + new EliteItemLore(itemStack, false); + player.getInventory().addItem(itemStack); + populateShop(event.getInventory(), Bukkit.getPlayer(event.getWhoClicked().getUniqueId())); + + SharedShopElements.buyMessage(player, itemDisplayName, itemValue); + + } else { + + player.closeInventory(); + SharedShopElements.insufficientFundsMessage(player, itemValue); + + } + + } + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/menus/EliteMenu.java b/src/main/java/com/magmaguy/elitemobs/menus/EliteMenu.java new file mode 100644 index 000000000..096d701b3 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/menus/EliteMenu.java @@ -0,0 +1,57 @@ +package com.magmaguy.elitemobs.menus; + +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.inventory.Inventory; + +import java.util.List; +import java.util.Map; + +public class EliteMenu implements Listener { + + public static void createEliteMenu(Player player, Inventory inventory, Map inventories) { + inventories.put(player, inventory); + } + + public static boolean isEliteMenu(InventoryClickEvent event, Map inventories) { + if (event.getCurrentItem() == null) return false; + if (event.getCurrentItem().getType().equals(Material.AIR)) return false; + Player player = (Player) event.getWhoClicked(); + Inventory inventory = inventories.get(player); + if (inventory == null) return false; + return inventory.equals(event.getView().getTopInventory()); + } + + public static boolean isTopMenu(InventoryClickEvent event) { + return event.getClickedInventory().equals(event.getView().getTopInventory()); + } + + public static boolean isBottomMenu(InventoryClickEvent event) { + return !isTopMenu(event); + } + + public static boolean onInventoryClose(InventoryCloseEvent event, Map inventories) { + Player player = (Player) event.getPlayer(); + Inventory inventory = inventories.get(player); + if (inventory == null) return false; + inventories.remove(player); + return event.getView().getTopInventory().equals(inventory); + } + + public static void cancel(Inventory eliteInventory, Inventory playerInventory, List inputSlots) { + for (int slot : inputSlots) + if (eliteInventory.getItem(slot) != null) { + playerInventory.addItem(eliteInventory.getItem(slot)); + eliteInventory.remove(eliteInventory.getItem(slot)); + } + } + + public static void onPlayerQuit(PlayerQuitEvent event, Map inventories) { + inventories.remove(event.getPlayer()); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/menus/EnhancementMenu.java b/src/main/java/com/magmaguy/elitemobs/menus/EnhancementMenu.java new file mode 100644 index 000000000..415d116ae --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/menus/EnhancementMenu.java @@ -0,0 +1,202 @@ +package com.magmaguy.elitemobs.menus; + +import com.magmaguy.elitemobs.api.EliteMobsItemDetector; +import com.magmaguy.elitemobs.config.menus.premade.EnhancementMenuConfig; +import com.magmaguy.elitemobs.items.EliteItemLore; +import com.magmaguy.elitemobs.items.ItemTagger; +import com.magmaguy.elitemobs.items.ItemTierFinder; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; + +public class EnhancementMenu extends EliteMenu { + private static final int eliteItemInputSlot = EnhancementMenuConfig.eliteItemInputSlot; + private static final int scrapItemInputSlot = EnhancementMenuConfig.eliteUpgradeOrbInputSlot; + private static final int outputSlot = EnhancementMenuConfig.outputSlot; + private static final int eliteItemInformationInputSlot = EnhancementMenuConfig.eliteItemInputInformationSlot; + private static final int eliteScrapInformationInputSlot = EnhancementMenuConfig.eliteUpgradeOrbInputInformationSlot; + private static final int informationOutputSlot = EnhancementMenuConfig.outputInformationSlot; + public static HashMap inventories = new HashMap<>(); + + private static void calculateOutput(Inventory EnhancementInventory) { + if (EnhancementInventory.getItem(EnhancementMenuConfig.eliteUpgradeOrbInputSlot) == null || EnhancementInventory.getItem(EnhancementMenuConfig.eliteItemInputSlot) == null) { + EnhancementInventory.setItem(EnhancementMenuConfig.outputSlot, null); + return; + } + int enhancementScore = ItemTagger.getEnchantment(EnhancementInventory.getItem(EnhancementMenuConfig.eliteUpgradeOrbInputSlot).getItemMeta(), "EliteUpgradeItem"); + int itemScore = ItemTierFinder.findBattleTier(EnhancementInventory.getItem(EnhancementMenuConfig.eliteItemInputSlot)); + + if (enhancementScore <= itemScore) { + EnhancementInventory.setItem(EnhancementMenuConfig.outputSlot, null); + return; + } + + ItemStack outputItem = EnhancementInventory.getItem(EnhancementMenuConfig.eliteItemInputSlot).clone(); + Enchantment mainCombatEnchantment = ItemTierFinder.getMainCombatEnchantment(outputItem.getType()); + NamespacedKey enchantmentKey = mainCombatEnchantment.getKey(); + ItemMeta itemMeta = outputItem.getItemMeta(); + int enchantmentLevel = ItemTagger.getEnchantment(outputItem.getItemMeta(), enchantmentKey) + 1; + if (outputItem.getEnchantmentLevel(mainCombatEnchantment) < mainCombatEnchantment.getMaxLevel()) + outputItem.addEnchantment(mainCombatEnchantment, enchantmentLevel); + ItemTagger.registerEnchantment(itemMeta, enchantmentKey, enchantmentLevel); + outputItem.setItemMeta(itemMeta); + + new EliteItemLore(outputItem, false); + + EnhancementInventory.setItem(outputSlot, outputItem); + } + + /** + * Creates a menu for scrapping elitemobs items. Only special Elite Mob items can be scrapped here. + * + * @param player Player for whom the inventory will be created + */ + public void constructEnhancementMenu(Player player) { + Inventory EnhancementInventory = Bukkit.createInventory(player, 54, EnhancementMenuConfig.shopName); + + for (int i = 0; i < EnhancementInventory.getSize(); i++) { + + if (i == EnhancementMenuConfig.infoSlot) { + EnhancementInventory.setItem(i, EnhancementMenuConfig.infoButton); + continue; + } + + if (i == EnhancementMenuConfig.cancelSlot) { + EnhancementInventory.setItem(i, EnhancementMenuConfig.cancelButton); + continue; + } + + if (i == eliteItemInformationInputSlot) { + EnhancementInventory.setItem(i, EnhancementMenuConfig.eliteItemInputInfoButton); + continue; + } + + if (i == eliteScrapInformationInputSlot) { + EnhancementInventory.setItem(i, EnhancementMenuConfig.eliteUpgradeOrbInputInfoButton); + continue; + } + + if (i == informationOutputSlot) { + EnhancementInventory.setItem(i, EnhancementMenuConfig.outputInfoButton); + continue; + } + + + if (i == EnhancementMenuConfig.confirmSlot) { + + ItemStack clonedConfirmButton = EnhancementMenuConfig.confirmButton.clone(); + + List lore = new ArrayList<>(); + for (String string : EnhancementMenuConfig.confirmButton.getItemMeta().getLore()) + lore.add(string); + EnhancementMenuConfig.confirmButton.getItemMeta().setLore(lore); + ItemMeta clonedMeta = clonedConfirmButton.getItemMeta(); + clonedMeta.setLore(lore); + clonedConfirmButton.setItemMeta(clonedMeta); + EnhancementInventory.setItem(i, clonedConfirmButton); + continue; + + } + + + if (i == EnhancementMenuConfig.eliteItemInputSlot || i == EnhancementMenuConfig.eliteUpgradeOrbInputSlot || i == EnhancementMenuConfig.outputSlot) + continue; + EnhancementInventory.setItem(i, ItemStackGenerator.generateItemStack(Material.GLASS_PANE)); + + } + + player.openInventory(EnhancementInventory); + createEliteMenu(player, EnhancementInventory, inventories); + } + + public static class EnhancementMenuEvents implements Listener { + @EventHandler + public void onInteract(InventoryClickEvent event) { + if (!isEliteMenu(event, inventories)) return; + event.setCancelled(true); + + Player player = (Player) event.getWhoClicked(); + ItemStack currentItem = event.getCurrentItem(); + int clickedSlot = event.getSlot(); + Inventory EnhancementInventory = event.getView().getTopInventory(); + Inventory playerInventory = event.getView().getBottomInventory(); + + if (isBottomMenu(event)) { + + //Item is upgrade orb + if (ItemTagger.hasEnchantment(currentItem.getItemMeta(), "EliteUpgradeItem")) { + int upgradeOrbLevel = ItemTagger.getEnchantment(currentItem.getItemMeta(), "EliteUpgradeItem"); + if (upgradeOrbLevel >= 0) { + if (EnhancementInventory.getItem(scrapItemInputSlot) == null) { + EnhancementInventory.setItem(scrapItemInputSlot, currentItem); + playerInventory.clear(clickedSlot); + calculateOutput(EnhancementInventory); + } + return; + } + } + + //Item is elite combat item + if (EliteMobsItemDetector.isEliteMobsItem(currentItem)) + if (ItemTierFinder.getMainCombatEnchantment(currentItem.getType()) != null) + if (EnhancementInventory.getItem(eliteItemInputSlot) == null) { + EnhancementInventory.setItem(eliteItemInputSlot, currentItem); + playerInventory.remove(currentItem); + calculateOutput(EnhancementInventory); + } + + } else if (isTopMenu(event)) { + + //return item to inventory + if (event.getSlot() == scrapItemInputSlot || event.getSlot() == eliteItemInputSlot) { + playerInventory.addItem(currentItem); + EnhancementInventory.remove(currentItem); + calculateOutput(EnhancementInventory); + return; + } + + //cancel button + if (event.getSlot() == EnhancementMenuConfig.cancelSlot) { + player.closeInventory(); + return; + } + + //confirm button + if (event.getSlot() == EnhancementMenuConfig.confirmSlot) { + if (EnhancementInventory.getItem(outputSlot) != null) { + EnhancementInventory.setItem(EnhancementMenuConfig.eliteItemInputSlot, null); + EnhancementInventory.setItem(EnhancementMenuConfig.eliteUpgradeOrbInputSlot, null); + playerInventory.addItem(EnhancementInventory.getItem(outputSlot)); + EnhancementInventory.remove(EnhancementInventory.getItem(outputSlot)); + EnhancementInventory.setItem(outputSlot, null); + } + } + + } + + } + + @EventHandler + public void onInventoryClose(InventoryCloseEvent event) { + if (!EliteMenu.onInventoryClose(event, inventories)) return; + EliteMenu.cancel(event.getView().getTopInventory(), event.getView().getBottomInventory(), Arrays.asList(eliteItemInputSlot, scrapItemInputSlot)); + } + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/menus/GetLootMenu.java b/src/main/java/com/magmaguy/elitemobs/menus/GetLootMenu.java new file mode 100644 index 000000000..471a60cbf --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/menus/GetLootMenu.java @@ -0,0 +1,200 @@ +package com.magmaguy.elitemobs.menus; + +import com.magmaguy.elitemobs.config.menus.premade.GetLootMenuConfig; +import com.magmaguy.elitemobs.items.customitems.CustomItem; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.*; + +/** + * Created by MagmaGuy on 04/05/2017. + */ +public class GetLootMenu extends EliteMenu implements Listener { + + private static final List lootSlots = new ArrayList<>(Arrays.asList(10, 11, 12, 13, 14, 15, 16, 19, 20, 21, 22, 23, 24, 25, 28, 29, 30, 31, + 32, 33, 34, 37, 38, 39, 40, 41, 42, 43, 46, 47, 48, 49, 50, 51, 52)); + public static HashMap inventories = new HashMap<>(); + private final String shopName = GetLootMenuConfig.menuName; + public int currentHeaderPage = 1; + public int currentLootPage = 1; + public boolean filter = false; + public int filterRank = 0; + public Inventory inventory; + + public GetLootMenu(Player player) { + + Inventory fakeChestInventory = Bukkit.createInventory(null, 54, shopName); + tierConstructor(fakeChestInventory); + headerConstructor(fakeChestInventory); + lootNavigationConstructor(fakeChestInventory); + lootConstructor(fakeChestInventory); + + player.openInventory(fakeChestInventory); + inventory = fakeChestInventory; + + inventories.put(player, this); + } + + public GetLootMenu(Player player, GetLootMenu getLootMenu) { + this.currentHeaderPage = getLootMenu.currentHeaderPage; + this.currentLootPage = getLootMenu.currentLootPage; + this.filter = getLootMenu.filter; + this.filterRank = getLootMenu.filterRank; + Inventory fakeChestInventory = Bukkit.createInventory(null, 54, shopName); + tierConstructor(fakeChestInventory); + headerConstructor(fakeChestInventory); + lootNavigationConstructor(fakeChestInventory); + lootConstructor(fakeChestInventory); + + player.openInventory(fakeChestInventory); + inventory = fakeChestInventory; + + inventories.put(player, this); + } + + private void headerConstructor(Inventory inventory) { + inventory.setItem(0, GetLootMenuConfig.leftArrowItem); + inventory.setItem(8, GetLootMenuConfig.rightArrowItem); + inventory.setItem(4, GetLootMenuConfig.infoItem); + } + + private void tierConstructor(Inventory inventory) { + + List tierSlots = new ArrayList<>(); + + tierSlots.add(1); + tierSlots.add(2); + tierSlots.add(3); + tierSlots.add(5); + tierSlots.add(6); + tierSlots.add(7); + + List keySet = new ArrayList<>(CustomItem.getTieredLoot().keySet()); + Collections.sort(keySet); + + int counter = 1; + for (int number : tierSlots) { + if (keySet.size() >= counter + ((currentHeaderPage - 1) * 6)) { + ItemStack chest = new ItemStack(Material.CHEST, 1); + ItemMeta chestItemMeta = chest.getItemMeta(); + chestItemMeta.setDisplayName(GetLootMenuConfig.tierTranslation + " " + keySet.get((counter - 1) + ((currentHeaderPage - 1) * 6))); + List lore = new ArrayList(); + lore.add(GetLootMenuConfig.itemFilterTranslation); + chestItemMeta.setLore(lore); + chest.setItemMeta(chestItemMeta); + inventory.setItem(number, chest); + } + counter++; + } + + } + + private void lootNavigationConstructor(Inventory inventory) { + inventory.setItem(27, GetLootMenuConfig.previousLootItem); + inventory.setItem(35, GetLootMenuConfig.nextLootItem); + } + + private void lootConstructor(Inventory inventory) { + + List getLootList = new ArrayList<>(); + for (List list : CustomItem.getTieredLoot().values()) + getLootList.addAll(list); + + int counter = 1; + for (int number : lootSlots) { + if (!filter) { + if (getLootList.size() >= counter + ((currentLootPage - 1) * 35)) + inventory.setItem(number, getLootList.get(counter - 1 + ((currentLootPage - 1) * 35))); + } else { + List currentRankLoot = CustomItem.getTieredLoot().get(filterRank); + if (currentRankLoot.size() >= counter + ((currentLootPage - 1) * 35)) + inventory.setItem(number, currentRankLoot.get(counter - 1 + ((currentLootPage - 1) * 35))); + } + counter++; + } + } + + public static class GetLootMenuListener implements Listener { + @EventHandler + public void onClick(InventoryClickEvent event) { + + GetLootMenu getLootMenu = null; + for (GetLootMenu iteratedMenu : inventories.values()) + if (iteratedMenu != null && iteratedMenu.inventory.equals(event.getInventory())) { + getLootMenu = iteratedMenu; + break; + } + if (getLootMenu == null) return; + event.setCancelled(true); + + Player player = (Player) event.getWhoClicked(); + ItemStack currentItem = event.getCurrentItem(); + + if (!isTopMenu(event)) return; + //CASE: If the player clicked something in the actual getloot menu + + //CASE: If it was one of the items that they can get + if (lootSlots.contains(event.getSlot())) { + player.getInventory().addItem(currentItem); + return; + } + + if (currentItem == null || currentItem.getItemMeta() == null) return; + //CASE: If it was the "back to home" button + if (event.getSlot() == 4) { + new GetLootMenu(player); + return; + } + + //CASE: Left header arrow, previous tier + if (event.getSlot() == 0) { + if (getLootMenu.currentHeaderPage - 1 > 1) { + getLootMenu.currentHeaderPage--; + new GetLootMenu(player, getLootMenu); + } + return; + } + + if (event.getSlot() == 8) { + getLootMenu.currentHeaderPage++; + new GetLootMenu(player, getLootMenu); + return; + } + + if (event.getSlot() == 27) { + getLootMenu.currentLootPage--; + new GetLootMenu(player, getLootMenu); + return; + } + + if (event.getSlot() == 35) { + getLootMenu.currentLootPage++; + new GetLootMenu(player, getLootMenu); + return; + } + + if (event.getSlot() == 1 || + event.getSlot() == 2 || + event.getSlot() == 3 || + event.getSlot() == 5 || + event.getSlot() == 6 || + event.getSlot() == 7) { + getLootMenu.filter = true; + getLootMenu.filterRank = Integer.parseInt(currentItem.getItemMeta().getDisplayName().split("\\s")[1]); + getLootMenu.currentLootPage = 1; + new GetLootMenu(player, getLootMenu); + return; + } + } + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/menus/ProceduralShopMenu.java b/src/main/java/com/magmaguy/elitemobs/menus/ProceduralShopMenu.java new file mode 100644 index 000000000..83f3430b2 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/menus/ProceduralShopMenu.java @@ -0,0 +1,139 @@ +package com.magmaguy.elitemobs.menus; + +import com.magmaguy.elitemobs.config.EconomySettingsConfig; +import com.magmaguy.elitemobs.config.menus.premade.BuyOrSellMenuConfig; +import com.magmaguy.elitemobs.config.menus.premade.ProceduralShopMenuConfig; +import com.magmaguy.elitemobs.economy.EconomyHandler; +import com.magmaguy.elitemobs.items.EliteItemLore; +import com.magmaguy.elitemobs.items.ItemTagger; +import com.magmaguy.elitemobs.items.ItemWorthCalculator; +import com.magmaguy.elitemobs.items.itemconstructor.ItemConstructor; +import com.magmaguy.elitemobs.utils.ObfuscatedStringHandler; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +import java.util.List; +import java.util.Random; + +/** + * Created by MagmaGuy on 17/06/2017. + */ +public class ProceduralShopMenu implements Listener { + + private static final String SHOP_KEY = ObfuscatedStringHandler.obfuscateString("/"); + private static final String SHOP_NAME = ProceduralShopMenuConfig.shopName + SHOP_KEY; + private static final List validSlots = ProceduralShopMenuConfig.storeSlots; + + public static void shopInitializer(Player player) { + + if (!EconomySettingsConfig.isEnableEconomy()) return; + BuyOrSellMenu.constructBuyOrSellMenu(player, BuyOrSellMenuConfig.BUY_PROCEDURAL_ITEM); + + } + + public static void shopConstructor(Player player) { + + Inventory shopInventory = Bukkit.createInventory(player, 54, SHOP_NAME); + populateShop(shopInventory, player); + player.openInventory(shopInventory); + + } + + private static void populateShop(Inventory shopInventory, Player player) { + + shopInventory.setItem(ProceduralShopMenuConfig.rerollSlot, ProceduralShopMenuConfig.rerollItem); + shopContents(shopInventory, player); + + } + + private static void shopContents(Inventory shopInventory, Player player) { + + Random random = new Random(); + + for (int i : validSlots) { + + int balancedMax = ProceduralShopMenuConfig.maxTier - ProceduralShopMenuConfig.minTier; + int balancedMin = ProceduralShopMenuConfig.minTier; + + int randomTier = random.nextInt(balancedMax) + balancedMin; + + ItemStack itemStack = ItemConstructor.constructItem(randomTier, null, player, true); + //SoulbindEnchantment.addEnchantment(itemStack, player); + new EliteItemLore(itemStack, true); + + shopInventory.setItem(i, itemStack); + + } + + } + + @EventHandler + public void onClick(InventoryClickEvent event) { + + if (!event.getView().getTitle().equals(SHOP_NAME)) return; + if (event.getClickedInventory() == null || !event.getClickedInventory().getType().equals(InventoryType.CHEST)) { + event.setCancelled(true); + return; + } + event.setCancelled(true); + if (!SharedShopElements.inventoryNullPointerPreventer(event)) return; + + //reroll loot button + if (event.getCurrentItem().getItemMeta().getDisplayName().equals(ProceduralShopMenuConfig.rerollItem.getItemMeta().getDisplayName())) { + populateShop(event.getInventory(), Bukkit.getPlayer(event.getWhoClicked().getUniqueId())); + event.setCancelled(true); + return; + } + + if (!ItemTagger.isEliteItem(event.getCurrentItem())) { + event.setCancelled(true); + return; + } + + Player player = (Player) event.getWhoClicked(); + ItemStack itemStack = event.getCurrentItem(); + String itemDisplayName = itemStack.getItemMeta().getDisplayName(); + + double itemValue = ItemWorthCalculator.determineItemWorth(itemStack, player); + + boolean inventoryHasFreeSlots = false; + for (ItemStack iteratedStack : player.getInventory().getStorageContents()) + if (iteratedStack == null) { + inventoryHasFreeSlots = true; + break; + } + + //These slots are for buying items + if (event.getView().getTitle().equalsIgnoreCase(SHOP_NAME) && validSlots.contains(event.getSlot())) { + + if (!inventoryHasFreeSlots) { + + player.sendMessage(ProceduralShopMenuConfig.messageFullInventory); + player.closeInventory(); + + } else if (EconomyHandler.checkCurrency(player.getUniqueId()) >= itemValue) { + //player has enough money + EconomyHandler.subtractCurrency(player.getUniqueId(), itemValue); + new EliteItemLore(itemStack, false); + player.getInventory().addItem(itemStack); + populateShop(event.getInventory(), Bukkit.getPlayer(event.getWhoClicked().getUniqueId())); + SharedShopElements.buyMessage(player, itemDisplayName, itemValue); + + } else { + + player.closeInventory(); + SharedShopElements.insufficientFundsMessage(player, itemValue); + + } + + } + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/menus/RefinerMenu.java b/src/main/java/com/magmaguy/elitemobs/menus/RefinerMenu.java new file mode 100644 index 000000000..6bbb1cc84 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/menus/RefinerMenu.java @@ -0,0 +1,221 @@ +package com.magmaguy.elitemobs.menus; + +import com.magmaguy.elitemobs.config.menus.premade.RefinerMenuConfig; +import com.magmaguy.elitemobs.config.menus.premade.SellMenuConfig; +import com.magmaguy.elitemobs.items.ItemTagger; +import com.magmaguy.elitemobs.items.itemconstructor.ItemConstructor; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class RefinerMenu extends EliteMenu { + + protected static final Map inventories = new HashMap<>(); + private static final List inputSlots = RefinerMenuConfig.getInputSlots(); + + private static ArrayList[] calculateOutput(Inventory inventory, Player player) { + ArrayList inputItemStacks = new ArrayList<>(); + for (int slot : inputSlots) + inputItemStacks.add(inventory.getItem(slot)); + // itemStack[0] = inputArray , itemStack[1] = outputArray + ArrayList[] itemStacks = new ArrayList[2]; + itemStacks[0] = new ArrayList<>(); + itemStacks[1] = new ArrayList<>(); + HashMap inputScrapLevelAndAmountHashMap = new HashMap<>(); + + for (ItemStack itemStack : inputItemStacks) + if (itemStack != null) { + int scrapLevel = ItemTagger.getEnchantment(itemStack.getItemMeta(), "EliteScrap"); + if (scrapLevel >= 0) { + if (inputScrapLevelAndAmountHashMap.containsKey(scrapLevel)) + inputScrapLevelAndAmountHashMap.put(scrapLevel, inputScrapLevelAndAmountHashMap.get(scrapLevel) + itemStack.getAmount()); + else + inputScrapLevelAndAmountHashMap.put(scrapLevel, itemStack.getAmount()); + } else + itemStacks[0].add(itemStack); + } + + for (Integer scrapLevel : inputScrapLevelAndAmountHashMap.keySet()) { + int scrapAmount = inputScrapLevelAndAmountHashMap.get(scrapLevel); + int newScrapAmount = (int) (scrapAmount / 10d); + int scrapRemainderAmount = scrapAmount - newScrapAmount * 10; + + ItemStack scrapRemainderItem = ItemConstructor.constructScrapItem( + scrapLevel, player, false); + scrapRemainderItem.setAmount(scrapRemainderAmount); + itemStacks[0].add(scrapRemainderItem); + + ItemStack upgradedScrapItem = ItemConstructor.constructScrapItem( + scrapLevel + 1, player, false); + upgradedScrapItem.setAmount(newScrapAmount); + itemStacks[1].add(upgradedScrapItem); + } + + return itemStacks; + } + + private static void refreshOutputVisuals(Inventory inventory, List outputSlots, Player player) { + ArrayList[] output = calculateOutput(inventory, player); + for (int i = 0; i < outputSlots.size(); i++) + if (output[1].size() > i) + inventory.setItem(outputSlots.get(i), output[1].get(i)); + else + inventory.setItem(outputSlots.get(i), null); + } + + /** + * Creates a menu for scrapping elitemobs items. Only special Elite Mob items can be scrapped here. + * + * @param player Player for whom the inventory will be created + */ + public void constructRefinerMenu(Player player) { + + Inventory refinerInventory = Bukkit.createInventory(player, 54, RefinerMenuConfig.getShopName()); + + for (int i = 0; i < 54; i++) { + + if (i == RefinerMenuConfig.getInfoSlot()) { + refinerInventory.setItem(i, RefinerMenuConfig.getInfoButton()); + continue; + } + + if (i == RefinerMenuConfig.getCancelSlot()) { + refinerInventory.setItem(i, RefinerMenuConfig.getCancelButton()); + continue; + } + + if (i == RefinerMenuConfig.getInputInformationSlot()) { + refinerInventory.setItem(i, RefinerMenuConfig.getInputInfoButton()); + continue; + } + + if (i == RefinerMenuConfig.getOutputInformationSlot()) { + refinerInventory.setItem(i, RefinerMenuConfig.getOutputInfoButton()); + continue; + } + + + if (i == RefinerMenuConfig.getConfirmSlot()) { + + ItemStack clonedConfirmButton = RefinerMenuConfig.getConfirmButton().clone(); + + List lore = new ArrayList<>(); + for (String string : RefinerMenuConfig.getConfirmButton().getItemMeta().getLore()) + lore.add(string); + RefinerMenuConfig.getConfirmButton().getItemMeta().setLore(lore); + ItemMeta clonedMeta = clonedConfirmButton.getItemMeta(); + clonedMeta.setLore(lore); + clonedConfirmButton.setItemMeta(clonedMeta); + refinerInventory.setItem(i, clonedConfirmButton); + continue; + + } + + if (inputSlots.contains(i) || RefinerMenuConfig.getOutputSlots().contains(i)) + continue; + + refinerInventory.setItem(i, ItemStackGenerator.generateItemStack(Material.GLASS_PANE)); + + } + + player.openInventory(refinerInventory); + createEliteMenu(player, refinerInventory, inventories); + } + + public static class RefinerMenuEvents implements Listener { + @EventHandler(ignoreCancelled = true) + public void onInventoryInteract(InventoryClickEvent event) { + if (!isEliteMenu(event, inventories)) return; + event.setCancelled(true); + + Player player = (Player) event.getWhoClicked(); + ItemStack currentItem = event.getCurrentItem(); + Inventory shopInventory = event.getView().getTopInventory(); + Inventory playerInventory = event.getView().getBottomInventory(); + + if (EliteMenu.isBottomMenu(event)) { + //CASE: If the player clicked on something in their inventory to put it on the shop + + if (!ItemTagger.hasEnchantment(currentItem.getItemMeta(), "EliteScrap")) return; + + boolean isFull = true; + + //If the shop is full, don't let the player put stuff in it + for (int i : RefinerMenuConfig.getInputSlots()) + if (shopInventory.getItem(i) == null) + isFull = false; + + if (isFull) return; + + //Do transfer + for (int slot : RefinerMenu.inputSlots) + if (shopInventory.getItem(slot) == null) { + shopInventory.setItem(slot, currentItem); + playerInventory.clear(event.getSlot()); + break; + } + + refreshOutputVisuals(shopInventory, RefinerMenuConfig.getOutputSlots(), player); + + } else if (EliteMenu.isTopMenu(event)) { + //CASE: Player clicked on the shop + + //Signature item, does nothing + if (currentItem.equals(SellMenuConfig.infoButton)) + return; + + //upgrade items in shop + if (event.getSlot() == SellMenuConfig.confirmSlot) { + + for (int i = 0; i < 2; i++) + for (ItemStack itemStack : calculateOutput(shopInventory, player)[i]) + player.getInventory().addItem(itemStack); + + for (int slot : RefinerMenuConfig.getInputSlots()) + shopInventory.setItem(slot, null); + for (int slot : RefinerMenuConfig.getOutputSlots()) + shopInventory.setItem(slot, null); + + return; + } + + //cancel, transfer items back to player inv and exit + if (event.getSlot() == SellMenuConfig.cancelSlot) { + player.closeInventory(); + return; + } + + //If player clicks on a border glass pane, do nothing + if (!inputSlots.contains(event.getSlot())) return; + + //If player clicks on one of the items already in the shop, return to their inventory + playerInventory.addItem(event.getCurrentItem()); + shopInventory.clear(event.getSlot()); + refreshOutputVisuals(shopInventory, RefinerMenuConfig.getOutputSlots(), player); + + } + + } + + @EventHandler + public void onInventoryClose(InventoryCloseEvent event) { + if (!EliteMenu.onInventoryClose(event, inventories)) return; + EliteMenu.cancel(event.getView().getTopInventory(), event.getView().getBottomInventory(), inputSlots); + } + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/menus/RepairMenu.java b/src/main/java/com/magmaguy/elitemobs/menus/RepairMenu.java new file mode 100644 index 000000000..03e501564 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/menus/RepairMenu.java @@ -0,0 +1,190 @@ +package com.magmaguy.elitemobs.menus; + +import com.magmaguy.elitemobs.api.EliteMobsItemDetector; +import com.magmaguy.elitemobs.config.menus.premade.RepairMenuConfig; +import com.magmaguy.elitemobs.items.ItemTagger; +import com.magmaguy.elitemobs.items.ItemTierFinder; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.Damageable; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; + +public class RepairMenu extends EliteMenu { + private static final int eliteItemInputSlot = RepairMenuConfig.eliteItemInputSlot; + private static final int scrapItemInputSlot = RepairMenuConfig.eliteScrapInputSlot; + private static final int outputSlot = RepairMenuConfig.outputSlot; + private static final int eliteItemInformationInputSlot = RepairMenuConfig.eliteItemInputInformationSlot; + private static final int eliteScrapInformationInputSlot = RepairMenuConfig.eliteScrapInputInformationSlot; + private static final int informationOutputSlot = RepairMenuConfig.outputInformationSlot; + public static HashMap inventories = new HashMap<>(); + + private static void calculateOutput(Inventory repairInventory) { + if (repairInventory.getItem(RepairMenuConfig.eliteScrapInputSlot) == null || repairInventory.getItem(RepairMenuConfig.eliteItemInputSlot) == null) { + repairInventory.setItem(RepairMenuConfig.outputSlot, null); + return; + } + + int scrapLevel = ItemTagger.getEnchantment(repairInventory.getItem(RepairMenuConfig.eliteScrapInputSlot).getItemMeta(), "EliteScrap"); + ItemStack outputItem = repairInventory.getItem(RepairMenuConfig.eliteItemInputSlot).clone(); + int itemLevel = ItemTierFinder.findBattleTier(outputItem); + int baselineRepair = 300; + int levelDifferenceModifier = (scrapLevel - itemLevel) * 10; + int newDamage = baselineRepair + levelDifferenceModifier; + Damageable damageable = (Damageable) outputItem.getItemMeta(); + int damage = Math.min(damageable.getDamage() - newDamage, damageable.getDamage()); + damageable.setDamage(damage); + outputItem.setItemMeta(damageable); + repairInventory.setItem(outputSlot, outputItem); + } + + /** + * Creates a menu for scrapping elitemobs items. Only special Elite Mob items can be scrapped here. + * + * @param player Player for whom the inventory will be created + */ + public void constructRepairMenu(Player player) { + Inventory repairInventory = Bukkit.createInventory(player, 54, RepairMenuConfig.shopName); + + for (int i = 0; i < repairInventory.getSize(); i++) { + + if (i == RepairMenuConfig.infoSlot) { + repairInventory.setItem(i, RepairMenuConfig.infoButton); + continue; + } + + if (i == RepairMenuConfig.cancelSlot) { + repairInventory.setItem(i, RepairMenuConfig.cancelButton); + continue; + } + + if (i == eliteItemInformationInputSlot) { + repairInventory.setItem(i, RepairMenuConfig.eliteItemInputInfoButton); + continue; + } + + if (i == eliteScrapInformationInputSlot) { + repairInventory.setItem(i, RepairMenuConfig.eliteScrapInputInfoButton); + continue; + } + + if (i == informationOutputSlot) { + repairInventory.setItem(i, RepairMenuConfig.outputInfoButton); + continue; + } + + + if (i == RepairMenuConfig.confirmSlot) { + + ItemStack clonedConfirmButton = RepairMenuConfig.confirmButton.clone(); + + List lore = new ArrayList<>(); + for (String string : RepairMenuConfig.confirmButton.getItemMeta().getLore()) + lore.add(string); + RepairMenuConfig.confirmButton.getItemMeta().setLore(lore); + ItemMeta clonedMeta = clonedConfirmButton.getItemMeta(); + clonedMeta.setLore(lore); + clonedConfirmButton.setItemMeta(clonedMeta); + repairInventory.setItem(i, clonedConfirmButton); + continue; + + } + + + if (i == RepairMenuConfig.eliteItemInputSlot || i == RepairMenuConfig.eliteScrapInputSlot || i == RepairMenuConfig.outputSlot) + continue; + repairInventory.setItem(i, ItemStackGenerator.generateItemStack(Material.GLASS_PANE)); + + } + + player.openInventory(repairInventory); + createEliteMenu(player, repairInventory, inventories); + } + + public static class RepairMenuEvents implements Listener { + @EventHandler + public void onInteract(InventoryClickEvent event) { + if (!isEliteMenu(event, inventories)) return; + event.setCancelled(true); + + Player player = (Player) event.getWhoClicked(); + ItemStack currentItem = event.getCurrentItem(); + int clickedSlot = event.getSlot(); + Inventory repairInventory = event.getView().getTopInventory(); + Inventory playerInventory = event.getView().getBottomInventory(); + + if (isBottomMenu(event)) { + //Item is scrap + if (ItemTagger.hasEnchantment(currentItem.getItemMeta(), "EliteScrap")) { + int scrapLevel = ItemTagger.getEnchantment(currentItem.getItemMeta(), "EliteScrap"); + if (scrapLevel >= 0) { + if (repairInventory.getItem(scrapItemInputSlot) == null) { + repairInventory.setItem(scrapItemInputSlot, currentItem); + playerInventory.clear(clickedSlot); + calculateOutput(repairInventory); + } + return; + } + } + + //Item is elite item + if (EliteMobsItemDetector.isEliteMobsItem(currentItem)) + if (currentItem.getItemMeta() instanceof Damageable) + if (repairInventory.getItem(eliteItemInputSlot) == null) { + repairInventory.setItem(eliteItemInputSlot, currentItem); + playerInventory.remove(currentItem); + calculateOutput(repairInventory); + } + + } else if (isTopMenu(event)) { + + //return item to inventory + if (event.getSlot() == scrapItemInputSlot || event.getSlot() == eliteItemInputSlot) { + playerInventory.addItem(currentItem); + repairInventory.remove(currentItem); + calculateOutput(repairInventory); + return; + } + + //cancel button + if (event.getSlot() == RepairMenuConfig.cancelSlot) { + player.closeInventory(); + return; + } + + //confirm button + if (event.getSlot() == RepairMenuConfig.confirmSlot) { + if (repairInventory.getItem(outputSlot) != null) { + repairInventory.setItem(RepairMenuConfig.eliteItemInputSlot, null); + repairInventory.setItem(RepairMenuConfig.eliteScrapInputSlot, null); + playerInventory.addItem(repairInventory.getItem(outputSlot)); + repairInventory.remove(repairInventory.getItem(outputSlot)); + repairInventory.setItem(outputSlot, null); + } + } + + } + + } + + @EventHandler + public void onInventoryClose(InventoryCloseEvent event) { + if (!EliteMenu.onInventoryClose(event, inventories)) return; + EliteMenu.cancel(event.getView().getTopInventory(), event.getView().getBottomInventory(), Arrays.asList(eliteItemInputSlot, scrapItemInputSlot)); + } + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/menus/ScrapperMenu.java b/src/main/java/com/magmaguy/elitemobs/menus/ScrapperMenu.java new file mode 100644 index 000000000..afb32cbc8 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/menus/ScrapperMenu.java @@ -0,0 +1,172 @@ +package com.magmaguy.elitemobs.menus; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.api.EliteMobsItemDetector; +import com.magmaguy.elitemobs.config.ItemSettingsConfig; +import com.magmaguy.elitemobs.config.TranslationConfig; +import com.magmaguy.elitemobs.config.menus.premade.ScrapperMenuConfig; +import com.magmaguy.elitemobs.config.menus.premade.SellMenuConfig; +import com.magmaguy.elitemobs.items.ItemTierFinder; +import com.magmaguy.elitemobs.items.customenchantments.SoulbindEnchantment; +import com.magmaguy.elitemobs.items.itemconstructor.ItemConstructor; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +public class ScrapperMenu extends EliteMenu { + private static final List validSlots = ScrapperMenuConfig.storeSlots; + + public static HashMap inventories = new HashMap<>(); + + /** + * Creates a menu for scrapping elitemobs items. Only special Elite Mob items can be scrapped here. + * + * @param player Player for whom the inventory will be created + */ + public void constructScrapMenu(Player player) { + + Inventory scrapInventory = Bukkit.createInventory(player, 54, ScrapperMenuConfig.shopName); + + for (int i = 0; i < 54; i++) { + + if (i == ScrapperMenuConfig.infoSlot) { + scrapInventory.setItem(i, ScrapperMenuConfig.infoButton); + continue; + } + + if (i == ScrapperMenuConfig.cancelSlot) { + scrapInventory.setItem(i, ScrapperMenuConfig.cancelButton); + continue; + } + + if (i == ScrapperMenuConfig.confirmSlot) { + + ItemStack clonedConfirmButton = ScrapperMenuConfig.confirmButton.clone(); + + List lore = new ArrayList<>(); + for (String string : ScrapperMenuConfig.confirmButton.getItemMeta().getLore()) + lore.add(string); + ScrapperMenuConfig.confirmButton.getItemMeta().setLore(lore); + ItemMeta clonedMeta = clonedConfirmButton.getItemMeta(); + clonedMeta.setLore(lore); + clonedConfirmButton.setItemMeta(clonedMeta); + scrapInventory.setItem(i, clonedConfirmButton); + continue; + + } + + if (validSlots.contains(i)) + continue; + + scrapInventory.setItem(i, ItemStackGenerator.generateItemStack(Material.GLASS_PANE)); + + } + + player.openInventory(scrapInventory); + createEliteMenu(player, scrapInventory, inventories); + + } + + public static class ScrapperMenuEvents implements Listener { + @EventHandler(ignoreCancelled = true) + public void onInventoryInteract(InventoryClickEvent event) { + if (!isEliteMenu(event, inventories)) return; + event.setCancelled(true); + + Player player = (Player) event.getWhoClicked(); + ItemStack currentItem = event.getCurrentItem(); + Inventory shopInventory = event.getView().getTopInventory(); + Inventory playerInventory = event.getView().getBottomInventory(); + + if (EliteMenu.isBottomMenu(event)) { + //CASE: If the player clicked on something in their inventory to put it on the shop + + //Check if it's an elitemobs item. The soulbind check only says if the player would be able to pick it up, and vanilla items can be picked up + if (!EliteMobsItemDetector.isEliteMobsItem(event.getCurrentItem())) { + event.getWhoClicked().sendMessage(ChatColorConverter.convert(TranslationConfig.getShopSaleInstructions())); + return; + } + + //If the item isn't soulbound to the player, it can't be sold by that player + if (!SoulbindEnchantment.isValidSoulbindUser(currentItem.getItemMeta(), player)) { + player.sendMessage(ChatColorConverter.convert(TranslationConfig.getShopSaleOthersItems())); + return; + } + + //Do transfer + for (int slot : ScrapperMenuConfig.storeSlots) + if (shopInventory.getItem(slot) == null) { + shopInventory.setItem(slot, currentItem); + playerInventory.clear(event.getSlot()); + break; + } + + } else if (EliteMenu.isTopMenu(event)) { + //CASE: Player clicked on the shop + + //Signature item, does nothing + if (currentItem.equals(SellMenuConfig.infoButton)) + return; + + //sell items in shop + if (event.getSlot() == SellMenuConfig.confirmSlot) { + + for (Integer validSlot : validSlots) { + ItemStack itemStack = shopInventory.getItem(validSlot); + if (itemStack == null) + continue; + int tier = ItemTierFinder.findBattleTier(itemStack); + for (int i = 0; i < itemStack.getAmount(); i++) { + if (ThreadLocalRandom.current().nextDouble() > .75) { + player.sendMessage(ChatColorConverter.convert(ItemSettingsConfig.getScrapFailedMessage())); + continue; + } + player.getInventory().addItem(ItemConstructor.constructScrapItem(tier, player, false)); + player.sendMessage(ChatColorConverter.convert(ItemSettingsConfig.getScrapSucceededMessage())); + } + itemStack.setAmount(0); + } + + return; + } + + //cancel, transfer items back to player inv and exit + if (event.getSlot() == SellMenuConfig.cancelSlot) { + player.closeInventory(); + return; + } + + //If player clicks on a border glass pane, do nothing + if (!validSlots.contains(event.getSlot())) return; + + + //If player clicks on one of the items already in the shop, return to their inventory + playerInventory.addItem(event.getCurrentItem()); + shopInventory.clear(event.getSlot()); + + } + + } + + @EventHandler + public void onInventoryClose(InventoryCloseEvent event) { + if (!EliteMenu.onInventoryClose(event, inventories)) return; + EliteMenu.cancel(event.getView().getTopInventory(), event.getView().getBottomInventory(), validSlots); + } + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/menus/SellMenu.java b/src/main/java/com/magmaguy/elitemobs/menus/SellMenu.java new file mode 100644 index 000000000..7d6c40f18 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/menus/SellMenu.java @@ -0,0 +1,231 @@ +package com.magmaguy.elitemobs.menus; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.api.EliteMobsItemDetector; +import com.magmaguy.elitemobs.config.EconomySettingsConfig; +import com.magmaguy.elitemobs.config.TranslationConfig; +import com.magmaguy.elitemobs.config.menus.premade.SellMenuConfig; +import com.magmaguy.elitemobs.economy.EconomyHandler; +import com.magmaguy.elitemobs.items.ItemWorthCalculator; +import com.magmaguy.elitemobs.items.customenchantments.SoulbindEnchantment; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class SellMenu extends EliteMenu implements Listener { + + private static final List validSlots = SellMenuConfig.storeSlots; + + public static HashMap inventories = new HashMap<>(); + + private static double calculateShopValue(Inventory shopInventory, Player player) { + double itemWorth = 0; + for (Integer validSlot : validSlots) { + ItemStack itemStack = shopInventory.getItem(validSlot); + if (itemStack == null) continue; + itemWorth += (ItemWorthCalculator.determineResaleWorth(itemStack, player) * itemStack.getAmount()); + } + return itemWorth; + } + + private static ItemStack updateConfirmButton(double itemWorth) { + ItemStack clonedConfirmButton = SellMenuConfig.confirmButton.clone(); + + List lore = new ArrayList<>(); + for (String string : clonedConfirmButton.getItemMeta().getLore()) + lore.add(string + .replace("$currency_amount", itemWorth + "") + .replace("$currency_name", EconomySettingsConfig.getCurrencyName())); + + ItemMeta clonedMeta = clonedConfirmButton.getItemMeta(); + clonedMeta.setLore(lore); + clonedConfirmButton.setItemMeta(clonedMeta); + return clonedConfirmButton; + } + + private static void cancel(Inventory playerInventory, Inventory shopInventory) { + for (Integer validSlot : validSlots) { + ItemStack itemStack = shopInventory.getItem(validSlot); + if (itemStack != null) { + playerInventory.addItem(itemStack); + shopInventory.remove(itemStack); + } + } + } + + /** + * Creates a menu for selling elitemobs items. Only special Elite Mob items can be sold here. + * + * @param player Player for whom the inventory will be created + */ + public void constructSellMenu(Player player) { + + Inventory sellInventory = Bukkit.createInventory(player, 54, SellMenuConfig.shopName); + + for (int i = 0; i < 54; i++) { + + if (i == SellMenuConfig.infoSlot) { + sellInventory.setItem(i, SellMenuConfig.infoButton); + continue; + } + + if (i == SellMenuConfig.cancelSlot) { + sellInventory.setItem(i, SellMenuConfig.cancelButton); + continue; + } + + if (i == SellMenuConfig.confirmSlot) { + + ItemStack clonedConfirmButton = SellMenuConfig.confirmButton.clone(); + + List lore = new ArrayList<>(); + for (String string : SellMenuConfig.confirmButton.getItemMeta().getLore()) + lore.add(string + .replace("$currency_amount", 0 + "") + .replace("$currency_name", EconomySettingsConfig.getCurrencyName())); + SellMenuConfig.confirmButton.getItemMeta().setLore(lore); + ItemMeta clonedMeta = clonedConfirmButton.getItemMeta(); + clonedMeta.setLore(lore); + clonedConfirmButton.setItemMeta(clonedMeta); + sellInventory.setItem(i, clonedConfirmButton); + continue; + + } + + if (validSlots.contains(i)) + continue; + + sellInventory.setItem(i, ItemStackGenerator.generateItemStack(Material.GLASS_PANE)); + + } + + player.openInventory(sellInventory); + createEliteMenu(player, sellInventory, inventories); + + } + + @EventHandler + public void onInventoryClick(InventoryClickEvent event) { + + if (!isEliteMenu(event, inventories)) return; + event.setCancelled(true); + + Player player = (Player) event.getWhoClicked(); + ItemStack currentItem = event.getCurrentItem(); + Inventory shopInventory = event.getView().getTopInventory(); + Inventory playerInventory = event.getView().getBottomInventory(); + + if (isBottomMenu(event)) { + //CASE: If the player clicked on something in their inventory to put it on the shop + + //Check if it's an elitemobs item. The soulbind check only says if the player would be able to pick it up, and vanilla items can be picked up + if (!EliteMobsItemDetector.isEliteMobsItem(event.getCurrentItem())) { + event.getWhoClicked().sendMessage(ChatColorConverter.convert(TranslationConfig.getShopSaleInstructions())); + return; + } + + //If the item isn't soulbound to the player, it can't be sold by that player + if (!SoulbindEnchantment.isValidSoulbindUser(currentItem.getItemMeta(), player)) { + player.sendMessage(ChatColorConverter.convert(TranslationConfig.getShopSaleOthersItems())); + return; + } + + //If the shop is full, don't let the player put stuff in it + if (shopInventory.firstEmpty() == -1) return; + + //Do transfer + shopInventory.addItem(currentItem); + playerInventory.clear(event.getSlot()); + + //Update worth of things to be sold, now using cached prices + event.getInventory().setItem(SellMenuConfig.confirmSlot, updateConfirmButton(calculateShopValue(shopInventory, player))); + + } else { + //CASE: Player clicked on the shop + + //Signature item, does nothing + if (currentItem.equals(SellMenuConfig.infoButton)) + return; + + //sell items in shop + if (event.getSlot() == SellMenuConfig.confirmSlot) { + + int amount = (int) validSlots.stream().filter(validSlot -> shopInventory.getItem(validSlot) != null).count(); + double totalItemValue = 0; + + for (Integer validSlot : validSlots) { + ItemStack itemStack = shopInventory.getItem(validSlot); + if (itemStack == null) + continue; + double itemValue = ItemWorthCalculator.determineResaleWorth(itemStack, player) * itemStack.getAmount(); + EconomyHandler.addCurrency(player.getUniqueId(), itemValue); + totalItemValue += itemValue; + + if (amount < 4) + player.sendMessage(ChatColorConverter.convert( + TranslationConfig.getShopSellMessage() + .replace("$item_name", itemStack.getItemMeta().getDisplayName()) + .replace("$currency_amount", itemValue + "") + .replace("$currency_name", EconomySettingsConfig.getCurrencyName()))); + shopInventory.clear(validSlot); + } + + if (amount >= 3) + player.sendMessage(ChatColorConverter.convert( + TranslationConfig.getShopBatchSellMessage() + .replace("$currency_amount", totalItemValue + "") + .replace("$currency_name", EconomySettingsConfig.getCurrencyName()))); + + player.sendMessage(ChatColorConverter.convert( + TranslationConfig.getShopCurrentBalance() + .replace("$currency_amount", EconomyHandler.checkCurrency(player.getUniqueId()) + "") + .replace("$currency_name", EconomySettingsConfig.getCurrencyName()))); + updateConfirmButton(0); + return; + } + + //cancel, transfer items back to player inv and exit + if (event.getSlot() == SellMenuConfig.cancelSlot) { + cancel(playerInventory, shopInventory); + event.getWhoClicked().closeInventory(); + return; + } + + //If player clicks on a border glass pane, do nothing + if (!validSlots.contains(event.getSlot())) return; + + + //If player clicks on one of the items already in the shop, return to their inventory + playerInventory.addItem(event.getCurrentItem()); + shopInventory.clear(event.getSlot()); + + event.getInventory().setItem(SellMenuConfig.confirmSlot, updateConfirmButton(calculateShopValue(shopInventory, player))); + + } + } + + @EventHandler + public void onInventoryClose(InventoryCloseEvent event) { + if (!onInventoryClose(event, inventories)) return; + cancel(event.getView().getBottomInventory(), event.getView().getTopInventory()); + } + + @EventHandler + public void onPlayerQuit(PlayerQuitEvent event) { + onPlayerQuit(event, inventories); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/menus/SharedShopElements.java b/src/main/java/com/magmaguy/elitemobs/menus/SharedShopElements.java new file mode 100644 index 000000000..096db18fc --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/menus/SharedShopElements.java @@ -0,0 +1,91 @@ +package com.magmaguy.elitemobs.menus; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.config.EconomySettingsConfig; +import com.magmaguy.elitemobs.config.TranslationConfig; +import com.magmaguy.elitemobs.economy.EconomyHandler; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.scheduler.BukkitRunnable; + +public class SharedShopElements { + + public static boolean inventoryNullPointerPreventer(InventoryClickEvent event) { + return sellMenuNullPointPreventer(event); + } + + public static boolean sellMenuNullPointPreventer(InventoryClickEvent event) { + + //Check if current item is valid + if (event.getCurrentItem() == null) return false; + if (event.getCurrentItem().getType().equals(Material.AIR)) return false; + return event.getCurrentItem().getItemMeta() != null; + + } + + public static void buyMessage(Player player, String itemDisplayName, double itemValue) { + + new BukkitRunnable() { + + @Override + public void run() { + + player.sendMessage( + ChatColorConverter.convert( + TranslationConfig.getShopBuyMessage() + .replace("$item_name", itemDisplayName) + .replace("$item_value", itemValue + "") + .replace("$currency_name", EconomySettingsConfig.getCurrencyName()))); + + player.sendMessage( + ChatColorConverter.convert( + TranslationConfig.getShopCurrentBalance() + .replace("$currency_amount", EconomyHandler.checkCurrency(player.getUniqueId()) + "") + .replace("$currency_name", EconomySettingsConfig.getCurrencyName()))); + + + } + + + }.runTaskLater(Bukkit.getPluginManager().getPlugin(MetadataHandler.ELITE_MOBS), 2); + + } + + public static void insufficientFundsMessage(Player player, double itemValue) { + + new BukkitRunnable() { + + @Override + public void run() { + + player.sendMessage( + ChatColorConverter.convert( + TranslationConfig.getShopInsufficientFundsMessage() + .replace("$currency_name", EconomySettingsConfig.getCurrencyName()))); + + player.sendMessage( + ChatColorConverter.convert( + TranslationConfig.getShopCurrentBalance() + .replace("$currency_amount", EconomyHandler.checkCurrency(player.getUniqueId()) + "") + .replace("$currency_name", EconomySettingsConfig.getCurrencyName()))); + + player.sendMessage( + ChatColorConverter.convert( + TranslationConfig.getShopItemPrice() + .replace("$item_value", itemValue + "") + .replace("$currency_name", EconomySettingsConfig.getCurrencyName()))); + + } + + + }.runTaskLater(Bukkit.getPluginManager().getPlugin(MetadataHandler.ELITE_MOBS), 2); + + player.closeInventory(); + + } + + +} diff --git a/src/main/java/com/magmaguy/elitemobs/menus/SmeltMenu.java b/src/main/java/com/magmaguy/elitemobs/menus/SmeltMenu.java new file mode 100644 index 000000000..5e0f6470b --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/menus/SmeltMenu.java @@ -0,0 +1,217 @@ +package com.magmaguy.elitemobs.menus; + +import com.magmaguy.elitemobs.config.menus.premade.ScrapperMenuConfig; +import com.magmaguy.elitemobs.config.menus.premade.SmeltMenuConfig; +import com.magmaguy.elitemobs.items.ItemTagger; +import com.magmaguy.elitemobs.items.itemconstructor.ItemConstructor; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class SmeltMenu extends EliteMenu { + + private static final List inputSlots = SmeltMenuConfig.inputSlots; + private static final List outputSlots = SmeltMenuConfig.outputSlots; + private static final int informationInputSlot = SmeltMenuConfig.inputInformationSlot; + private static final int informationOutputSlot = SmeltMenuConfig.outputInformationSlot; + public static HashMap inventories = new HashMap<>(); + + private static ArrayList[] calculateOutput(ArrayList inputItemStacks, Player player) { + // itemStack[0] = inputArray , itemStack[1] = outputArray + ArrayList[] itemStacks = new ArrayList[2]; + itemStacks[0] = new ArrayList<>(); + itemStacks[1] = new ArrayList<>(); + HashMap inputScrapLevelAndAmountHashMap = new HashMap<>(); + + for (ItemStack itemStack : inputItemStacks) + if (itemStack != null) { + int scrapLevel = ItemTagger.getEnchantment(itemStack.getItemMeta(), "EliteScrap"); + if (scrapLevel >= 0) { + if (inputScrapLevelAndAmountHashMap.containsKey(scrapLevel)) + inputScrapLevelAndAmountHashMap.put(scrapLevel, inputScrapLevelAndAmountHashMap.get(scrapLevel) + itemStack.getAmount()); + else + inputScrapLevelAndAmountHashMap.put(scrapLevel, itemStack.getAmount()); + } else + itemStacks[0].add(itemStack); + } + + for (Integer scrapLevel : inputScrapLevelAndAmountHashMap.keySet()) { + int scrapAmount = inputScrapLevelAndAmountHashMap.get(scrapLevel); + int itemUpgradeOrbAmount = (int) Math.floor(scrapAmount / 25); + int scrapRemainderAmount = scrapAmount - itemUpgradeOrbAmount * 25; + + ItemStack scrapRemainderItem = ItemConstructor.constructScrapItem( + scrapLevel, player, false); + scrapRemainderItem.setAmount(scrapRemainderAmount); + itemStacks[0].add(scrapRemainderItem); + + ItemStack upgradeItem = ItemConstructor.constructUpgradeItem(scrapLevel, player, false); + upgradeItem.setAmount(itemUpgradeOrbAmount); + itemStacks[1].add(upgradeItem); + } + + return itemStacks; + } + + /** + * Creates a menu for scrapping elitemobs items. Only special Elite Mob items can be scrapped here. + * + * @param player Player for whom the inventory will be created + */ + public void constructSmeltMenu(Player player) { + Inventory smeltInventory = Bukkit.createInventory(player, 54, SmeltMenuConfig.shopName); + + for (int i = 0; i < 54; i++) { + + if (i == ScrapperMenuConfig.infoSlot) { + smeltInventory.setItem(i, SmeltMenuConfig.infoButton); + continue; + } + + if (i == ScrapperMenuConfig.cancelSlot) { + smeltInventory.setItem(i, SmeltMenuConfig.cancelButton); + continue; + } + + if (i == informationInputSlot) { + smeltInventory.setItem(i, SmeltMenuConfig.inputInfoButton); + continue; + } + + if (i == informationOutputSlot) { + smeltInventory.setItem(i, SmeltMenuConfig.outputInfoButton); + continue; + } + + + if (i == ScrapperMenuConfig.confirmSlot) { + + ItemStack clonedConfirmButton = SmeltMenuConfig.confirmButton.clone(); + + List lore = new ArrayList<>(); + for (String string : SmeltMenuConfig.confirmButton.getItemMeta().getLore()) + lore.add(string); + SmeltMenuConfig.confirmButton.getItemMeta().setLore(lore); + ItemMeta clonedMeta = clonedConfirmButton.getItemMeta(); + clonedMeta.setLore(lore); + clonedConfirmButton.setItemMeta(clonedMeta); + smeltInventory.setItem(i, clonedConfirmButton); + continue; + + } + + if (inputSlots.contains(i) || outputSlots.contains(i)) + continue; + + smeltInventory.setItem(i, ItemStackGenerator.generateItemStack(Material.GLASS_PANE)); + + } + + player.openInventory(smeltInventory); + createEliteMenu(player, smeltInventory, inventories); + } + + public static class SmeltMenuEvents implements Listener { + @EventHandler + public void onInventoryInteract(InventoryClickEvent event) { + + if (!isEliteMenu(event, inventories)) return; + event.setCancelled(true); + + Player player = (Player) event.getWhoClicked(); + ItemStack currentItem = event.getCurrentItem(); + Inventory smeltInventory = event.getView().getTopInventory(); + Inventory playerInventory = event.getView().getBottomInventory(); + + if (isBottomMenu(event)) { + if (!ItemTagger.hasEnchantment(currentItem.getItemMeta(), "EliteScrap")) return; + boolean inputIsFull = true; + for (int slot : inputSlots) { + if (smeltInventory.getItem(slot) == null) { + smeltInventory.setItem(slot, currentItem); + playerInventory.remove(currentItem); + inputIsFull = false; + break; + } + } + + if (inputIsFull) return; + + ArrayList inputItemStacks = new ArrayList<>(); + for (int slot : inputSlots) + inputItemStacks.add(smeltInventory.getItem(slot)); + ArrayList[] output = calculateOutput(inputItemStacks, player); + for (int i = 0; i < outputSlots.size(); i++) + if (output[1].size() > i) + smeltInventory.setItem(outputSlots.get(i), output[1].get(i)); + else + smeltInventory.setItem(outputSlots.get(i), null); + + } else if (isTopMenu(event)) { + + if (event.getSlot() == SmeltMenuConfig.cancelSlot) { + player.closeInventory(); + return; + } + + if (event.getSlot() == SmeltMenuConfig.confirmSlot) { + ArrayList inputItemStacks = new ArrayList<>(); + for (int slot : inputSlots) + inputItemStacks.add(smeltInventory.getItem(slot)); + + ArrayList[] output = calculateOutput(inputItemStacks, player); + + for (ItemStack itemStack : output[0]) + player.getInventory().addItem(itemStack); + for (int slot : inputSlots) + smeltInventory.setItem(slot, null); + + for (ItemStack itemStack : output[1]) + player.getInventory().addItem(itemStack); + for (int slot : outputSlots) + smeltInventory.setItem(slot, null); + + return; + } + + if (currentItem == null) return; + if (currentItem.getType().equals(Material.AIR)) return; + if (currentItem.getAmount() == 0) return; + if (inputSlots.contains(event.getSlot())) { + playerInventory.addItem(currentItem); + smeltInventory.remove(currentItem); + ArrayList inputItemStacks = new ArrayList<>(); + for (int slot : inputSlots) + inputItemStacks.add(smeltInventory.getItem(slot)); + ArrayList[] output = calculateOutput(inputItemStacks, player); + for (int i = 0; i < outputSlots.size(); i++) + if (output[1].size() > i) + smeltInventory.setItem(outputSlots.get(i), output[1].get(i)); + else + smeltInventory.setItem(outputSlots.get(i), null); + } + } + + } + + @EventHandler + public void onInventoryClose(InventoryCloseEvent event) { + if (!EliteMenu.onInventoryClose(event, inventories)) return; + EliteMenu.cancel(event.getView().getTopInventory(), event.getView().getBottomInventory(), SmeltMenu.inputSlots); + } + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/menus/UnbindMenu.java b/src/main/java/com/magmaguy/elitemobs/menus/UnbindMenu.java new file mode 100644 index 000000000..11c7d19be --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/menus/UnbindMenu.java @@ -0,0 +1,177 @@ +package com.magmaguy.elitemobs.menus; + +import com.magmaguy.elitemobs.api.EliteMobsItemDetector; +import com.magmaguy.elitemobs.config.menus.premade.UnbinderMenuConfig; +import com.magmaguy.elitemobs.items.ItemTagger; +import com.magmaguy.elitemobs.items.customenchantments.UnbindEnchantment; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.Damageable; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; + +public class UnbindMenu extends EliteMenu { + private static final int eliteItemInputSlot = UnbinderMenuConfig.getEliteItemInputSlot(); + private static final int scrapItemInputSlot = UnbinderMenuConfig.getEliteUnbindInputSlot(); + private static final int outputSlot = UnbinderMenuConfig.getOutputSlot(); + private static final int eliteItemInformationInputSlot = UnbinderMenuConfig.getEliteItemInputInformationSlot(); + private static final int eliteScrapInformationInputSlot = UnbinderMenuConfig.getEliteScrapInputInformationSlot(); + private static final int informationOutputSlot = UnbinderMenuConfig.getOutputInformationSlot(); + public static HashMap inventories = new HashMap<>(); + + private static void calculateOutput(Inventory UnbinderInventory) { + if (UnbinderInventory.getItem(UnbinderMenuConfig.getEliteUnbindInputSlot()) == null || UnbinderInventory.getItem(UnbinderMenuConfig.getEliteItemInputSlot()) == null) { + UnbinderInventory.setItem(UnbinderMenuConfig.getOutputSlot(), null); + return; + } + ItemStack outputItem = UnbinderInventory.getItem(UnbinderMenuConfig.getEliteItemInputSlot()).clone(); + UnbinderInventory.setItem(outputSlot, UnbindEnchantment.unbindItem(outputItem)); + } + + /** + * Creates a menu for scrapping elitemobs items. Only special Elite Mob items can be scrapped here. + * + * @param player Player for whom the inventory will be created + */ + public void constructUnbinderMenu(Player player) { + Inventory UnbinderInventory = Bukkit.createInventory(player, 54, UnbinderMenuConfig.getShopName()); + + for (int i = 0; i < UnbinderInventory.getSize(); i++) { + + if (i == UnbinderMenuConfig.getInfoSlot()) { + UnbinderInventory.setItem(i, UnbinderMenuConfig.getInfoButton()); + continue; + } + + if (i == UnbinderMenuConfig.getCancelSlot()) { + UnbinderInventory.setItem(i, UnbinderMenuConfig.getCancelButton()); + continue; + } + + if (i == eliteItemInformationInputSlot) { + UnbinderInventory.setItem(i, UnbinderMenuConfig.getEliteItemInputInfoButton()); + continue; + } + + if (i == eliteScrapInformationInputSlot) { + UnbinderInventory.setItem(i, UnbinderMenuConfig.getEliteUnbindInputInfoButton()); + continue; + } + + if (i == informationOutputSlot) { + UnbinderInventory.setItem(i, UnbinderMenuConfig.getOutputInfoButton()); + continue; + } + + + if (i == UnbinderMenuConfig.getConfirmSlot()) { + + ItemStack clonedConfirmButton = UnbinderMenuConfig.getConfirmButton().clone(); + + List lore = new ArrayList<>(); + for (String string : UnbinderMenuConfig.getConfirmButton().getItemMeta().getLore()) + lore.add(string); + UnbinderMenuConfig.getConfirmButton().getItemMeta().setLore(lore); + ItemMeta clonedMeta = clonedConfirmButton.getItemMeta(); + clonedMeta.setLore(lore); + clonedConfirmButton.setItemMeta(clonedMeta); + UnbinderInventory.setItem(i, clonedConfirmButton); + continue; + + } + + + if (i == UnbinderMenuConfig.getEliteItemInputSlot() || i == UnbinderMenuConfig.getEliteUnbindInputSlot() || i == UnbinderMenuConfig.getOutputSlot()) + continue; + UnbinderInventory.setItem(i, ItemStackGenerator.generateItemStack(Material.GLASS_PANE)); + + } + + player.openInventory(UnbinderInventory); + createEliteMenu(player, UnbinderInventory, inventories); + } + + public static class UnbinderMenuEvents implements Listener { + @EventHandler + public void onInteract(InventoryClickEvent event) { + if (!isEliteMenu(event, inventories)) return; + event.setCancelled(true); + + Player player = (Player) event.getWhoClicked(); + ItemStack currentItem = event.getCurrentItem(); + int clickedSlot = event.getSlot(); + Inventory unbinderInventory = event.getView().getTopInventory(); + Inventory playerInventory = event.getView().getBottomInventory(); + + if (isBottomMenu(event)) { + //Item is unbind scroll + if (ItemTagger.hasEnchantment(currentItem.getItemMeta(), UnbindEnchantment.key)) { + if (unbinderInventory.getItem(scrapItemInputSlot) == null) { + unbinderInventory.setItem(scrapItemInputSlot, currentItem); + playerInventory.clear(clickedSlot); + calculateOutput(unbinderInventory); + } + return; + } + + //Item is elite item + if (EliteMobsItemDetector.isEliteMobsItem(currentItem)) + if (currentItem.getItemMeta() instanceof Damageable) + if (unbinderInventory.getItem(eliteItemInputSlot) == null) { + unbinderInventory.setItem(eliteItemInputSlot, currentItem); + playerInventory.remove(currentItem); + calculateOutput(unbinderInventory); + } + + } else if (isTopMenu(event)) { + + //return item to inventory + if (event.getSlot() == scrapItemInputSlot || event.getSlot() == eliteItemInputSlot) { + playerInventory.addItem(currentItem); + unbinderInventory.remove(currentItem); + calculateOutput(unbinderInventory); + return; + } + + //cancel button + if (event.getSlot() == UnbinderMenuConfig.getCancelSlot()) { + player.closeInventory(); + return; + } + + //confirm button + if (event.getSlot() == UnbinderMenuConfig.getConfirmSlot()) { + if (unbinderInventory.getItem(outputSlot) != null) { + unbinderInventory.setItem(UnbinderMenuConfig.getEliteItemInputSlot(), null); + unbinderInventory.setItem(UnbinderMenuConfig.getEliteUnbindInputSlot(), null); + playerInventory.addItem(unbinderInventory.getItem(outputSlot)); + unbinderInventory.remove(unbinderInventory.getItem(outputSlot)); + unbinderInventory.setItem(outputSlot, null); + } + } + + } + + } + + @EventHandler + public void onInventoryClose(InventoryCloseEvent event) { + if (!EliteMenu.onInventoryClose(event, inventories)) return; + EliteMenu.cancel(event.getView().getTopInventory(), event.getView().getBottomInventory(), Arrays.asList(eliteItemInputSlot, scrapItemInputSlot)); + } + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/ActionBossMobEntity.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/ActionBossMobEntity.java deleted file mode 100644 index 34545dcc3..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/ActionBossMobEntity.java +++ /dev/null @@ -1,22 +0,0 @@ -package com.magmaguy.elitemobs.mobconstructor; - -import com.magmaguy.elitemobs.mobpowers.ElitePower; -import org.bukkit.Location; -import org.bukkit.entity.EntityType; - -import java.util.HashSet; - -public class ActionBossMobEntity extends BossMobEntity { - - /* - These bosses can be removed when a chunk unloads - */ - public ActionBossMobEntity(EntityType entityType, Location location, int eliteMobLevel, String name) { - super(entityType, location, eliteMobLevel, name); - } - - public ActionBossMobEntity(EntityType entityType, Location location, int eliteMobsLevel, String name, HashSet elitePowers) { - super(entityType, location, eliteMobsLevel, name, elitePowers); - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/BossMobEntity.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/BossMobEntity.java deleted file mode 100644 index 5f53ec0f7..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/BossMobEntity.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.magmaguy.elitemobs.mobconstructor; - -import com.magmaguy.elitemobs.events.mobs.sharedeventproperties.BossMobDeathCountdown; -import com.magmaguy.elitemobs.mobpowers.ElitePower; -import org.bukkit.Location; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.LivingEntity; - -import java.util.HashSet; - -public class BossMobEntity extends EliteMobEntity { - - public BossMobEntity(EntityType entityType, Location location, int eliteMobLevel, String name) { - - super(entityType, location, eliteMobLevel, name); - setupBossMob(super.getLivingEntity()); - - } - - public BossMobEntity(EntityType entityType, Location location, int eliteMobLevel, String name, HashSet elitePowers) { - - super(entityType, location, eliteMobLevel, name); - setupBossMob(super.getLivingEntity(), elitePowers); - - } - - private void setupBossMob(LivingEntity livingEntity) { - - super.setHasNormalLoot(true); - BossMobDeathCountdown.startDeathCountdown(livingEntity); - - } - - private void setupBossMob(LivingEntity livingEntity, HashSet elitePowers) { - - setupBossMob(livingEntity); - super.setCustomPowers(elitePowers); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/CombatSystem.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/CombatSystem.java deleted file mode 100644 index 399524491..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/CombatSystem.java +++ /dev/null @@ -1,379 +0,0 @@ -package com.magmaguy.elitemobs.mobconstructor; - -import com.magmaguy.elitemobs.EntityTracker; -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.collateralminecraftchanges.PlayerDeathMessageByEliteMob; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; -import com.magmaguy.elitemobs.items.ItemTierFinder; -import com.magmaguy.elitemobs.items.MobTierFinder; -import com.magmaguy.elitemobs.items.ObfuscatedSignatureLoreData; -import com.magmaguy.elitemobs.items.itemconstructor.LoreGenerator; -import com.magmaguy.elitemobs.utils.EntityFinder; -import org.bukkit.Material; -import org.bukkit.attribute.Attribute; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.entity.*; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.block.Action; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.event.entity.EntityDamageEvent; -import org.bukkit.event.entity.ExplosionPrimeEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.inventory.ItemStack; -import org.bukkit.potion.PotionEffect; -import org.bukkit.scheduler.BukkitRunnable; - -import java.util.HashMap; - -public class CombatSystem implements Listener { - - public static final double PER_LEVEL_POWER_INCREASE = 0.1; - public static final double TARGET_HITS_TO_KILL = ConfigValues.mobCombatSettingsConfig.getDouble(MobCombatSettingsConfig.TARGET_HITS_TO_KILL); - public static final double BASE_DAMAGE_DEALT_TO_PLAYERS = ConfigValues.mobCombatSettingsConfig.getDouble(MobCombatSettingsConfig.BASE_DAMAGE_DEALT_TO_PLAYER); - public static final double TO_PLAYER_DAMAGE_TIER_HANDICAP = 0.75; - public static final double TO_ELITE_DAMAGE_TIER_HANDICAP = 0.33; - - public static final double DIAMOND_TIER_LEVEL = 3; - public static final double IRON_TIER_LEVEL = 2; - public static final double STONE_CHAIN_TIER_LEVEL = 1; - public static final double GOLD_WOOD_LEATHER_TIER_LEVEL = 0; - - //TODO: Handle thorns damage and potion effects - - //this event deals with elite mobs damaging players - @EventHandler(priority = EventPriority.HIGHEST) - public void eliteMobDamageHandler(EntityDamageByEntityEvent event) { - - if (event.isCancelled()) return; - if (!(event.getEntity() instanceof Player)) return; - - LivingEntity damager = EntityFinder.getRealDamager(event); - if (damager == null) return; - - if (!EntityTracker.isEliteMob(event.getDamager())) - return; - - EliteMobEntity eliteMobEntity = EntityTracker.getEliteMobEntity(damager); - if (eliteMobEntity == null) return; - - //From this point on, the damage event is fully altered by Elite Mobs - - //Get rid of all vanilla armor reduction - for (EntityDamageEvent.DamageModifier modifier : EntityDamageEvent.DamageModifier.values()) - if (event.isApplicable(modifier)) - event.setDamage(modifier, 0); - - Player player = (Player) event.getEntity(); - - //Determine tiers - double eliteTier = MobTierFinder.findMobTier(eliteMobEntity); - double playerTier = ItemTierFinder.findArmorSetTier(player); - - double newDamage = eliteToPlayerDamageFormula(eliteTier, playerTier, player, event); - - //Prevent untouchable armor and 1-shots - - if (newDamage < 1) newDamage = 1; - if (newDamage > 19) newDamage = 19; - - //Set the final damage value - event.setDamage(EntityDamageEvent.DamageModifier.BASE, newDamage); - - //Deal with the player getting killed - if (player.getHealth() - event.getDamage() <= 0) - PlayerDeathMessageByEliteMob.addDeadPlayer(player, PlayerDeathMessageByEliteMob.intializeDeathMessage(player, damager)); - - } - - private double eliteToPlayerDamageFormula(double eliteTier, double playerTier, Player player, EntityDamageByEntityEvent event) { - - double tierDifference = eliteTier - playerTier; - tierDifference = (Math.abs(tierDifference) < 2) ? tierDifference : tierDifference > 0 ? 2 : -2; - - /* - Apply secondary enchantment damage reduction - */ - double newBaseDamage = BASE_DAMAGE_DEALT_TO_PLAYERS - secondaryEnchantmentDamageReduction(player, event) * 2; - - return newBaseDamage + - newBaseDamage * (tierDifference) * TO_PLAYER_DAMAGE_TIER_HANDICAP; - - } - - private double secondaryEnchantmentDamageReduction(Player player, EntityDamageByEntityEvent event) { - - double totalReductionLevel = 0; - - for (ItemStack itemStack : player.getInventory().getArmorContents()) { - - if (itemStack == null) continue; - - for (Enchantment enchantment : itemStack.getEnchantments().keySet()) { - - if (enchantment.getName().equals(Enchantment.PROTECTION_PROJECTILE.getName()) && event.getDamager() instanceof Projectile) - totalReductionLevel += getDamageIncreasePercentage(enchantment, itemStack); - - - if (enchantment.getName().equals(Enchantment.PROTECTION_EXPLOSIONS.getName()) && event.getCause().equals(EntityDamageByEntityEvent.DamageCause.ENTITY_EXPLOSION)) - totalReductionLevel += getDamageIncreasePercentage(enchantment, itemStack); - - - } - - } - - totalReductionLevel = totalReductionLevel / 4; - totalReductionLevel = totalReductionLevel > 1 ? 1 : totalReductionLevel; - - return totalReductionLevel; - - } - - /* - Deal with elite creeper explosions (visually) - Damage is dealt by eliteMobDamageHandler - */ - @EventHandler(priority = EventPriority.HIGHEST) - public void onEliteCreeperDetonation(ExplosionPrimeEvent event) { - - if (event.isCancelled()) return; - if (!(event.getEntity() instanceof Creeper && EntityTracker.isEliteMob(event.getEntity()))) - return; - - /* - This is necessary because the propagate the same duration as they have, which is nearly infinite - */ - for (PotionEffect potionEffect : ((Creeper) event.getEntity()).getActivePotionEffects()) - ((Creeper) event.getEntity()).removePotionEffect(potionEffect.getType()); - - EliteMobEntity eliteMobEntity = EntityTracker.getEliteMobEntity(event.getEntity()); - - int mobLevel = eliteMobEntity.getLevel() < 1 ? 1 : eliteMobEntity.getLevel(); - - float newExplosionRange = (float) (event.getRadius() + Math.ceil(0.01 * mobLevel * event.getRadius() * - ConfigValues.mobCombatSettingsConfig.getDouble(MobCombatSettingsConfig.ELITE_CREEPER_EXPLOSION_MULTIPLIER))); - - if (newExplosionRange > 20) - newExplosionRange = 20; - - - event.setRadius(newExplosionRange); - - } - - /* - Elite Mobs have purely cosmetic armor. It doesn't do any actual damage reduction, as that would seriously complicate - the underlying math for dealing damage for no real reason. - */ - - /* - This deals with elite mobs being damaged by non-player entities - */ - @EventHandler(priority = EventPriority.HIGHEST) - public void eliteMobDamageGeneric(EntityDamageEvent event) { - - if (event.isCancelled()) return; - if (!(event.getEntity() instanceof LivingEntity)) return; - if (!EntityTracker.isEliteMob(event.getEntity())) return; - if (event.getCause().equals(EntityDamageEvent.DamageCause.ENTITY_ATTACK)) return; - if (!event.getCause().equals(EntityDamageEvent.DamageCause.CUSTOM)) - event.setDamage(EntityDamageEvent.DamageModifier.BASE, event.getDamage()); - - } - - /* - This deals with players hitting the elite mob - */ - @EventHandler(priority = EventPriority.HIGHEST) - public void eliteMobDamageByPlayer(EntityDamageByEntityEvent event) { - - if (event.isCancelled()) return; - LivingEntity damager = EntityFinder.getRealDamager(event); - if (damager == null) return; - - EliteMobEntity eliteMobEntity = EntityTracker.getEliteMobEntity(event.getEntity()); - if (eliteMobEntity == null) return; - - //From this point on, the event damage is handled by Elite Mobs - - /* - Case in which the player is not the entity dealing damage, just deal raw damage - */ - if (!damager.getType().equals(EntityType.PLAYER) && EntityTracker.isEliteMob(damager)) { - - event.setDamage(event.getDamage()); - return; - - } - - for (EntityDamageEvent.DamageModifier modifier : EntityDamageEvent.DamageModifier.values()) - if (event.isApplicable(modifier)) - event.setDamage(modifier, 0); - - /* - Case in which a player has hit the Elite Mob - */ - - if (!damager.getType().equals(EntityType.PLAYER)) return; - Player player = (Player) damager; - - double playerTier; - if (player.getInventory().getItemInMainHand() == null || player.getInventory().getItemInMainHand().getType().equals(Material.BOW) && event.getDamager() instanceof Player) - playerTier = 0; - else - playerTier = ItemTierFinder.findBattleTier(player.getInventory().getItemInMainHand()); - double eliteTier = MobTierFinder.findMobTier(eliteMobEntity); - double maxHealth = eliteMobEntity.getMaxHealth(); - - double newDamage = playerToEliteDamageFormula(eliteTier, playerTier, maxHealth, player, eliteMobEntity.getLivingEntity()); - - event.setDamage(EntityDamageEvent.DamageModifier.BASE, newDamage); - - } - - private double playerToEliteDamageFormula(double eliteTier, double playerTier, double maxHealth, Player player, LivingEntity eliteMob) { - - double tierDifference = playerTier - eliteTier; - - /* - This caps the tier difference between mobs and players to prevent insurmountable boss fights - */ - tierDifference = Math.abs(tierDifference) > 2.5 ? (tierDifference > 0 ? 2.5 : -2.5) : tierDifference; - - /* - This applies secondary enchantments, that is, it applies enchantments that only affect specific mob types - such as smite which only works with undead mobs - */ - double bonusSecondaryEnchantmentDamage = 3 * secondaryEnchantmentDamageIncrease(player.getInventory().getItemInMainHand(), eliteMob); - double newTargetHitsToKill = TARGET_HITS_TO_KILL - bonusSecondaryEnchantmentDamage; - - double finalDamage = getCooledAttackStrength(player) * (maxHealth / newTargetHitsToKill + - maxHealth / newTargetHitsToKill * (tierDifference) * TO_ELITE_DAMAGE_TIER_HANDICAP); - - /* - Make sure that players are dealing at least 1 damage as to not create unkillable bosses - */ - return finalDamage < 1 ? 1 : finalDamage; - - } - - /* - This deals with cooldown damage reduction based on the default cooldown property of minecraft and a custom - cooldown penalty on top of it (just linear) - */ - private float getCooledAttackStrength(Player player) { - - if (!playerHitCooldownHashMap.containsKey(player)) return 1; - - float swingDelay = clock - playerHitCooldownHashMap.get(player); - float cooldownPeriod = getCooldownPeriod(player); - - if (swingDelay > cooldownPeriod) return 1; - - return swingDelay / cooldownPeriod; - - } - - /* - This part is pretty much a copy of how Minecraft does the cooldown check - */ - private float getCooldownPeriod(Player player) { - return (float) (1.0D / player.getAttribute(Attribute.GENERIC_ATTACK_SPEED).getValue() * 20.0D); - } - - private static int clock = 0; - - public static void launchInternalClock() { - - new BukkitRunnable() { - - @Override - public void run() { - - if (clock == Integer.MAX_VALUE) clock = 0; - clock++; - - } - - }.runTaskTimer(MetadataHandler.PLUGIN, 1, 1); - - } - - - /* - This deals with damage increases specific to specific mob types - It returns a percentage where 0 is no relevant enchantment present and 1 is maximum potential level reached for - relevant enchantment - */ - private double secondaryEnchantmentDamageIncrease(ItemStack weapon, LivingEntity eliteMob) { - - if (ObfuscatedSignatureLoreData.obfuscatedSignatureDetector(weapon)) { - String deobfuscatedString = weapon.getItemMeta().getLore().get(0).replace("§", ""); - if (deobfuscatedString.contains(LoreGenerator.OBFUSCATED_ENCHANTMENTS)) { - if (eliteMob instanceof Spider || eliteMob instanceof Silverfish) - return getDamageIncreasePercentage(Enchantment.DAMAGE_ARTHROPODS, findObfuscatedMainEnchantment(deobfuscatedString, Enchantment.DAMAGE_ARTHROPODS)); - - if (eliteMob instanceof Zombie || eliteMob instanceof Skeleton) - return getDamageIncreasePercentage(Enchantment.DAMAGE_ARTHROPODS, findObfuscatedMainEnchantment(deobfuscatedString, Enchantment.DAMAGE_UNDEAD)); - } - } - - for (Enchantment enchantment : weapon.getEnchantments().keySet()) { - - if (enchantment.getName().equals(Enchantment.DAMAGE_ARTHROPODS.getName()) && (eliteMob instanceof Spider || eliteMob instanceof Silverfish)) - return getDamageIncreasePercentage(enchantment, weapon); - - if (enchantment.getName().equals(Enchantment.DAMAGE_UNDEAD.getName()) && (eliteMob instanceof Zombie || eliteMob instanceof Skeleton)) - return getDamageIncreasePercentage(enchantment, weapon); - - } - - return 0; - - } - - private static int findObfuscatedMainEnchantment(String deobfuscatedLore, Enchantment enchantment) { - for (String string : deobfuscatedLore.split(",")) - if (string.contains(enchantment.getName())) - return Integer.parseInt(string.split(":")[1]); - - return 0; - } - - private double getDamageIncreasePercentage(Enchantment enchantment, ItemStack weapon) { - - double maxEnchantmentLevel = getMaxEnchantmentLevel(enchantment); - double currentEnchantmentLevel = weapon.getEnchantmentLevel(enchantment); - - return currentEnchantmentLevel / maxEnchantmentLevel <= 1 ? currentEnchantmentLevel / maxEnchantmentLevel : 1; - - } - - private double getDamageIncreasePercentage(Enchantment enchantment, double level) { - - double maxEnchantmentLevel = getMaxEnchantmentLevel(enchantment); - - return level / maxEnchantmentLevel <= 1 ? level / maxEnchantmentLevel : 1; - - } - - private int getMaxEnchantmentLevel(Enchantment enchantment) { - return ConfigValues.itemsProceduralSettingsConfig.getInt("Valid Enchantments." + enchantment.getName() + ".Max Level"); - } - - private HashMap playerHitCooldownHashMap = new HashMap<>(); - - @EventHandler(priority = EventPriority.MONITOR) - public void onPlayerInteract(PlayerInteractEvent event) { - - if (!(event.getAction().equals(Action.LEFT_CLICK_AIR) || event.getAction().equals(Action.LEFT_CLICK_BLOCK) || - event.getAction().equals(Action.PHYSICAL))) return; - - playerHitCooldownHashMap.put(event.getPlayer(), clock); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/CustomSpawn.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/CustomSpawn.java new file mode 100644 index 000000000..5e79e4690 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/CustomSpawn.java @@ -0,0 +1,337 @@ +package com.magmaguy.elitemobs.mobconstructor; + +import com.magmaguy.elitemobs.EliteMobs; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.adventurersguild.GuildRank; +import com.magmaguy.elitemobs.config.ValidWorldsConfig; +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfig; +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import com.magmaguy.elitemobs.config.customspawns.CustomSpawnConfig; +import com.magmaguy.elitemobs.config.customspawns.CustomSpawnConfigFields; +import com.magmaguy.elitemobs.events.MoonPhaseDetector; +import com.magmaguy.elitemobs.events.TimedEvent; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import com.magmaguy.elitemobs.playerdata.database.PlayerData; +import com.magmaguy.elitemobs.thirdparty.worldguard.WorldGuardFlagChecker; +import com.magmaguy.elitemobs.utils.DebugMessage; +import com.magmaguy.elitemobs.utils.VersionChecker; +import com.magmaguy.elitemobs.utils.WarningMessage; +import lombok.Getter; +import lombok.Setter; +import org.bukkit.*; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.ThreadLocalRandom; + +public class CustomSpawn { + + @Getter + private final CustomSpawnConfigFields customSpawnConfigFields; + @Getter + private final ArrayList customBossEntities = new ArrayList<>(); + @Getter + @Setter + private boolean isEvent = false; + @Getter + @Setter + private World world; + private TimedEvent timedEvent; + private int allTries = 0; + @Getter + @Setter + private Location spawnLocation; + @Setter + private boolean keepTrying = true; + + /** + * Used by the TimedEvent system to find valid locations + */ + public CustomSpawn(String customSpawnConfig, List customBossesFilenames, TimedEvent timedEvent) { + this.customSpawnConfigFields = CustomSpawnConfig.getCustomEvent(customSpawnConfig); + this.timedEvent = timedEvent; + + if (customSpawnConfigFields == null) { + new WarningMessage("Invalid custom spawn detected for file " + customSpawnConfig + " in event " + timedEvent.getCustomEventsConfigFields().getFilename()); + return; + } + + customBossesFilenames.forEach(bossString -> { + CustomBossesConfigFields customBossesConfigFields = CustomBossesConfig.getCustomBoss(bossString); + if (customBossesConfigFields == null) { + new WarningMessage("Attempted to pass invalid boss into CustomSpawn: " + bossString); + return; + } + CustomBossEntity customBossEntity = new CustomBossEntity(customBossesConfigFields); + customBossEntities.add(customBossEntity); + customBossEntity.setCustomSpawn(this); + }); + } + + public CustomSpawn(String customSpawnConfig, CustomBossEntity customBossEntity) { + this.customSpawnConfigFields = CustomSpawnConfig.getCustomEvent(customSpawnConfig); + if (customSpawnConfigFields == null) { + new WarningMessage("Invalid custom spawn detected for file " + customSpawnConfig); + return; + } + customBossEntities.add(customBossEntity); + } + + public static int getHighestValidBlock(Location location, int highestYLevel) { + int height = location.getBlockY() - 1; + //todo: when the Minecraft max height goes over 256 (and under 0) this will need to get reviewed + while (height < 256) { + height++; + if (height > highestYLevel) + return -1; + Location floorLocation = new Location(location.getWorld(), location.getX(), height - 1, location.getZ()); + if (floorLocation.getBlock().isPassable()) + continue; + Location tempLocation = new Location(location.getWorld(), location.getX(), height, location.getZ()); + if (!tempLocation.getBlock().getType().isAir()) + continue; + Location locationAbove = new Location(location.getWorld(), location.getX(), height + 1, location.getZ()); + if (!locationAbove.getBlock().getType().isAir()) + continue; + return height; + } + return -100; + } + + public void queueSpawn() { + //Make sure a location exists + if (spawnLocation == null) + new BukkitRunnable() { + @Override + public void run() { + generateCustomSpawn(); + } + }.runTaskAsynchronously(MetadataHandler.PLUGIN); + else + spawn(); + + } + + private void spawn() { + //Pass back to sync if it's in async + new BukkitRunnable() { + @Override + public void run() { + + if (!keepTrying) cancel(); + + if (Objects.requireNonNull(spawnLocation.getWorld()).getTime() < customSpawnConfigFields.getEarliestTime() || + spawnLocation.getWorld().getTime() > customSpawnConfigFields.getLatestTime()) + return; + + if (customSpawnConfigFields.getMoonPhase() != null) + if (!MoonPhaseDetector.detectMoonPhase(spawnLocation.getWorld()).equals(customSpawnConfigFields.getMoonPhase())) + return; + + for (CustomBossEntity customBossEntity : customBossEntities) + if (!customBossEntity.exists()) + customBossEntity.spawn(spawnLocation, isEvent); + + cancel(); + + if (timedEvent != null) + timedEvent.queueEvent(); + + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + } + + private void generateCustomSpawn() { + int maxTries = 100; + int tries = 0; + while (tries < maxTries && spawnLocation == null) { + if (!keepTrying) + return; + tries++; + allTries++; + this.spawnLocation = generateRandomSpawnLocation(); + if (spawnLocation != null) + break; + } + + if (spawnLocation == null) { + if (keepTrying) { + new BukkitRunnable() { + @Override + public void run() { + generateCustomSpawn(); + if (timedEvent != null) + new DebugMessage("Failed to spawn " + timedEvent.getCustomEventsConfigFields().getFilename() + " after " + allTries + " tries. Will try again in 1 minute."); + } + }.runTaskLaterAsynchronously(MetadataHandler.PLUGIN, 20 * 60); + } else { + customBossEntities.forEach((customBossEntity -> { + if (customBossEntity.summoningEntity != null) + customBossEntity.summoningEntity.removeReinforcement(customBossEntity); + })); + } + } else { + if (isEvent) + new DebugMessage("Spawned bosses for event after " + allTries + " tries"); + spawn(); + } + } + + public Location generateRandomSpawnLocation() { + if (customSpawnConfigFields == null) { + new WarningMessage("Something tried to spawn but has invalid custom spawn config fields! This isn't good.", true); + new WarningMessage("Bosses: "); + getCustomBossEntities().forEach((customBossEntity) -> { + if (customBossEntity != null) + if (customBossEntity.getName() != null) + new WarningMessage(customBossEntity.getCustomBossesConfigFields().getName()); + }); + if (timedEvent != null) { + new WarningMessage("Event: " + timedEvent.getCustomEventsConfigFields().getFilename()); + timedEvent.end(); + } + return null; + } + + //If there are no players online, don't spawn anything - this condition shouldn't be reachable in the first place + if (Bukkit.getOnlinePlayers().isEmpty()) { + keepTrying = false; + if (timedEvent != null) + timedEvent.end(); + return null; + } + + //Go through online players and select the ones in valid worlds + List validPlayers = new ArrayList<>(); + if (world == null) + for (Player player : Bukkit.getOnlinePlayers()) { + if (!PlayerData.isInMemory(player.getUniqueId())) continue; + Location playerLocation = player.getLocation(); + if (!ValidWorldsConfig.getValidWorlds().contains(playerLocation.getWorld().getName())) + continue; + if (!playerLocation.getWorld().getGameRuleValue(GameRule.DO_MOB_SPAWNING)) continue; + if (!customSpawnConfigFields.getValidWorlds().isEmpty()) + if (!customSpawnConfigFields.getValidWorlds().contains(playerLocation.getWorld())) + continue; + if (!customSpawnConfigFields.getValidWorldEnvironments().isEmpty()) + if (!customSpawnConfigFields.getValidWorldEnvironments().contains(Objects.requireNonNull(playerLocation.getWorld()).getEnvironment())) + continue; + if (GuildRank.getActiveGuildRank(player) == 0) continue; + validPlayers.add(player); + } + else + validPlayers.addAll(world.getPlayers()); + + //If there are no players in valid worlds, skip + if (validPlayers.isEmpty()) + return null; + + //Select a random player + Player selectedPlayer = validPlayers.get(ThreadLocalRandom.current().nextInt(validPlayers.size())); + + //Randomize vector between 24 and 128 block away from a source location + Vector randomizedVector = new Vector(ThreadLocalRandom.current().nextInt(24, 128), + 0, //this doesn't really matter, it likely gets modified later + ThreadLocalRandom.current().nextInt(24, 128)); + + //Allow negative X and Z values + if (ThreadLocalRandom.current().nextBoolean()) + randomizedVector.setX(randomizedVector.getX() * -1); + if (ThreadLocalRandom.current().nextBoolean()) + randomizedVector.setY(randomizedVector.getY() * -1); + + //Temp location - do not run checks on it yet + Location location = selectedPlayer.getLocation().clone().add(randomizedVector); + //This doesn't matter too much since it will be parsed later, also these values are already tweaked for 1.18. + if (VersionChecker.serverVersionOlderThan(18, 1)) + location.setY(ThreadLocalRandom.current().nextInt(-0, 256)); + else + location.setY(ThreadLocalRandom.current().nextInt(-64, 256)); + World world = location.getWorld(); + + if (!customSpawnConfigFields.getValidBiomes().isEmpty() && !customSpawnConfigFields.getValidBiomes().contains(location.getBlock().getBiome())) + return null; + + //Set Y level - Location isn't final yet + if (customSpawnConfigFields.isSurfaceSpawn()) + //this won't work for Nether environments, but who wants surface spawns on the Nether? + location = Objects.requireNonNull(location.getWorld()).getHighestBlockAt(location).getLocation().add(new Vector(0.5, 1, 0.5)); + else if (customSpawnConfigFields.isUndergroundSpawn()) { + int highestBlockYAt = Objects.requireNonNull(location.getWorld()).getHighestBlockYAt(location); + //Let's hope there's caves + if (location.getY() > highestBlockYAt || + location.getY() > highestBlockYAt / 2D) { + for (int y = (int) location.getY(); y > -64; y--) { + Location tempLocation = location.clone(); + tempLocation.setY(y); + if (location.getBlock().getType().equals(Material.VOID_AIR)) return null; + if (y < customSpawnConfigFields.getLowestYLevel()) return null; + Block groundBlock = location.clone().subtract(new Vector(0, 1, 0)).getBlock(); + if (!groundBlock.getType().isSolid()) continue; + //Check temp location block + if (!tempLocation.getBlock().getType().isAir()) continue; + //Check block above temp location + if (!tempLocation.add(new Vector(0, 1, 0)).getBlock().getType().isAir()) continue; + location = tempLocation; + break; + } + } else { + for (int y = (int) location.getY(); y < highestBlockYAt; y++) { + Location tempLocation = location.clone(); + tempLocation.setY(y); + if (location.getBlock().getType().equals(Material.VOID_AIR)) return null; + if (y < customSpawnConfigFields.getLowestYLevel()) return null; + Block groundBlock = location.clone().subtract(new Vector(0, 1, 0)).getBlock(); + if (!groundBlock.getType().isSolid()) continue; + //Check temp location block + if (!tempLocation.getBlock().getType().isAir()) continue; + //Check block above temp location + if (!tempLocation.add(new Vector(0, 1, 0)).getBlock().getType().isAir()) continue; + location = tempLocation; + break; + } + } + } else + //Straight upwards check + location.setY(getHighestValidBlock(location, getHighestValidBlock(location, customSpawnConfigFields.getHighestYLevel()))); + + //Prevent spawning right on top of players + assert world != null; + for (Player player : world.getPlayers()) + if (player.getLocation().distanceSquared(location) < Math.pow(24, 2)) + return null; + + //Nether ceiling check + if (location.getY() > 127 && world.getEnvironment().equals(World.Environment.NETHER)) + return null; + + //Custom height check + if (location.getY() == -100 || location.getY() > customSpawnConfigFields.getHighestYLevel() || location.getY() < customSpawnConfigFields.getLowestYLevel()) + return null; + + //Check WorldGuard flags + if (EliteMobs.worldGuardIsEnabled) { + if (!WorldGuardFlagChecker.doEventFlag(location)) + return null; + + if (!WorldGuardFlagChecker.doEliteMobsSpawnFlag(location)) + return null; + + if (!WorldGuardFlagChecker.doMobSpawnFlag(location)) + return null; + } + + //Light level check - following 1.18 rules + if (!customSpawnConfigFields.isCanSpawnInLight()) + if (location.getBlock().getLightLevel() > 8) + return null; + + return location; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/EliteEntity.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/EliteEntity.java new file mode 100644 index 000000000..3e6b81ecd --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/EliteEntity.java @@ -0,0 +1,676 @@ +package com.magmaguy.elitemobs.mobconstructor; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobHealEvent; +import com.magmaguy.elitemobs.api.internal.RemovalReason; +import com.magmaguy.elitemobs.collateralminecraftchanges.KeepNeutralsAngry; +import com.magmaguy.elitemobs.combatsystem.CombatSystem; +import com.magmaguy.elitemobs.combatsystem.antiexploit.AntiExploitMessage; +import com.magmaguy.elitemobs.config.AntiExploitConfig; +import com.magmaguy.elitemobs.config.DefaultConfig; +import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.events.CustomEvent; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs.EliteMobProperties; +import com.magmaguy.elitemobs.powers.meta.ElitePower; +import com.magmaguy.elitemobs.powers.meta.MajorPower; +import com.magmaguy.elitemobs.powers.meta.MinorPower; +import com.magmaguy.elitemobs.powerstances.MajorPowerPowerStance; +import com.magmaguy.elitemobs.powerstances.MinorPowerPowerStance; +import com.magmaguy.elitemobs.tagger.PersistentTagger; +import com.magmaguy.elitemobs.utils.EventCaller; +import com.magmaguy.elitemobs.utils.VersionChecker; +import com.magmaguy.elitemobs.utils.WarningMessage; +import lombok.Getter; +import lombok.Setter; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.attribute.Attribute; +import org.bukkit.entity.*; +import org.bukkit.event.entity.CreatureSpawnEvent; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.*; +import java.util.concurrent.ThreadLocalRandom; + +public class EliteEntity implements SimplePersistentEntityInterface { + + protected final HashMap damagers = new HashMap<>(); + protected final UUID eliteUUID = UUID.randomUUID(); + /* + Store all powers in one set, makes no sense to access it in individual sets. + The reason they are split up in the first place is to add them in a certain ratio + Once added, they can just be stored in a pool + */ + @Getter + protected HashSet elitePowers = new HashSet<>(); + //coming soon - decoupling aggro from damage to allow for tanking mechanics + protected HashMap aggro = new HashMap<>(); + /* + Note that a lot of values here are defined by EliteMobProperties.java + */ + protected LivingEntity livingEntity; + //LivingEntity gets removed as soon as it dies, unsyncedLivingEntity only ever overwrites when a new living entity is created. + protected LivingEntity unsyncedLivingEntity; + @Getter + @Setter + protected int level; + @Getter + protected double maxHealth; + @Getter + protected String name; + @Getter + protected int minorPowerCount = 0; + @Getter + protected int majorPowerCount = 0; + @Getter + @Setter + protected boolean minorVisualEffect = false; + @Getter + @Setter + protected boolean majorVisualEffect = false; + @Getter + @Setter + protected boolean visualEffectObfuscated = true; + @Getter + protected boolean isNaturalEntity; + protected EntityType entityType; + @Getter + protected Boolean isPersistent = false; + @Getter + @Setter + protected boolean vanillaLoot = true; + @Getter + @Setter + protected boolean eliteLoot = true; + @Getter + @Setter + protected boolean randomLoot = true; + @Getter + protected CreatureSpawnEvent.SpawnReason spawnReason; + @Getter + @Setter + protected double healthMultiplier = 1.0; + @Getter + @Setter + protected double damageMultiplier = 1.0; + protected double defaultMaxHealth; + @Getter + @Setter + protected boolean inCooldown = false; + @Getter + protected boolean triggeredAntiExploit = false; + protected int antiExploitPoints = 0; + @Getter + protected boolean inAntiExploitCooldown = false; + @Getter + @Setter + protected boolean inCombat = false; + @Getter + protected boolean inCombatGracePeriod = false; + @Setter + protected EliteEntity summoningEntity; + protected List globalReinforcementEntities = new ArrayList<>(); + protected List eliteReinforcementEntities = new ArrayList<>(); + //currently used to store ender crystals for the dragon boss fight + protected List nonEliteReinforcementEntities = new ArrayList<>(); + protected boolean bypassesProtections = false; + private double health; + @Getter + @Setter + private boolean dying = false; + @Getter + @Setter + private boolean healing = false; + + /** + * Functions as a placeholder for {@link CustomBossEntity} that haven't been initialized yet. Uses the builder pattern + * in order to further initialize values at an arbitrary point in the future. + *

+ * Uses: + * - {@link CustomEvent} queueing through the {@link CustomSpawn} system + *

+ * {@link EliteEntity} constructed this way must at some point correctly invoke {@link CustomBossEntity#setSpawnLocation(Location)} + * for the spawn method. + */ + public EliteEntity() { + } + + /** + * This is the generic constructor used in most instances of natural elite mob generation + */ + public EliteEntity(LivingEntity livingEntity, + int level, + CreatureSpawnEvent.SpawnReason spawnReason) { + setLevel(level); + setLivingEntity(livingEntity, spawnReason); + //Get correct instance of plugin data, necessary for settings names and health among other things + EliteMobProperties eliteMobProperties = EliteMobProperties.getPluginData(livingEntity); + setName(eliteMobProperties); + setArmor(); + setMaxHealth(); + randomizePowers(eliteMobProperties); + } + + public boolean getBypassesProtections() { + return bypassesProtections; + } + + public void setBypassesProtections(boolean bypassesProtections) { + this.bypassesProtections = bypassesProtections; + } + + /** + * Elite UUID. This UUID is guaranteed to be final for the Elite Entity, and is not in sync with the {@link LivingEntity} {@link UUID} . + *

+ * Noteworthy uses: {@link EliteEntity} will survive chunk reloads, and in the case of {@link com.magmaguy.elitemobs.mobconstructor.custombosses.RegionalBossEntity} will survive deaths for the entirety of runtime. + * + * @return The final UUID value of this {@link EliteEntity} + */ + public UUID getEliteUUID() { + return eliteUUID; + } + + public void addDamager(Player player, double damage) { + if (!damagers.isEmpty()) + for (Player iteratedPlayer : damagers.keySet()) + if (iteratedPlayer.getUniqueId().equals(player.getUniqueId())) { + this.damagers.put(iteratedPlayer, this.damagers.get(iteratedPlayer) + damage); + return; + } + this.damagers.put(player, damage); + } + + public void addDamagers(Map newDamagers) { + this.damagers.putAll(newDamagers); + } + + public boolean hasDamagers() { + return !damagers.isEmpty(); + } + + public Map getDamagers() { + return damagers; + } + + public boolean isCustomBossEntity() { + return this instanceof CustomBossEntity; + } + + /** + * Returns the {@link LivingEntity} currently being used by the {@link EliteEntity}. Returns null if none is currently active, even + * if one was active previously. + * + * @return Currently active {@link LivingEntity} + * @see EliteEntity#getUnsyncedLivingEntity() if you want a version that does get nulled once the {@link LivingEntity} stops being valid + */ + public LivingEntity getLivingEntity() { + return livingEntity; + } + + /** + * This {@link LivingEntity} represents the previous entity spawned by EliteMobs. It is only overwritten when a new one + * is generated, whereas {@link EliteEntity#getLivingEntity()} returns null as soon as the {@link LivingEntity} stops being alive + * for safety reasons. + *

+ * This is the method used when operations need to be run on dead instances, such as in {@link com.magmaguy.elitemobs.api.EliteMobDeathEvent}. + * + * @return The latest {@link LivingEntity} generated for this {@link EliteEntity} + */ + public LivingEntity getUnsyncedLivingEntity() { + return unsyncedLivingEntity; + } + + public void setLivingEntity(LivingEntity livingEntity, CreatureSpawnEvent.SpawnReason spawnReason) { + if (livingEntity == null) return; + this.livingEntity = livingEntity; + this.unsyncedLivingEntity = livingEntity; + this.entityType = livingEntity.getType(); + + this.livingEntity.setCanPickupItems(false); + livingEntity.getEquipment().setItemInMainHandDropChance(0); + livingEntity.getEquipment().setItemInOffHandDropChance(0); + livingEntity.getEquipment().setHelmetDropChance(0); + livingEntity.getEquipment().setChestplateDropChance(0); + livingEntity.getEquipment().setLeggingsDropChance(0); + livingEntity.getEquipment().setBootsDropChance(0); + + if (livingEntity.getType().equals(EntityType.RABBIT)) { + ((Rabbit) livingEntity).setRabbitType(Rabbit.Type.THE_KILLER_BUNNY); + } + + if (entityType.equals(EntityType.WOLF)) { + Wolf wolf = (Wolf) livingEntity; + wolf.setAngry(true); + wolf.setBreed(false); + KeepNeutralsAngry.showMeYouWarFace(this); + } + + if (entityType.equals(EntityType.POLAR_BEAR)) { + KeepNeutralsAngry.showMeYouWarFace(this); + } + + if (entityType.equals(EntityType.ENDER_DRAGON)) + Objects.requireNonNull(((EnderDragon) livingEntity).getBossBar()).setTitle(getName()); + + if (entityType.equals(EntityType.LLAMA)) { + KeepNeutralsAngry.showMeYouWarFace(this); + } + + if (!VersionChecker.serverVersionOlderThan(17, 0) && entityType.equals(EntityType.GOAT)) { + ((Goat) livingEntity).setScreaming(true); + } + + if (!VersionChecker.serverVersionOlderThan(15, 0) && livingEntity instanceof Bee) { + KeepNeutralsAngry.showMeYouWarFace(this); + ((Bee) livingEntity).setCannotEnterHiveTicks(Integer.MAX_VALUE); + } + this.spawnReason = spawnReason; + + //This sets whether the entity gets despawned when beyond a certain distance from the player, should only happen + //for entities which aren't pseudo-persistent + this.getLivingEntity().setRemoveWhenFarAway(!isPersistent); + this.getLivingEntity().setPersistent(false); + + setMaxHealth(); + + if (getName() == null) + setName(EliteMobProperties.getPluginData(entityType)); + + this.name = livingEntity.getCustomName(); + + PersistentTagger.tagElite(livingEntity, eliteUUID); + EntityTracker.registerEliteMob(this); + } + + public void setNameVisible(boolean isVisible) { + //Check if the boss is already dead + if (livingEntity == null) return; + livingEntity.setCustomNameVisible(isVisible); + } + + private void setMaxHealth() { + this.defaultMaxHealth = EliteMobProperties.getPluginData(this.getLivingEntity().getType()).getDefaultMaxHealth(); + this.maxHealth = (level * CombatSystem.TARGET_HITS_TO_KILL + this.defaultMaxHealth) * healthMultiplier; + livingEntity.getAttribute(Attribute.GENERIC_MAX_HEALTH).setBaseValue(maxHealth); + livingEntity.setHealth(maxHealth); + this.health = maxHealth; + } + + public void setNormalizedMaxHealth() { + this.defaultMaxHealth = MobCombatSettingsConfig.getNormalizedBaselineHealth(); + this.maxHealth = (level * CombatSystem.TARGET_HITS_TO_KILL + this.defaultMaxHealth) * healthMultiplier; + livingEntity.getAttribute(Attribute.GENERIC_MAX_HEALTH).setBaseValue(maxHealth); + livingEntity.setHealth(maxHealth); + this.health = maxHealth; + } + + public void resetMaxHealth() { + livingEntity.getAttribute(Attribute.GENERIC_MAX_HEALTH).setBaseValue(maxHealth); + livingEntity.setHealth(maxHealth); + this.health = maxHealth; + } + + /** + * Health is cached by EliteMobs for when health needs to be displayed when the {@link LivingEntity} isn't valid, but + * return the field from the {@link LivingEntity} when available + * + * @return Boss health + */ + public double getHealth() { + if (livingEntity != null) + return livingEntity.getHealth(); + else + return this.health; + } + + public void setHealth(double health) { + if (livingEntity == null) return; + this.health = Math.min(health, this.maxHealth); + livingEntity.setHealth(this.health); + } + + public void syncPluginHealth(double health) { + this.health = health; + } + + public void heal(double healAmount) { + EliteMobHealEvent eliteMobHealEvent = new EliteMobHealEvent(this, healAmount); + new EventCaller(eliteMobHealEvent); + if (eliteMobHealEvent.isCancelled()) return; + setHealth(health + healAmount); + } + + public double damage(double damage) { + health = Math.max(0, livingEntity.getHealth() - damage); + livingEntity.setHealth(health); + return damage; + } + + public void fullHeal() { + EliteMobHealEvent eliteMobHealEvent = new EliteMobHealEvent(this, true); + new EventCaller(eliteMobHealEvent); + if (eliteMobHealEvent.isCancelled()) return; + setHealth(this.maxHealth); + this.health = maxHealth; + damagers.clear(); + } + + public void combatEnd() { + } + + private void setArmor() { + if (!MobCombatSettingsConfig.isDoEliteArmor()) return; + + if (!(livingEntity instanceof Zombie || livingEntity instanceof PigZombie || + livingEntity instanceof Skeleton || livingEntity instanceof WitherSkeleton)) return; + + livingEntity.getEquipment().setBoots(new ItemStack(Material.AIR)); + livingEntity.getEquipment().setLeggings(new ItemStack(Material.AIR)); + livingEntity.getEquipment().setChestplate(new ItemStack(Material.AIR)); + livingEntity.getEquipment().setHelmet(new ItemStack(Material.AIR)); + + if (level >= 5 && MobCombatSettingsConfig.isDoEliteHelmets()) + livingEntity.getEquipment().setHelmet(new ItemStack(Material.LEATHER_HELMET)); + + if (level >= 10) livingEntity.getEquipment().setBoots(new ItemStack(Material.LEATHER_BOOTS)); + if (level >= 15) livingEntity.getEquipment().setLeggings(new ItemStack(Material.LEATHER_LEGGINGS)); + if (level >= 20) livingEntity.getEquipment().setChestplate(new ItemStack(Material.LEATHER_CHESTPLATE)); + if (level >= 25 && MobCombatSettingsConfig.isDoEliteHelmets()) + livingEntity.getEquipment().setHelmet(new ItemStack(Material.CHAINMAIL_HELMET)); + if (level >= 30) livingEntity.getEquipment().setBoots(new ItemStack(Material.CHAINMAIL_BOOTS)); + if (level >= 35) livingEntity.getEquipment().setLeggings(new ItemStack(Material.CHAINMAIL_LEGGINGS)); + if (level >= 40) livingEntity.getEquipment().setChestplate(new ItemStack(Material.CHAINMAIL_CHESTPLATE)); + if (level >= 45 && MobCombatSettingsConfig.isDoEliteHelmets()) + livingEntity.getEquipment().setHelmet(new ItemStack(Material.IRON_HELMET)); + if (level >= 50) livingEntity.getEquipment().setBoots(new ItemStack(Material.IRON_BOOTS)); + if (level >= 55) livingEntity.getEquipment().setLeggings(new ItemStack(Material.IRON_LEGGINGS)); + if (level >= 60) livingEntity.getEquipment().setChestplate(new ItemStack(Material.IRON_CHESTPLATE)); + if (level >= 65) livingEntity.getEquipment().setBoots(new ItemStack(Material.DIAMOND_BOOTS)); + if (level >= 70 && MobCombatSettingsConfig.isDoEliteHelmets()) + livingEntity.getEquipment().setHelmet(new ItemStack(Material.DIAMOND_HELMET)); + if (level >= 75) livingEntity.getEquipment().setLeggings(new ItemStack(Material.DIAMOND_LEGGINGS)); + if (level >= 80) livingEntity.getEquipment().setChestplate(new ItemStack(Material.DIAMOND_CHESTPLATE)); + + if (livingEntity.getEquipment().getHelmet() != null) { + ItemMeta helmetMeta = livingEntity.getEquipment().getHelmet().getItemMeta(); + if (helmetMeta != null) { + helmetMeta.setUnbreakable(true); + livingEntity.getEquipment().getHelmet().setItemMeta(helmetMeta); + } + } + } + + public void randomizePowers(EliteMobProperties eliteMobProperties) { + + if (level < 1) return; + + int availableDefensivePowers = 0; + int availableOffensivePowers = 0; + int availableMiscellaneousPowers = 0; + int availableMajorPowers = 0; + + if (level >= 10) availableDefensivePowers = 1; + if (level >= 20) availableOffensivePowers = 1; + if (level >= 30) availableMiscellaneousPowers = 1; + if (level >= 40) availableMajorPowers = 1; + if (level >= 50) availableDefensivePowers = 2; + if (level >= 60) availableOffensivePowers = 2; + if (level >= 70) availableMiscellaneousPowers = 2; + if (level >= 80) availableMajorPowers = 2; + + //apply defensive powers + applyPowers((HashSet) eliteMobProperties.getValidDefensivePowers().clone(), availableDefensivePowers); + + //apply offensive powers + applyPowers((HashSet) eliteMobProperties.getValidOffensivePowers().clone(), availableOffensivePowers); + + //apply miscellaneous powers + applyPowers((HashSet) eliteMobProperties.getValidMiscellaneousPowers().clone(), availableMiscellaneousPowers); + + //apply major powers + applyPowers((HashSet) eliteMobProperties.getValidMajorPowers().clone(), availableMajorPowers); + + new MinorPowerPowerStance(this); + new MajorPowerPowerStance(this); + + } + + public void applyPowers(HashSet elitePowers, int availablePowerAmount) { + elitePowers.removeIf(elitePower -> !PowersConfig.getPower(elitePower.getFileName()).isEnabled()); + + if (availablePowerAmount < 1) return; + + ArrayList localPowers = new ArrayList<>(elitePowers); + + for (ElitePower mobPower : this.elitePowers) + localPowers.remove(mobPower); + + for (int i = 0; i < availablePowerAmount; i++) + if (localPowers.size() < 1) + break; + else { + ElitePower selectedPower = localPowers.get(ThreadLocalRandom.current().nextInt(localPowers.size())); + try { + this.elitePowers.add(selectedPower.getClass().newInstance()); + selectedPower.applyPowers(this.livingEntity); + localPowers.remove(selectedPower); + if (selectedPower instanceof MajorPower) + this.majorPowerCount++; + if (selectedPower instanceof MinorPower) + this.minorPowerCount++; + } catch (Exception ex) { + new WarningMessage("Failed to instance new power!"); + } + } + + } + + public void applyPowers(HashSet elitePowers) { + this.elitePowers = elitePowers; + for (ElitePower elitePower : elitePowers) + elitePower.applyPowers(livingEntity); + } + + public boolean hasPower(ElitePower mobPower) { + for (ElitePower elitePower : elitePowers) + if (elitePower.getClass().equals(mobPower.getClass())) + return true; + return false; + } + + public boolean hasPower(PowersConfigFields powersConfigFields) { + for (ElitePower elitePower : elitePowers) + if (elitePower.getPowersConfigFields().equals(powersConfigFields)) + return true; + return false; + } + + public ElitePower getPower(PowersConfigFields powersConfigFields) { + for (ElitePower elitePower : elitePowers) + if (elitePower.getPowersConfigFields().equals(powersConfigFields)) + return elitePower; + return null; + } + + public ElitePower getPower(ElitePower elitePower) { + for (ElitePower iteratedPower : getElitePowers()) + if (iteratedPower.getClass().equals(elitePower.getClass())) + return iteratedPower; + return null; + } + + public ElitePower getPower(String elitePower) { + for (ElitePower iteratedPower : getElitePowers()) + if (iteratedPower.getFileName().equals(elitePower)) + return iteratedPower; + return null; + } + + public void setName(EliteMobProperties eliteMobProperties) { + this.name = ChatColorConverter.convert( + eliteMobProperties.getName().replace( + "$level", level + "")); + livingEntity.setCustomName(this.name); + livingEntity.setCustomNameVisible(DefaultConfig.isAlwaysShowNametags()); + } + + public void setName(String name, boolean applyToLivingEntity) { + this.name = name; + //This is necessary for the custom boss mega consumer + if (applyToLivingEntity) + livingEntity.setCustomName(name); + } + + public void setPersistent(boolean bool) { + this.isPersistent = bool; + if (livingEntity != null) + livingEntity.setRemoveWhenFarAway(!isPersistent); + } + + public void doCooldown() { + setInCooldown(true); + new BukkitRunnable() { + @Override + public void run() { + setInCooldown(false); + } + }.runTaskLater(MetadataHandler.PLUGIN, 20 * 15); + } + + public void doGlobalPowerCooldown(int ticks) { + setInCooldown(true); + new BukkitRunnable() { + @Override + public void run() { + setInCooldown(false); + } + }.runTaskLater(MetadataHandler.PLUGIN, ticks); + } + + public void setTriggeredAntiExploit(boolean triggeredAntiExploit) { + this.triggeredAntiExploit = triggeredAntiExploit; + if (triggeredAntiExploit) { + this.eliteLoot = false; + this.vanillaLoot = false; + } + } + + public void incrementAntiExploit(int value, String cause) { + antiExploitPoints += value; + if (antiExploitPoints > AntiExploitConfig.getAntiExploitThreshold()) { + setTriggeredAntiExploit(true); + AntiExploitMessage.sendWarning(livingEntity, cause); + } + } + + public void decrementAntiExploit(int value) { + antiExploitPoints -= value; + } + + public void setInAntiExploitCooldown() { + this.inAntiExploitCooldown = true; + new BukkitRunnable() { + @Override + public void run() { + inAntiExploitCooldown = false; + } + }.runTaskLater(MetadataHandler.PLUGIN, 20); + } + + public void setCombatGracePeriod(int delayInTicks) { + this.inCombatGracePeriod = true; + new BukkitRunnable() { + @Override + public void run() { + inCombatGracePeriod = false; + } + }.runTaskLater(MetadataHandler.PLUGIN, delayInTicks); + } + + public void addGlobalReinforcement(CustomBossEntity customBossEntity) { + this.globalReinforcementEntities.add(customBossEntity); + } + + public void addReinforcement(CustomBossEntity customBossEntity) { + this.eliteReinforcementEntities.add(customBossEntity); + } + + public void addReinforcement(Entity entity) { + this.nonEliteReinforcementEntities.add(entity); + } + + /** + * Returns true if the {@link LivingEntity} is exists and loaded. + * + * @return Whether the EliteEntity is currently valid. + */ + public boolean isValid() { + if (livingEntity == null) return false; + return livingEntity.isValid(); + } + + public boolean exists() { + if (livingEntity == null) return false; + return !livingEntity.isDead(); + } + + public Location getLocation() { + if (livingEntity != null) return livingEntity.getLocation(); + if (unsyncedLivingEntity != null) return unsyncedLivingEntity.getLocation(); + return null; + } + + public void remove(RemovalReason removalReason) { + //This prevents the entity tracker from running this code twice when removing due to specific reasons + //Custom bosses have their own tracking removal rules + if (livingEntity != null && (!(this instanceof CustomBossEntity))) + EntityTracker.getEliteMobEntities().remove(eliteUUID); + if (livingEntity != null && !removalReason.equals(RemovalReason.DEATH)) + livingEntity.remove(); + if (livingEntity instanceof EnderDragon && removalReason.equals(RemovalReason.DEATH)) { + ((EnderDragon) livingEntity).setPhase(EnderDragon.Phase.DYING); + Objects.requireNonNull(((EnderDragon) livingEntity).getDragonBattle()).generateEndPortal(false); + } + this.livingEntity = null; + } + + public void removeReinforcement(CustomBossEntity customBossEntity) { + eliteReinforcementEntities.remove(customBossEntity); + } + + public int getGlobalReinforcementsCount() { + return this.globalReinforcementEntities.size(); + } + + /** + * This method is implemented by the {@link SimplePersistentEntityInterface} to conform to the pattern but is only ever used in overrides by extended classes. + */ + @Override + public void chunkLoad() { + remove(RemovalReason.CHUNK_UNLOAD); + } + + /** + * Chunk unloading always removes Elite Entities as if they are Custom Bosses they have their own handler with an override. + */ + @Override + public void chunkUnload() { + remove(RemovalReason.CHUNK_UNLOAD); + } + + @Override + public void worldLoad() { + } + + @Override + public void worldUnload() { + remove(RemovalReason.WORLD_UNLOAD); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/EliteMobConstructor.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/EliteMobConstructor.java deleted file mode 100644 index 18b8caaa6..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/EliteMobConstructor.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.magmaguy.elitemobs.mobconstructor; - -import com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs.EliteMobProperties; -import org.bukkit.Bukkit; -import org.bukkit.entity.LivingEntity; - -public class EliteMobConstructor { - - /* - This class assumes that the entity has already been filtered and validated before being invoked - */ - public static EliteMobEntity constructEliteMob(LivingEntity livingEntity, int mobLevel) { - - if (!EliteMobProperties.isValidEliteMobType(livingEntity)) { - Bukkit.getLogger().warning("[EliteMobs] Attempted to construct an invalid Elite Mob. Report this to the dev!"); - Bukkit.getLogger().warning("[EliteMobs] Elite Mob type: " + livingEntity.getType()); - return null; - } - - return new EliteMobEntity(livingEntity, mobLevel); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/EliteMobEntity.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/EliteMobEntity.java deleted file mode 100644 index 38de3d31f..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/EliteMobEntity.java +++ /dev/null @@ -1,603 +0,0 @@ -package com.magmaguy.elitemobs.mobconstructor; - -import com.magmaguy.elitemobs.ChatColorConverter; -import com.magmaguy.elitemobs.EntityTracker; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.DefaultConfig; -import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; -import com.magmaguy.elitemobs.items.MobTierFinder; -import com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs.EliteMobProperties; -import com.magmaguy.elitemobs.mobpowers.ElitePower; -import com.magmaguy.elitemobs.mobpowers.majorpowers.MajorPower; -import com.magmaguy.elitemobs.mobpowers.minorpowers.MinorPower; -import com.magmaguy.elitemobs.mobspawning.NaturalMobSpawnEventHandler; -import com.magmaguy.elitemobs.powerstances.MajorPowerPowerStance; -import com.magmaguy.elitemobs.powerstances.MinorPowerPowerStance; -import com.magmaguy.elitemobs.utils.VersionChecker; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.attribute.Attribute; -import org.bukkit.entity.*; -import org.bukkit.inventory.ItemStack; - -import java.util.ArrayList; -import java.util.HashSet; -import java.util.concurrent.ThreadLocalRandom; - -public class EliteMobEntity { - - /* - Note that a lot of values here are defined by EliteMobProperties.java - */ - private LivingEntity eliteMob; - private int eliteMobLevel; - private double eliteMobTier; - private double maxHealth; - private String name; - /* - Store all powers in one set, makes no sense to access it in individual sets. - The reason they are split up in the first place is to add them in a certain ratio - Once added, they can just be stored in a pool - */ - private HashSet powers = new HashSet<>(); - private int minorPowerCount = 0; - private int majorPowerCount = 0; - private boolean hasMinorVisualEffect = false; - private boolean hasMajorVisualEffect = false; - private boolean hasVisualEffectObfuscated = true; - private boolean isNaturalEntity; - /* - This just defines default behavior - */ - private boolean hasStacking = true; - private boolean hasCustomArmor = false; - private boolean hasCustomName = false; - private boolean hasCustomPowers = false; - private boolean hasFarAwayUnload = true; - private boolean hasCustomHealth = false; - private boolean hasNormalLoot = true; - - /** - * This is the generic constructor used in most instances of natural elite mob generation - * - * @param livingEntity Minecraft entity associated to this elite mob - * @param eliteMobLevel Level of the mob, can be modified during runtime. Dynamically assigned. - */ - public EliteMobEntity(LivingEntity livingEntity, int eliteMobLevel) { - - /* - Register living entity to keep track of which entity this object is tied to - */ - this.eliteMob = livingEntity; - /* - Register level, this is variable as per stacking rules - */ - setEliteMobLevel(eliteMobLevel); - eliteMobTier = MobTierFinder.findMobTier(eliteMobLevel); - /* - Get correct instance of plugin data, necessary for settings names and health among other things - */ - EliteMobProperties eliteMobProperties = EliteMobProperties.getPluginData(livingEntity); - /* - Handle name, variable as per stacking rules - */ - setCustomName(eliteMobProperties); - /* - Handle health, max is variable as per stacking rules - Currently #setHealth() resets the health back to maximum - */ - setMaxHealth(eliteMobProperties); - setHealth(); - /* - Set the armor - */ - setArmor(); - /* - Register whether or not the elite mob is natural - */ - this.isNaturalEntity = EntityTracker.isNaturalEntity(livingEntity); - /* - Set the power list - */ - randomizePowers(eliteMobProperties); - /* - Start tracking the entity - */ - EntityTracker.registerEliteMob(this); - - eliteMob.setCanPickupItems(false); - - } - - /** - * This is the generic constructor used in most instances of natural elite mob generation - * - * @param livingEntity Minecraft entity associated to this elite mob - * @param eliteMobLevel Level of the mob, can be modified during runtime. Dynamically assigned. - */ - public EliteMobEntity(LivingEntity livingEntity, int eliteMobLevel, double currentHealthPercent) { - - /* - Register living entity to keep track of which entity this object is tied to - */ - this.eliteMob = livingEntity; - /* - Register level, this is variable as per stacking rules - */ - setEliteMobLevel(eliteMobLevel); - eliteMobTier = MobTierFinder.findMobTier(eliteMobLevel); - /* - Get correct instance of plugin data, necessary for settings names and health among other things - */ - EliteMobProperties eliteMobProperties = EliteMobProperties.getPluginData(livingEntity); - /* - Handle name, variable as per stacking rules - */ - setCustomName(eliteMobProperties); - /* - Handle health, max is variable as per stacking rules - Currently #setHealth() resets the health back to maximum - */ - setMaxHealth(eliteMobProperties); - setHealth(); - /* - Set the armor - */ - setArmor(); - /* - Register whether or not the elite mob is natural - */ - this.isNaturalEntity = EntityTracker.isNaturalEntity(livingEntity); - /* - Set the power list - */ - randomizePowers(eliteMobProperties); - /* - Start tracking the entity - */ - EntityTracker.registerEliteMob(this); - - eliteMob.setCanPickupItems(false); - - } - - - /** - * Spawning method for boss mobs. - * Assumes custom powers and custom names. - * - * @param livingEntity the living entity associated to the mob - * @param eliteMobLevel boss mob level, should be automatically generated based on the highest player tier online - * @param name the name for this boss mob, overrides the usual elite mob name format - * @see BossMobEntity - */ - public EliteMobEntity(EntityType entityType, Location location, int eliteMobLevel, String name) { - - /* - Register living entity to keep track of which entity this object is tied to - */ - this.eliteMob = spawnBossMobLivingEntity(entityType, location); - /* - Register level, this is variable as per stacking rules - */ - setEliteMobLevel(eliteMobLevel); - eliteMobTier = MobTierFinder.findMobTier(eliteMobLevel); - /* - Get correct instance of plugin data, necessary for settings names and health among other things - */ - EliteMobProperties eliteMobProperties = EliteMobProperties.getPluginData(entityType); - /* - Handle name, variable as per stacking rules - */ - setCustomName(name); - /* - Handle health, max is variable as per stacking rules - Currently #setHealth() resets the health back to maximum - */ - setMaxHealth(eliteMobProperties); - setHealth(); - /* - Register whether or not the elite mob is natural - */ - this.isNaturalEntity = EntityTracker.isNaturalEntity(this.eliteMob); - /* - These have custom powers - */ - this.hasCustomPowers = true; - /* - Start tracking the entity - */ - EntityTracker.registerEliteMob(this); - - if (ConfigValues.defaultConfig.getBoolean(DefaultConfig.PREVENT_ITEM_PICKUP)) - eliteMob.setCanPickupItems(false); - - this.setHasStacking(false); - this.setHasCustomArmor(true); - - } - - /* - This is the generic constructor for elite mobs spawned via commands - */ - public EliteMobEntity(EntityType entityType, Location location, int eliteMobLevel, HashSet mobPowers) { - - /* - Register living entity to keep track of which entity this object is tied to - */ - this.eliteMob = spawnBossMobLivingEntity(entityType, location); - /* - Register level, this is variable as per stacking rules - */ - setEliteMobLevel(eliteMobLevel); - eliteMobTier = MobTierFinder.findMobTier(eliteMobLevel); - /* - Get correct instance of plugin data, necessary for settings names and health among other things - */ - EliteMobProperties eliteMobProperties = EliteMobProperties.getPluginData(entityType); - /* - Handle name, variable as per stacking rules - */ - setCustomName(eliteMobProperties); - /* - Handle health, max is variable as per stacking rules - Currently #setHealth() resets the health back to maximum - */ - setMaxHealth(eliteMobProperties); - setHealth(); - /* - Set the armor - */ - setArmor(); - /* - Register whether or not the elite mob is natural - All mobs spawned via commands are considered natural - */ - this.isNaturalEntity = true; - /* - Set the power list - */ - this.powers = mobPowers; - /* - Start tracking the entity - */ - EntityTracker.registerEliteMob(new EliteMobEntity(this.eliteMob, this.eliteMobLevel)); - - if (ConfigValues.defaultConfig.getBoolean(DefaultConfig.PREVENT_ITEM_PICKUP)) - eliteMob.setCanPickupItems(false); - - } - - /* - This avoids accidentally assigning an elite mob to an entity spawned specifically to be a boss mob or reinforcement - */ - private static LivingEntity spawnBossMobLivingEntity(EntityType entityType, Location location) { - NaturalMobSpawnEventHandler.setIgnoreMob(true); - return (LivingEntity) location.getWorld().spawnEntity(location, entityType); - } - - private void setCustomName(EliteMobProperties eliteMobProperties) { - this.name = ChatColorConverter.convert( - eliteMobProperties.getName().replace( - "$level", eliteMobLevel + "")); - eliteMob.setCustomName(this.name); - if (ConfigValues.defaultConfig.getBoolean(DefaultConfig.ALWAYS_SHOW_NAMETAGS)) - eliteMob.setCustomNameVisible(true); - } - - private void setCustomName(String name) { - this.name = ChatColorConverter.convert(name); - this.getLivingEntity().setCustomName(this.name); - this.hasCustomName = true; - if (ConfigValues.defaultConfig.getBoolean(DefaultConfig.ALWAYS_SHOW_NAMETAGS)) - eliteMob.setCustomNameVisible(true); - } - - private void setEliteMobLevel(int newLevel) { - if (newLevel < 1) - newLevel = 1; - this.eliteMobLevel = newLevel; - } - - private void setMaxHealth(EliteMobProperties eliteMobProperties) { - double defaultMaxHealth = eliteMobProperties.getDefaultMaxHealth(); - this.maxHealth = (eliteMobLevel * CombatSystem.PER_LEVEL_POWER_INCREASE * defaultMaxHealth + defaultMaxHealth); - eliteMob.getAttribute(Attribute.GENERIC_MAX_HEALTH).setBaseValue(maxHealth); - } - - private void setHealth() { - eliteMob.setHealth(maxHealth = (maxHealth > 2048) ? 2048 : maxHealth); - } - - private void setHealth(double healthPercentage) { - eliteMob.setHealth(this.maxHealth * healthPercentage); - } - - - private void setArmor() { - - if (VersionChecker.currentVersionIsUnder(12, 2)) return; - if (!ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.ELITE_ARMOR)) return; - - eliteMob.getEquipment().setItemInMainHandDropChance(0); - eliteMob.getEquipment().setHelmetDropChance(0); - eliteMob.getEquipment().setChestplateDropChance(0); - eliteMob.getEquipment().setLeggingsDropChance(0); - eliteMob.getEquipment().setBootsDropChance(0); - - if (hasCustomArmor) return; - - if (!(eliteMob instanceof Zombie || eliteMob instanceof PigZombie || - eliteMob instanceof Skeleton || eliteMob instanceof WitherSkeleton)) return; - - eliteMob.getEquipment().setBoots(new ItemStack(Material.AIR)); - eliteMob.getEquipment().setLeggings(new ItemStack(Material.AIR)); - eliteMob.getEquipment().setChestplate(new ItemStack(Material.AIR)); - eliteMob.getEquipment().setHelmet(new ItemStack(Material.AIR)); - - if (eliteMobLevel >= 12) - if (ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.ELITE_HELMETS)) - eliteMob.getEquipment().setHelmet(new ItemStack(Material.LEATHER_HELMET)); - - if (eliteMobLevel >= 14) - eliteMob.getEquipment().setBoots(new ItemStack(Material.LEATHER_BOOTS)); - - if (eliteMobLevel >= 16) - eliteMob.getEquipment().setLeggings(new ItemStack(Material.LEATHER_LEGGINGS)); - - if (eliteMobLevel >= 18) - eliteMob.getEquipment().setChestplate(new ItemStack(Material.LEATHER_CHESTPLATE)); - - if (eliteMobLevel >= 20) - if (ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.ELITE_HELMETS)) - eliteMob.getEquipment().setHelmet(new ItemStack(Material.CHAINMAIL_HELMET)); - - if (eliteMobLevel >= 22) - eliteMob.getEquipment().setBoots(new ItemStack(Material.CHAINMAIL_BOOTS)); - - if (eliteMobLevel >= 24) - eliteMob.getEquipment().setLeggings(new ItemStack(Material.CHAINMAIL_LEGGINGS)); - - if (eliteMobLevel >= 26) - eliteMob.getEquipment().setChestplate(new ItemStack(Material.CHAINMAIL_CHESTPLATE)); - - if (eliteMobLevel >= 28) - if (ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.ELITE_HELMETS)) - eliteMob.getEquipment().setHelmet(new ItemStack(Material.IRON_HELMET)); - - if (eliteMobLevel >= 30) - eliteMob.getEquipment().setBoots(new ItemStack(Material.IRON_BOOTS)); - - if (eliteMobLevel >= 32) - eliteMob.getEquipment().setLeggings(new ItemStack(Material.IRON_LEGGINGS)); - - if (eliteMobLevel >= 34) - eliteMob.getEquipment().setChestplate(new ItemStack(Material.IRON_CHESTPLATE)); - - if (eliteMobLevel >= 36) - eliteMob.getEquipment().setBoots(new ItemStack(Material.DIAMOND_BOOTS)); - - if (eliteMobLevel >= 38) - if (ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.ELITE_HELMETS)) - eliteMob.getEquipment().setHelmet(new ItemStack(Material.DIAMOND_HELMET)); - - if (eliteMobLevel >= 40) - eliteMob.getEquipment().setLeggings(new ItemStack(Material.DIAMOND_LEGGINGS)); - - if (eliteMobLevel >= 42) - eliteMob.getEquipment().setChestplate(new ItemStack(Material.DIAMOND_CHESTPLATE)); - - } - - private void randomizePowers(EliteMobProperties eliteMobProperties) { - - if (hasCustomPowers) return; - if (eliteMobTier < 1) return; - - int availableDefensivePowers = 0; - int availableOffensivePowers = 0; - int availableMiscellaneousPowers = 0; - int availableMajorPowers = 0; - - if (eliteMobTier >= 1) availableDefensivePowers = 1; - if (eliteMobTier >= 2) availableOffensivePowers = 1; - if (eliteMobTier >= 3) availableMiscellaneousPowers = 1; - if (eliteMobTier >= 4) availableMajorPowers = 1; - if (eliteMobTier >= 5) availableDefensivePowers = 2; - if (eliteMobTier >= 6) availableOffensivePowers = 2; - if (eliteMobTier >= 7) availableMiscellaneousPowers = 2; - if (eliteMobTier >= 8) availableMajorPowers = 2; - - //apply defensive powers - applyPowers((HashSet) eliteMobProperties.getValidDefensivePowers().clone(), availableDefensivePowers); - - //apply offensive powers - applyPowers((HashSet) eliteMobProperties.getValidOffensivePowers().clone(), availableOffensivePowers); - - //apply miscellaneous powers - applyPowers((HashSet) eliteMobProperties.getValidMiscellaneousPowers().clone(), availableMiscellaneousPowers); - - //apply major powers - applyPowers((HashSet) eliteMobProperties.getValidMajorPowers().clone(), availableMajorPowers); - - MinorPowerPowerStance minorPowerStanceMath = new MinorPowerPowerStance(this); - MajorPowerPowerStance majorPowerPowerStance = new MajorPowerPowerStance(this); - - } - - private void applyPowers(HashSet elitePowers, int availablePowerAmount) { - - if (availablePowerAmount < 1) return; - - ArrayList localPowers = new ArrayList<>(elitePowers); - - for (ElitePower mobPower : this.powers) - localPowers.remove(mobPower); - - for (int i = 0; i < availablePowerAmount; i++) - if (localPowers.size() < 1) - break; - else { - ElitePower selectedPower = localPowers.get(ThreadLocalRandom.current().nextInt(localPowers.size())); - this.powers.add(selectedPower); - selectedPower.applyPowers(this.eliteMob); - localPowers.remove(selectedPower); - if (selectedPower instanceof MajorPower) - this.majorPowerCount++; - if (selectedPower instanceof MinorPower) - this.minorPowerCount++; - } - - } - - public void setCustomPowers(HashSet elitePowers) { - - this.powers = elitePowers; - for (ElitePower elitePower : elitePowers) { - elitePower.applyPowers(this.eliteMob); - if (elitePower instanceof MinorPower) - this.minorPowerCount++; - if (elitePower instanceof MajorPower) - this.majorPowerCount++; - } - - if (this.minorPowerCount > 0) { - MinorPowerPowerStance minorPowerStanceMath = new MinorPowerPowerStance(this); - } - - if (this.majorPowerCount > 0) { - MajorPowerPowerStance majorPowerPowerStance = new MajorPowerPowerStance(this); - } - - } - - public LivingEntity getLivingEntity() { - return eliteMob; - } - - public int getLevel() { - return eliteMobLevel; - } - - public boolean hasPower(ElitePower mobPower) { - for (ElitePower elitePower : powers) - if (elitePower.getClass().getTypeName().equals(mobPower.getClass().getTypeName())) - return true; - return false; - } - - public int getMinorPowerCount() { - return this.minorPowerCount; - } - - public int getMajorPowerCount() { - return this.majorPowerCount; - } - - public HashSet getPowers() { - return powers; - } - - public double getMaxHealth() { - return maxHealth; - } - - public void setHasStacking(boolean bool) { - this.hasStacking = bool; - } - - public boolean getHasCustomArmor() { - return this.hasCustomArmor; - } - - public void setHasCustomArmor(boolean bool) { - this.hasCustomArmor = bool; - } - - public boolean getHasCustomPowers() { - return this.hasCustomPowers; - } - - public void setHasCustomPowers(boolean bool) { - this.hasCustomPowers = bool; - } - - public String getName() { - return this.name; - } - - public boolean hasMinorVisualEffect() { - return this.hasMinorVisualEffect; - } - - public void setHasMinorVisualEffect(boolean bool) { - this.hasMinorVisualEffect = bool; - } - - public boolean hasMajorVisualEffect() { - return this.hasMajorVisualEffect; - } - - public void setHasMajorVisualEffect(boolean bool) { - this.hasMajorVisualEffect = bool; - } - - public boolean isNaturalEntity() { - return this.isNaturalEntity; - } - - public void setIsNaturalEntity(Boolean bool) { - this.isNaturalEntity = bool; - this.hasNormalLoot = bool; - } - - public boolean canStack() { - return this.hasStacking; - } - - public void setName(String name) { - this.name = name; - } - - public boolean getHasFarAwayUnload() { - return this.hasFarAwayUnload; - } - - public void setHasFarAwayUnload(boolean bool) { - this.hasFarAwayUnload = bool; - } - - public boolean getHasNormalLoot() { - return this.hasNormalLoot; - } - - public void setHasNormalLoot(boolean bool) { - this.isNaturalEntity = bool; - this.hasNormalLoot = bool; - } - - public boolean getHasCustomHealth() { - return this.hasCustomHealth; - } - - public void setHasCustomHealth(boolean bool) { - this.hasCustomHealth = bool; - } - - public boolean getHasCustomName() { - return this.hasCustomName; - } - - public void setHasCustomName(boolean bool) { - this.hasCustomName = bool; - } - - public void setHasVisualEffectObfuscated(boolean bool) { - this.hasVisualEffectObfuscated = bool; - } - - public boolean getHasVisualEffectObfuscated() { - return this.hasVisualEffectObfuscated; - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/MergeHandler.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/MergeHandler.java index f454a0ff9..07ef53579 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/MergeHandler.java +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/MergeHandler.java @@ -1,27 +1,8 @@ -/* - * 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 . - */ - package com.magmaguy.elitemobs.mobconstructor; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; -import com.magmaguy.elitemobs.config.ValidMobsConfig; -import com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs.EliteMobProperties; +import com.magmaguy.elitemobs.config.ValidWorldsConfig; import com.magmaguy.elitemobs.mobconstructor.mobdata.passivemobs.SuperMobProperties; -import com.magmaguy.elitemobs.mobscanner.EliteMobScanner; -import com.magmaguy.elitemobs.mobscanner.SuperMobScanner; +import com.magmaguy.elitemobs.mobs.passive.PassiveEliteMobDeathHandler; import org.bukkit.entity.Entity; import org.bukkit.entity.LivingEntity; import org.bukkit.event.EventHandler; @@ -37,6 +18,8 @@ public class MergeHandler implements Listener { @EventHandler public void onDamageMerge(EntityDamageEvent event) { + if (!ValidWorldsConfig.getFileConfiguration().getBoolean("Valid worlds." + event.getEntity().getWorld().getName())) + return; validateEntityType(event.getEntity()); } @@ -44,19 +27,19 @@ public void onDamageMerge(EntityDamageEvent event) { @EventHandler public void onSpawnMerge(EntitySpawnEvent event) { + if (!ValidWorldsConfig.getFileConfiguration().getBoolean("Valid worlds." + event.getEntity().getWorld().getName())) + return; validateEntityType(event.getEntity()); } private void validateEntityType(Entity eventEntity) { - if (ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.AGGRESSIVE_MOB_STACKING) && - EliteMobProperties.isValidEliteMobType(eventEntity)) - EliteMobScanner.scanValidAggressiveLivingEntity((LivingEntity) eventEntity); + if (eventEntity == null) return; + if (!(eventEntity instanceof LivingEntity)) return; - if (ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.ALLOW_PASSIVE_SUPERMOBS) && - SuperMobProperties.isValidSuperMobType(eventEntity)) - SuperMobScanner.newSuperMobScan((LivingEntity) eventEntity); + if (SuperMobProperties.isValidSuperMobType(eventEntity)) + PassiveEliteMobDeathHandler.SuperMobScanner.newSuperMobScan((LivingEntity) eventEntity); } diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/ReinforcementMobEntity.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/ReinforcementMobEntity.java deleted file mode 100644 index b59bbec83..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/ReinforcementMobEntity.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.magmaguy.elitemobs.mobconstructor; - -import org.bukkit.Location; -import org.bukkit.entity.EntityType; - -public class ReinforcementMobEntity extends EliteMobEntity { - - /* - Half the level of the elite they're reinforcing - */ - public ReinforcementMobEntity(EntityType entityType, Location location, int eliteMobLevel, String name) { - super(entityType, location, (int) Math.ceil(eliteMobLevel / 2), name); - super.setHasNormalLoot(false); - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/SimplePersistentEntity.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/SimplePersistentEntity.java new file mode 100644 index 000000000..97d2d6310 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/SimplePersistentEntity.java @@ -0,0 +1,153 @@ +package com.magmaguy.elitemobs.mobconstructor; + +import com.google.common.collect.ArrayListMultimap; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import com.magmaguy.elitemobs.npcs.NPCEntity; +import com.magmaguy.elitemobs.utils.ChunkVectorizer; +import lombok.Getter; +import org.bukkit.Bukkit; +import org.bukkit.Chunk; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.world.ChunkLoadEvent; +import org.bukkit.event.world.WorldLoadEvent; +import org.bukkit.event.world.WorldUnloadEvent; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; + +public class SimplePersistentEntity { + + //Values are stored for the chunk load events + @Getter + private static final ArrayListMultimap persistentEntities = ArrayListMultimap.create(); + private static final ArrayListMultimap persistentEntitiesForQueuedWorlds = ArrayListMultimap.create(); + private final Location location; + private int chunk; + private CustomBossEntity customBossEntity; + private String worldName; + private NPCEntity npcEntity; + + /** + * Used to store the locations of custom bosses that have gone into unloaded chunks. + * + * @param customBossEntity + */ + public SimplePersistentEntity(CustomBossEntity customBossEntity, Location location) { + this.customBossEntity = customBossEntity; + this.location = location; + if (location == null) location = customBossEntity.getSpawnLocation(); + this.worldName = customBossEntity.getWorldName(); + if (location.getWorld() != null) { + this.chunk = ChunkVectorizer.hash( + location.getBlockX() >> 4, + location.getBlockZ() >> 4, + location.getWorld().getUID()); + addPersistentEntity(this); + } else { + addPersistentEntityForWorld(this); + } + } + + public SimplePersistentEntity(NPCEntity npcEntity) { + this.npcEntity = npcEntity; + this.location = npcEntity.getSpawnLocation(); + if (location != null && location.getWorld() != null) { + this.chunk = ChunkVectorizer.hash( + location.getBlockX() >> 4, + location.getBlockZ() >> 4, + location.getWorld().getUID()); + addPersistentEntity(this); + } else { + this.worldName = npcEntity.getNPCsConfigFields().getLocation().split(",")[0]; + addPersistentEntityForWorld(this); + } + } + + /** + * Used to add persistent entities to the list. This inserts an arbitrary amount of persistent entities into a chunk. + * Called when a SimplePersistentEntity is created. + * + * @param simplePersistentEntity Entity to be added + */ + private static void addPersistentEntity(SimplePersistentEntity simplePersistentEntity) { + persistentEntities.put(simplePersistentEntity.chunk, simplePersistentEntity); + } + + private static void addPersistentEntityForWorld(SimplePersistentEntity simplePersistentEntity) { + persistentEntitiesForQueuedWorlds.put(simplePersistentEntity.worldName, simplePersistentEntity); + } + + public void remove() { + persistentEntities.remove(this.chunk, this); + } + + public static class PersistentEntityEvent implements Listener { + private static final HashSet loadingChunks = new HashSet<>(); + + private static int chunkLocation(Chunk chunk) { + return ChunkVectorizer.hash(chunk); + } + + /** + * Behavior that runs when a chunk loads, spawning the entity + * + * @param chunkLocation + */ + private static void loadChunk(int chunkLocation, List simplePersistentEntityList) { + simplePersistentEntityList.forEach(simplePersistentEntity -> { + if (simplePersistentEntity.customBossEntity != null) + simplePersistentEntity.customBossEntity.chunkLoad(); + else if (simplePersistentEntity.npcEntity != null) + simplePersistentEntity.npcEntity.chunkLoad(); + }); + persistentEntities.removeAll(chunkLocation); + } + + private static void unloadWorld(World world) { + persistentEntities.values().removeIf(simplePersistentEntity -> { + if (simplePersistentEntity.location == null) return false; + if (simplePersistentEntity.location.getWorld() == null) return false; + if (!simplePersistentEntity.location.getWorld().equals(world)) return false; + if (simplePersistentEntity.customBossEntity != null) + simplePersistentEntity.customBossEntity.worldUnload(); + else if (simplePersistentEntity.npcEntity != null) + simplePersistentEntity.npcEntity.worldUnload(); + return true; + }); + } + + //Store world names and serialized locations + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + public void chunkLoadEvent(ChunkLoadEvent event) { + int chunkLocation = chunkLocation(event.getChunk()); + List simplePersistentEntityList = new ArrayList<>(persistentEntities.get(chunkLocation)); + if (loadingChunks.contains(chunkLocation)) return; + loadingChunks.add(chunkLocation); + Bukkit.getScheduler().runTaskLater(MetadataHandler.PLUGIN, () -> loadChunk(chunkLocation, simplePersistentEntityList), 1); + Bukkit.getScheduler().runTaskLater(MetadataHandler.PLUGIN, () -> loadingChunks.remove(chunkLocation), 1); + } + + @EventHandler(ignoreCancelled = true) + public void worldUnloadEvent(WorldUnloadEvent event) { + unloadWorld(event.getWorld()); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.MONITOR) + public void worldLoadEvent(WorldLoadEvent event) { + Bukkit.getScheduler().runTaskLater(MetadataHandler.PLUGIN, task -> { + for (SimplePersistentEntity simplePersistentEntity : persistentEntitiesForQueuedWorlds.get(event.getWorld().getName())) + if (simplePersistentEntity.customBossEntity != null) + simplePersistentEntity.customBossEntity.worldLoad(); + else if (simplePersistentEntity.npcEntity != null) + simplePersistentEntity.npcEntity.worldLoad(); + persistentEntitiesForQueuedWorlds.removeAll(event.getWorld().getName()); + }, 20); + } + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/SimplePersistentEntityInterface.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/SimplePersistentEntityInterface.java new file mode 100644 index 000000000..230f6c916 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/SimplePersistentEntityInterface.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.mobconstructor; + +public interface SimplePersistentEntityInterface { + + /** + * Sets the behavior for chunk loads + */ + void chunkLoad(); + + /** + * Sets the behavior for chunk unloads + */ + void chunkUnload(); + + void worldLoad(); + + void worldUnload(); + +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/SuperMobConstructor.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/SuperMobConstructor.java index 8da5a003b..d20cb0bcb 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/SuperMobConstructor.java +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/SuperMobConstructor.java @@ -1,8 +1,8 @@ package com.magmaguy.elitemobs.mobconstructor; import com.magmaguy.elitemobs.ChatColorConverter; -import com.magmaguy.elitemobs.config.ConfigValues; import com.magmaguy.elitemobs.config.DefaultConfig; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; import com.magmaguy.elitemobs.mobconstructor.mobdata.passivemobs.SuperMobProperties; import org.bukkit.Bukkit; import org.bukkit.attribute.Attribute; @@ -10,6 +10,8 @@ public class SuperMobConstructor { + private SuperMobConstructor() { + } /* This class assumes that the entity has already been filtered and validated before being invoked @@ -22,13 +24,15 @@ public static LivingEntity constructSuperMob(LivingEntity livingEntity) { } String name = ChatColorConverter.convert(SuperMobProperties.getDataInstance(livingEntity).getName()); - double newMaxHealth = SuperMobProperties.getDataInstance(livingEntity).getDefaultMaxHealth() * ConfigValues.defaultConfig.getInt(DefaultConfig.SUPERMOB_STACK_AMOUNT); + double newMaxHealth = SuperMobProperties.getDataInstance(livingEntity).getDefaultMaxHealth() * DefaultConfig.getSuperMobStackAmount(); livingEntity.setCustomName(name); livingEntity.setCustomNameVisible(true); livingEntity.getAttribute(Attribute.GENERIC_MAX_HEALTH).setBaseValue(newMaxHealth); livingEntity.setHealth(newMaxHealth); + EntityTracker.registerSuperMob(livingEntity); + return livingEntity; } diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/TimedBossMobEntity.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/TimedBossMobEntity.java deleted file mode 100644 index 276c1d143..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/TimedBossMobEntity.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.magmaguy.elitemobs.mobconstructor; - -import com.magmaguy.elitemobs.events.mobs.sharedeventproperties.BossMobDeathCountdown; -import org.bukkit.Location; -import org.bukkit.entity.EntityType; - -public class TimedBossMobEntity extends BossMobEntity { - - public TimedBossMobEntity(EntityType entityType, Location location, int eliteMobLevel, String name) { - super(entityType, location, eliteMobLevel, name); - super.setHasFarAwayUnload(false); - super.getLivingEntity().setRemoveWhenFarAway(false); - BossMobDeathCountdown.startDeathCountdown(super.getLivingEntity()); - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/TrashMobEntity.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/TrashMobEntity.java deleted file mode 100644 index 67b75fef4..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/TrashMobEntity.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.magmaguy.elitemobs.mobconstructor; - -import org.bukkit.Location; -import org.bukkit.attribute.Attribute; -import org.bukkit.entity.EntityType; - -public class TrashMobEntity extends ReinforcementMobEntity { - - public TrashMobEntity(EntityType entityType, Location location, String name) { - - super(entityType, location, 1, name); - super.setHasCustomHealth(true); - super.getLivingEntity().getAttribute(Attribute.GENERIC_MAX_HEALTH).setBaseValue(1); - super.getLivingEntity().setHealth(1); - super.setHasNormalLoot(false); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/AdvancedAggroManager.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/AdvancedAggroManager.java new file mode 100644 index 000000000..d7357f72a --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/AdvancedAggroManager.java @@ -0,0 +1,48 @@ +package com.magmaguy.elitemobs.mobconstructor.custombosses; + +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerEvent; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Mob; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; + +import java.util.ArrayList; +import java.util.List; + +public class AdvancedAggroManager implements Listener { + + @EventHandler(priority = EventPriority.HIGH) + public void onHit(EliteMobDamagedByPlayerEvent event) { + if (event.isCancelled()) return; + if (!event.getEliteMobEntity().hasDamagers()) return; + if (event.getEliteMobEntity().getDamagers().size() < 2) return; + if (!(event.getEliteMobEntity().getLivingEntity() instanceof Mob)) return; + + List nearbyPlayers = new ArrayList<>(); + for (Entity entity : event.getEliteMobEntity().getLivingEntity().getNearbyEntities(35, 35, 35)) + if (entity.getType().equals(EntityType.PLAYER)) + nearbyPlayers.add((Player) entity); + + Player player = null; + double damage = 0; + for (Player iteratedPlayer : event.getEliteMobEntity().getDamagers().keySet()) { + if (event.getEliteMobEntity().getDamagers().get(iteratedPlayer) > damage && + nearbyPlayers.contains(iteratedPlayer)) { + player = iteratedPlayer; + damage = event.getEliteMobEntity().getDamagers().get(iteratedPlayer); + } + } + + if (player == null) return; + + if (((Mob) event.getEliteMobEntity().getLivingEntity()).getTarget() == null || + !((Mob) event.getEliteMobEntity().getLivingEntity()).getTarget().getUniqueId().equals(player.getUniqueId())) { + ((Mob) event.getEliteMobEntity().getLivingEntity()).setTarget(player); + } + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/BossTrace.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/BossTrace.java new file mode 100644 index 000000000..ad80fbafa --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/BossTrace.java @@ -0,0 +1,60 @@ +package com.magmaguy.elitemobs.mobconstructor.custombosses; + +import com.magmaguy.elitemobs.api.internal.RemovalReason; +import com.magmaguy.elitemobs.utils.DebugMessage; +import com.magmaguy.elitemobs.utils.ServerTime; +import com.magmaguy.elitemobs.utils.WarningMessage; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; + +public class BossTrace { + private final long creationTimeStamp; + private final double creationTicksStamp; + //Welcome to my garden of insanity. This is necessary because Minecraft just refuses to cooperate + private List trace = new ArrayList<>(); + + public BossTrace() { + creationTimeStamp = System.currentTimeMillis(); + creationTicksStamp = ServerTime.getTime(); + String creationString = ChatColor.DARK_GREEN + "Creation timestamp: " + creationTimeStamp; + trace.add(creationString); + } + + + public void spawnPreprocessor(int version) { + if (!DebugMessage.isDebugMode()) return; + String spawnString = ChatColor.YELLOW + getPrefix() + "Spawn preprocessor " + version + "/2"; + trace.add(spawnString); + } + + public void setSpawn() { + if (!DebugMessage.isDebugMode()) return; + String spawnString = ChatColor.GREEN + getPrefix() + "Spawn!"; + trace.add(spawnString); + } + + public void setRemove(RemovalReason removalReason) { + if (!DebugMessage.isDebugMode()) return; + String removeString = ChatColor.RED + getPrefix() + "Remove! Reason: " + removalReason; + trace.add(removeString); + } + + private String getPrefix() { + return "[" + (ServerTime.getTime() - creationTicksStamp) + "t] "; + } + + public void postLog(Player player) { + if (!DebugMessage.isDebugMode()) + player.sendMessage(ChatColor.RED + "[EliteMobs] Debug mode must be on for this to work! Do " + ChatColor.GREEN + "/em debugmode"); + player.sendMessage(ChatColor.GREEN + "[EliteMobs] Here is the full activity log for this boss. A copy is also logged into console!"); + new WarningMessage("Sequential code execution list for boss:"); + for (String string : trace) { + player.sendMessage(string); + new WarningMessage(string); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/CustomBossBossBar.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/CustomBossBossBar.java new file mode 100644 index 000000000..0f0979af0 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/CustomBossBossBar.java @@ -0,0 +1,163 @@ +package com.magmaguy.elitemobs.mobconstructor.custombosses; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; +import com.magmaguy.elitemobs.config.TranslationConfig; +import com.magmaguy.elitemobs.utils.Round; +import com.magmaguy.elitemobs.utils.WarningMessage; +import net.md_5.bungee.api.chat.ClickEvent; +import net.md_5.bungee.api.chat.ComponentBuilder; +import net.md_5.bungee.api.chat.HoverEvent; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.Bukkit; +import org.bukkit.boss.BarColor; +import org.bukkit.boss.BarFlag; +import org.bukkit.boss.BarStyle; +import org.bukkit.boss.BossBar; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scheduler.BukkitTask; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; + +public class CustomBossBossBar { + + private final CustomBossEntity customBossEntity; + private final Map bossBars = new HashMap<>(); + private final HashSet trackingPlayers = new HashSet<>(); + private BukkitTask bossBarUpdater; + + public CustomBossBossBar(CustomBossEntity customBossEntity) { + this.customBossEntity = customBossEntity; + start(); + sendLocation(); + } + + private void sendLocation() { + for (Player player : Bukkit.getOnlinePlayers()) { + if (!player.getWorld().equals(customBossEntity.getLocation().getWorld())) continue; + TextComponent interactiveMessage = new TextComponent(MobCombatSettingsConfig.getBossLocationMessage()); + interactiveMessage.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/elitemobs trackcustomboss " + customBossEntity.getEliteUUID())); + interactiveMessage.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(TranslationConfig.getTrackMessage().replace("$name", customBossEntity.getName())).create())); + player.spigot().sendMessage(interactiveMessage); + } + } + + public void addTrackingPlayer(Player player) { + if (!trackingPlayers.contains(player)) + trackingPlayers.add(player); + else + trackingPlayers.remove(player); + } + + public void removeTrackingPlayer(Player player) { + trackingPlayers.remove(player); + BossBar bossBar = bossBars.remove(player); + if (bossBar != null) bossBar.removeAll(); + } + + public void remove() { + bossBars.values().forEach(BossBar::removeAll); + bossBars.clear(); + trackingPlayers.clear(); + bossBarUpdater.cancel(); + } + + /** + * Used not only for generating the boss bar message, but also the message that appears on the tracking screen for players + * + * @param player + * @param locationString + * @return + */ + public String bossBarMessage(Player player, String locationString) { + if (customBossEntity.getCustomBossesConfigFields().getLocationMessage() == null) return ""; + if (customBossEntity.getCustomBossesConfigFields().getLocationMessage().contains("$distance") || + customBossEntity.getCustomBossesConfigFields().getLocationMessage().contains("$location")) { + if (!player.getLocation().getWorld().equals(customBossEntity.getLocation().getWorld())) + return ChatColorConverter.convert(MobCombatSettingsConfig.getDefaultOtherWorldBossLocationMessage() + .replace("$name", customBossEntity.getName())); + + return ChatColorConverter.convert(customBossEntity.getCustomBossesConfigFields().getLocationMessage() + .replace("$distance", "" + (int) customBossEntity.getLocation().distance(player.getLocation()))) + .replace("$location", locationString); + } + + return ChatColorConverter.convert(customBossEntity.getCustomBossesConfigFields().getLocationMessage()); + + } + + private void updateBossBar(Player player, BossBar bossBar) { + if (player == null) return; + if (bossBar == null) return; + String locationString = customBossEntity.getLocation().getBlockX() + + ", " + customBossEntity.getLocation().getBlockY() + + ", " + customBossEntity.getLocation().getBlockZ(); + bossBar.setTitle(bossBarMessage(player, locationString)); + double progress = Round.twoDecimalPlaces(customBossEntity.getHealth() / customBossEntity.getMaxHealth()); + if (progress > 1) return; + bossBar.setProgress(progress); + } + + public void start() { + bossBarUpdater = new BukkitRunnable() { + @Override + public void run() { + //This can happen on phase changes where boss bars might not be configured on subsequent entities + if (!customBossEntity.exists() || customBossEntity.getCustomBossesConfigFields().getLocationMessage() == null) { + cancel(); + return; + } + + HashSet freshIteration = new HashSet<>(); + for (Player player : trackingPlayers) { + freshIteration.add(player); + if (!bossBars.containsKey(player)) createBossBar(player); + updateBossBar(player, bossBars.get(player)); + } + + //Remove players that have stopped + bossBars.entrySet().removeIf(entry -> { + if (!trackingPlayers.contains(entry.getKey())) { + entry.getValue().removeAll(); + return true; + } + return false; + }); + + //nearby player check + if (customBossEntity.isValid()) + for (Entity entity : customBossEntity.getLivingEntity().getNearbyEntities(30, 30, 30)) + if (entity.getType().equals(EntityType.PLAYER)) + if (!freshIteration.contains((Player) entity)) + createBossBar((Player) entity); + + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 5); + } + + private void createBossBar(Player player) { + String locationString = (int) customBossEntity.getLocation().getX() + + ", " + (int) customBossEntity.getLocation().getY() + + ", " + (int) customBossEntity.getLocation().getZ(); + BossBar bossBar = Bukkit.createBossBar(bossBarMessage(player, locationString), BarColor.GREEN, BarStyle.SOLID, BarFlag.PLAY_BOSS_MUSIC); + + if (customBossEntity.getHealth() / customBossEntity.getMaxHealth() > 1 || customBossEntity.getHealth() / customBossEntity.getMaxHealth() < 0) { + new WarningMessage("The following boss had more health than it should: " + customBossEntity.getName()); + new WarningMessage("This is a problem usually caused by running more than one plugin that modifies mob health!" + + " EliteMobs can't fix this issue because it is being caused by another plugin." + + " If you want EliteMobs to work correctly, find a way to fix this issue with whatever other plugin is causing it."); + return; + } + + bossBars.put(player, bossBar); + updateBossBar(player, bossBar); + bossBar.addPlayer(player); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/CustomBossDeath.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/CustomBossDeath.java new file mode 100644 index 000000000..546b03586 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/CustomBossDeath.java @@ -0,0 +1,185 @@ +package com.magmaguy.elitemobs.mobconstructor.custombosses; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.api.EliteMobDeathEvent; +import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; +import com.magmaguy.elitemobs.ondeathcommands.OnDeathCommands; +import com.magmaguy.elitemobs.thirdparty.discordsrv.DiscordSRVAnnouncement; +import com.magmaguy.elitemobs.utils.Round; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.inventory.ItemStack; + +import java.util.*; + +public class CustomBossDeath implements Listener { + + private static void doLoot(CustomBossEntity customBossEntity) { + for (Player player : customBossEntity.getDamagers().keySet()) + if (!customBossEntity.isTriggeredAntiExploit()) + dropLoot(player, customBossEntity); + } + + public static void dropLoot(Player player, CustomBossEntity customBossEntity) { + if (customBossEntity.customBossesConfigFields.getUniqueLootList().isEmpty()) return; + customBossEntity.customBossesConfigFields.getCustomLootTable().bossDrop(player, customBossEntity.getLevel(), customBossEntity.getLocation(), customBossEntity); + } + + private static void doDeathMessage(CustomBossEntity customBossEntity) { + //Do death message + StringBuilder playersList = new StringBuilder(); + for (Player player : customBossEntity.getDamagers().keySet()) { + if (playersList.length() == 0) + playersList.append(player.getDisplayName()); + else + playersList.append(", &f").append(player.getDisplayName()); + } + + playersList = new StringBuilder(ChatColorConverter.convert(playersList.toString())); + + if (customBossEntity.hasDamagers()) + if (customBossEntity.customBossesConfigFields.getDeathMessages() != null && + !customBossEntity.customBossesConfigFields.getDeathMessages().isEmpty()) { + Player topDamager = null, secondDamager = null, thirdDamager = null; + + HashMap sortedMap = sortByComparator(customBossEntity.getDamagers(), false); + + Iterator sortedMapIterator = sortedMap.keySet().iterator(); + for (int i = 1; i < 4; i++) { + if (i > sortedMap.size()) + break; + Player nextPlayer = sortedMapIterator.next(); + switch (i) { + case 1: + topDamager = nextPlayer; + break; + case 2: + secondDamager = nextPlayer; + break; + case 3: + thirdDamager = nextPlayer; + break; + } + } + + for (String string : customBossEntity.customBossesConfigFields.getDeathMessages()) { + if (string.contains("$damager1name")) + if (topDamager != null) + string = string.replace("$damager1name", topDamager.getDisplayName()); + else + string = ""; + if (string.contains("$damager1damage")) + if (topDamager != null) + string = string.replace("$damager1damage", + Round.twoDecimalPlaces(customBossEntity.getDamagers().get(topDamager)) + ""); + else + string = ""; + if (string.contains("$damager2name")) + if (secondDamager != null) + string = string.replace("$damager2name", secondDamager.getDisplayName()); + else + string = ""; + if (string.contains("$damager2damage")) + if (secondDamager != null) + string = string.replace("$damager2damage", + Round.twoDecimalPlaces(customBossEntity.getDamagers().get(secondDamager)) + ""); + else + string = ""; + if (string.contains("$damager3name")) + if (thirdDamager != null) + string = string.replace("$damager3name", thirdDamager.getDisplayName()); + else + string = ""; + if (string.contains("$damager3damage")) + if (thirdDamager != null) + string = string.replace("$damager3damage", + Round.twoDecimalPlaces(customBossEntity.getDamagers().get(thirdDamager)) + ""); + else + string = ""; + if (string.contains("$players")) + string = string.replace("$players", playersList.toString()); + if (customBossEntity.customBossesConfigFields.getAnnouncementPriority() > 0) + Bukkit.broadcastMessage(ChatColorConverter.convert(string)); + if (string.length() > 0) + if (customBossEntity.customBossesConfigFields.getAnnouncementPriority() > 2) + new DiscordSRVAnnouncement(ChatColorConverter.convert(string)); + else + for (Player player : customBossEntity.getDamagers().keySet()) + player.sendMessage(ChatColorConverter.convert(string)); + } + + for (Player player : Bukkit.getOnlinePlayers()) + if (customBossEntity.getDamagers().containsKey(player)) + player.sendMessage( + ChatColorConverter.convert( + MobCombatSettingsConfig.getBossKillParticipationMessage().replace( + "$playerDamage", + Round.twoDecimalPlaces(customBossEntity.getDamagers().get(player)) + ""))); + + } else { + if (customBossEntity.customBossesConfigFields.getDeathMessage() != null) { + if (customBossEntity.customBossesConfigFields.getAnnouncementPriority() == 0) + for (Player player : customBossEntity.getDamagers().keySet()) + player.sendMessage(ChatColorConverter.convert( + customBossEntity.customBossesConfigFields.getDeathMessage().replace("$players", playersList.toString()))); + if (customBossEntity.customBossesConfigFields.getAnnouncementPriority() > 0) + Bukkit.broadcastMessage(ChatColorConverter.convert( + customBossEntity.customBossesConfigFields.getDeathMessage().replace("$players", playersList.toString()))); + if (customBossEntity.customBossesConfigFields.getAnnouncementPriority() > 2) + new DiscordSRVAnnouncement(ChatColorConverter.convert( + customBossEntity.customBossesConfigFields.getDeathMessage().replace("$players", playersList.toString()))); + } + } + } + + //sorts damagers + private static HashMap sortByComparator(Map unsortMap, final boolean order) { + + List> list = new LinkedList>(unsortMap.entrySet()); + + // Sorting the list based on values + Collections.sort(list, new Comparator>() { + public int compare(Map.Entry o1, + Map.Entry o2) { + if (order) + return o1.getValue().compareTo(o2.getValue()); + else + return o2.getValue().compareTo(o1.getValue()); + } + }); + + // Maintaining insertion order with the help of LinkedList + HashMap sortedMap = new LinkedHashMap(); + for (Map.Entry entry : list) + sortedMap.put(entry.getKey(), entry.getValue()); + + return sortedMap; + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onEliteMobDeath(EliteMobDeathEvent event) { + if (!(event.getEliteEntity() instanceof CustomBossEntity)) return; + CustomBossEntity customBossEntity = (CustomBossEntity) event.getEliteEntity(); + + doLoot(customBossEntity); + doDeathMessage(customBossEntity); + + //untrack from trackable custom bosses + CustomBossEntity.trackableCustomBosses.remove(customBossEntity); + + if (customBossEntity.customBossesConfigFields.getOnDeathCommands() != null && + !customBossEntity.customBossesConfigFields.getOnDeathCommands().isEmpty()) + OnDeathCommands.parseConsoleCommand(customBossEntity.customBossesConfigFields.getOnDeathCommands(), event); + + if (!customBossEntity.customBossesConfigFields.isDropsVanillaLoot()) { + event.getEntityDeathEvent().setDroppedExp(0); + for (ItemStack itemStack : event.getEntityDeathEvent().getDrops()) + itemStack.setAmount(0); + } + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/CustomBossEntity.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/CustomBossEntity.java new file mode 100644 index 000000000..8a34fce93 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/CustomBossEntity.java @@ -0,0 +1,556 @@ +package com.magmaguy.elitemobs.mobconstructor.custombosses; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobEnterCombatEvent; +import com.magmaguy.elitemobs.api.EliteMobExitCombatEvent; +import com.magmaguy.elitemobs.api.EliteMobRemoveEvent; +import com.magmaguy.elitemobs.api.internal.RemovalReason; +import com.magmaguy.elitemobs.config.DefaultConfig; +import com.magmaguy.elitemobs.config.EventsConfig; +import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfig; +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import com.magmaguy.elitemobs.dungeons.Minidungeon; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.events.CustomEvent; +import com.magmaguy.elitemobs.mobconstructor.CustomSpawn; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.mobconstructor.SimplePersistentEntity; +import com.magmaguy.elitemobs.mobconstructor.SimplePersistentEntityInterface; +import com.magmaguy.elitemobs.mobconstructor.custombosses.transitiveblocks.TransitiveBlock; +import com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs.EliteMobProperties; +import com.magmaguy.elitemobs.playerdata.ElitePlayerInventory; +import com.magmaguy.elitemobs.powers.meta.CustomSummonPower; +import com.magmaguy.elitemobs.powers.meta.ElitePower; +import com.magmaguy.elitemobs.thirdparty.discordsrv.DiscordSRVAnnouncement; +import com.magmaguy.elitemobs.thirdparty.libsdisguises.DisguiseEntity; +import com.magmaguy.elitemobs.thirdparty.modelengine.CustomModel; +import com.magmaguy.elitemobs.utils.*; +import lombok.Getter; +import lombok.Setter; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.CreatureSpawnEvent; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.scheduler.BukkitTask; + +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Objects; + +public class CustomBossEntity extends EliteEntity implements Listener, SimplePersistentEntityInterface { + + @Getter + protected static HashSet trackableCustomBosses = new HashSet<>(); + private final List globalReinforcements = new ArrayList<>(); + @Getter + private final BossTrace bossTrace = new BossTrace(); + @Getter + protected CustomBossesConfigFields customBossesConfigFields; + protected CustomBossEntity customBossMount = null; + protected LivingEntity livingEntityMount = null; + protected CustomBossEntity mount; + protected SimplePersistentEntity simplePersistentEntity; + protected Location persistentLocation; + @Getter + @Setter + protected Location spawnLocation; + protected CustomBossTrail customBossTrail; + @Getter + protected CustomBossBossBar customBossBossBar; + protected Integer escapeMechanism; + @Getter + protected PhaseBossEntity phaseBossEntity = null; + @Getter + protected String worldName; + protected boolean chunkLoad = false; + private long lastTick = 0; + private int attemptsCounter = 1; + //For use by the phase switcher, which requires passing a specific spawn location for the phase, but when it's for a + //regional boss this causes issues such as reinforcements getting shifted over to the new spawn location + @Getter + @Setter + private Location respawnOverrideLocation; + private boolean worldIsLoading = false; + @Getter + @Setter + private Minidungeon minidungeon = null; + @Setter + private CustomSpawn customSpawn = null; + private int existsFailureCount = 0; + @Getter + @Setter + private boolean isMount = false; + @Getter + @Setter + private CustomModel customModel = null; + @Getter + private boolean normalizedCombat; + + /** + * Uses a builder pattern in order to construct a CustomBossEntity at an arbitrary point in the future. Does not + * spawn an entity until the spawn method is invoked. The customBossesConfigFields value isn't final. + *

+ * The {@link CustomBossEntity#setSpawnLocation(Location)} can be assigned at an arbitrary point in the future before the spawn is invoked. + * Uses: + * - {@link CustomEvent} queueing through the {@link CustomSpawn} system + */ + public CustomBossEntity(CustomBossesConfigFields customBossesConfigFields) { + //This creates a placeholder empty EliteMobEntity to be filled in later + super(); + //This stores everything that will need to be initialized for the EliteMobEntity + setCustomBossesConfigFields(customBossesConfigFields); + super.setPersistent(customBossesConfigFields.isPersistent()); + //Phases are final + if (!customBossesConfigFields.getPhases().isEmpty()) + this.phaseBossEntity = new PhaseBossEntity(this); + if (this instanceof RegionalBossEntity) + super.bypassesProtections = true; + } + + @Nullable + public static CustomBossEntity createCustomBossEntity(String filename) { + CustomBossesConfigFields customBossesConfigFields = CustomBossesConfig.getCustomBoss(filename); + if (customBossesConfigFields == null) + return null; + return new CustomBossEntity(customBossesConfigFields); + } + + @Override + public void setSummoningEntity(EliteEntity summoningEntity) { + this.summoningEntity = summoningEntity; + if (summoningEntity instanceof CustomBossEntity) + this.minidungeon = ((CustomBossEntity) summoningEntity).minidungeon; + } + + /** + * The customBossesConfigFields is not final, and changes if the boss has phases, loading the configuration from the phases as the fight goes along. + * + * @param customBossesConfigFields Configuration file to be used as the basis of the values of the boss. + */ + public void setCustomBossesConfigFields(CustomBossesConfigFields customBossesConfigFields) { + this.customBossesConfigFields = customBossesConfigFields; + normalizedCombat = customBossesConfigFields.isNormalizedCombat(); + super.setDamageMultiplier(customBossesConfigFields.getDamageMultiplier()); + super.setHealthMultiplier(customBossesConfigFields.getHealthMultiplier()); + super.setEliteLoot(customBossesConfigFields.isDropsEliteMobsLoot()); + super.setRandomLoot(customBossesConfigFields.isDropsRandomLoot()); + super.setVanillaLoot(customBossesConfigFields.isDropsVanillaLoot()); + super.setLevel(customBossesConfigFields.getLevel()); + setPluginName(); + super.elitePowers = ElitePowerParser.parsePowers(customBossesConfigFields.getPowers()); + if (this instanceof RegionalBossEntity) { + ((RegionalBossEntity) this).setOnSpawnTransitiveBlocks(TransitiveBlock.serializeTransitiveBlocks(customBossesConfigFields.getOnSpawnBlockStates(), customBossesConfigFields.getFilename())); + ((RegionalBossEntity) this).setOnRemoveTransitiveBlocks(TransitiveBlock.serializeTransitiveBlocks(customBossesConfigFields.getOnRemoveBlockStates(), customBossesConfigFields.getFilename())); + } + } + + public void spawn(Location spawnLocation, int level, boolean silent) { + bossTrace.spawnPreprocessor(1); + super.level = level; + this.spawnLocation = spawnLocation; + spawn(spawnLocation, silent); + } + + public void spawn(Location spawnLocation, boolean silent) { + bossTrace.spawnPreprocessor(2); + if (spawnLocation != null && spawnLocation.getWorld() != null && lastTick == spawnLocation.getWorld().getFullTime()) + attemptsCounter++; + else + attemptsCounter = 1; + if (spawnLocation != null && spawnLocation.getWorld() != null) + lastTick = spawnLocation.getWorld().getFullTime(); + //Use exists() here as the persistent entities will not try to respawn through this method + if (exists()) { + new WarningMessage("Warning: " + customBossesConfigFields.getFilename() + " attempted to double spawn " + attemptsCounter + " times!", true); + return; + } + this.spawnLocation = spawnLocation; + spawn(silent); + } + + public void spawn(boolean silent) { + bossTrace.setSpawn(); + if (livingEntity != null) { + new WarningMessage("Warning: " + customBossesConfigFields.getFilename() + " attempted to double spawn!", true); + return; + } + + if (spawnLocation == null) { + new WarningMessage("Boss " + customBossesConfigFields.getFilename() + " has a null location! This is probably due to an incorrectly configured regional location!"); + return; + } + + if (level == -1 && this instanceof RegionalBossEntity) + new WarningMessage("Boss " + getCustomBossesConfigFields().getFilename() + " is regional and has a dynamic level!" + + " This is a terrible idea. Change this as soon as possible!"); + + //This is a bit dumb but -1 is reserved for dynamic levels + if (level == -1) + if (!(this instanceof RegionalBossEntity) || spawnLocation.getWorld() != null) + getDynamicLevel(spawnLocation); + else + level = 1; + + Boolean isChunkLoadedSpawn = null; + + if (chunkLoad || ChunkLocationChecker.locationIsLoaded(spawnLocation) || isMount) { + chunkLoad = false; + super.livingEntity = new CustomBossMegaConsumer(this).spawn(); + setNormalizedHealth(); + isChunkLoadedSpawn = true; + if (super.livingEntity == null) + new WarningMessage("Something just prevented EliteMobs from spawning a Custom Boss! More info up next."); + simplePersistentEntity = null; + } else if (isPersistent) { + if (simplePersistentEntity != null) { + new WarningMessage("Attempted to create more than one SimplePersistentEntity for boss " + customBossesConfigFields.getFilename() + " .", true); + return; + } + simplePersistentEntity = new SimplePersistentEntity(this, getLocation()); + isChunkLoadedSpawn = false; + } + + if (!exists()) { + existsFailureCount++; + //this may seem odd but not setting it to null can cause double spawn attempts as the plugin catches itself + //correctly as not have a valid living entity but the checks are set up in such a way that if a living entity + //object is referenced then trying to spawn it again is a double spawn of the same entity + super.livingEntity = null; + if (existsFailureCount > 10) { + if (existsFailureCount == 11) { + new WarningMessage("EliteMobs tried and failed to spawn " + customBossesConfigFields.getFilename() + " " + existsFailureCount + "times, probably due to regional protections or third party plugin incompatibilities."); + new WarningMessage("To avoid cluttering up console, these warnings will now only appear once 6000 attempts for this boss. "); + } + if (existsFailureCount % 6000 == 0) { + new WarningMessage("EliteMobs tried and failed to spawn " + customBossesConfigFields.getFilename() + " " + existsFailureCount + "times, probably due to regional protections or third party plugin incompatibilities."); + new WarningMessage("To avoid cluttering up console, these warnings will now only appear once 6000 attempts for this boss. "); + } + return; + } + if (existsFailureCount > 1) { + new WarningMessage("EliteMobs tried and failed to spawn " + customBossesConfigFields.getFilename() + " " + existsFailureCount + "times, probably due to regional protections."); + return; + } + new WarningMessage("EliteMobs tried and failed to spawn " + customBossesConfigFields.getFilename() + " . Possible reasons for this:"); + new WarningMessage("- The region was protected by a plugin (most likely)"); + new WarningMessage("- The spawn was interfered with by some incompatible third party plugin"); + new WarningMessage("Debug data: "); + new WarningMessage("Chunk is loaded: " + ChunkLocationChecker.locationIsLoaded(spawnLocation)); + new WarningMessage("Spawn type is normal spawn with chunk loaded: " + isChunkLoadedSpawn); + new WarningMessage("Attempted spawn location: " + spawnLocation.toString(), true); + return; + } + + //It isn't worth initializing things that will notify players or spawn additional entities until we are certain that the boss has actually spawned + if (livingEntity != null) { + startBossTrails(); + mountEntity(); + //Prevent custom bosses from getting removed when far away, this is important for mounts and reinforcements in large arenas + getLivingEntity().setRemoveWhenFarAway(false); + } else + persistentLocation = spawnLocation; + + if (!silent) + announceSpawn(); + + if (summoningEntity != null) + summoningEntity.addReinforcement(this); + + if (spawnLocation.getWorld() != null) + for (ElitePower elitePower : elitePowers) + if (elitePower instanceof CustomSummonPower) + ((CustomSummonPower) elitePower).getCustomBossReinforcements().forEach((customBossReinforcement -> { + if (customBossReinforcement.summonType.equals(CustomSummonPower.SummonType.GLOBAL)) + globalReinforcements.add(CustomSummonPower.summonGlobalReinforcement(customBossReinforcement, this)); + })); + + CommandRunner.runCommandFromList(customBossesConfigFields.getOnSpawnCommands(), new ArrayList<>()); + } + + private void setNormalizedHealth() { + if (normalizedCombat) + super.setNormalizedMaxHealth(); + } + + public void setNormalizedCombat() { + normalizedCombat = true; + if (livingEntity != null) + setNormalizedMaxHealth(); + } + + private void setPluginName() { + if (this.level == -1) + setName(ChatColorConverter.convert(customBossesConfigFields.getName().replace("$level", "?" + "") + .replace("$normalLevel", ChatColorConverter.convert("&2[&a" + "?" + "&2]&f")) + .replace("$minibossLevel", ChatColorConverter.convert("&6〖&e" + "?" + "&6〗&f")) + .replace("$bossLevel", ChatColorConverter.convert("&4『&c" + "?" + "&4』&f")) + .replace("$reinforcementLevel", ChatColorConverter.convert("&8〔&7") + "?" + "&8〕&f") + .replace("$eventBossLevel", ChatColorConverter.convert("&4「&c" + "?" + "&4」&f"))), + false); + else + setName(ChatColorConverter.convert(customBossesConfigFields.getName().replace("$level", this.level + "") + .replace("$normalLevel", ChatColorConverter.convert("&2[&a" + this.level + "&2]&f")) + .replace("$minibossLevel", ChatColorConverter.convert("&6〖&e" + this.level + "&6〗&f")) + .replace("$bossLevel", ChatColorConverter.convert("&4『&c" + this.level + "&4』&f")) + .replace("$reinforcementLevel", ChatColorConverter.convert("&8〔&7") + this.level + "&8〕&f") + .replace("$eventBossLevel", ChatColorConverter.convert("&4「&c" + this.level + "&4」&f"))), + false); + } + + @Override + public void setName(String name, boolean applyToLivingEntity) { + super.setName(name, applyToLivingEntity); + if (isValid() && customModel != null) + customModel.setName(name, true); + } + + @Override + public void setName(EliteMobProperties eliteMobProperties) { + super.setName(eliteMobProperties); + if (isValid() && customModel != null) + customModel.setName(name, DefaultConfig.isAlwaysShowNametags()); + } + + @Override + public void setNameVisible(boolean isVisible) { + //Check if the boss is already dead + if (livingEntity == null) return; + super.setNameVisible(isVisible); + DisguiseEntity.setDisguiseNameVisibility(isVisible, livingEntity); + if (customModel != null && isValid()) + customModel.setNameVisible(isVisible); + } + + public void announceSpawn() { + setTracking(); + spawnMessage(); + startEscapeMechanismDelay(); + } + + private void setTracking() { + if (customBossesConfigFields.getAnnouncementPriority() < 1 || + !MobCombatSettingsConfig.isShowCustomBossLocation() || + customBossesConfigFields.getLocationMessage() == null) + return; + trackableCustomBosses.add(this); + customBossBossBar = new CustomBossBossBar(this); + } + + private void spawnMessage() { + if (customBossesConfigFields.getSpawnMessage() == null) return; + if (customBossesConfigFields.getAnnouncementPriority() < 1) return; + if (getLocation() == null) return; + if (getLocation().getWorld() == null) return; + if (!EventsConfig.isAnnouncementBroadcastWorldOnly()) + Bukkit.broadcastMessage(ChatColorConverter.convert(customBossesConfigFields.getSpawnMessage())); + else + for (Player player : getLocation().getWorld().getPlayers()) + player.sendMessage(ChatColorConverter.convert(customBossesConfigFields.getSpawnMessage())); + if (customBossesConfigFields.getAnnouncementPriority() < 3) return; + new DiscordSRVAnnouncement(ChatColorConverter.convert(customBossesConfigFields.getSpawnMessage())); + } + + public void getDynamicLevel(Location bossLocation) { + int bossLevel = 1; + for (Entity entity : bossLocation.getWorld().getNearbyEntities(bossLocation, Math.max(Bukkit.getViewDistance() * 16, 5 * 16), 256, Bukkit.getViewDistance() * 16D)) + if (entity instanceof Player) + if (ElitePlayerInventory.playerInventories.get(entity.getUniqueId()) != null) + if (ElitePlayerInventory.playerInventories.get(entity.getUniqueId()).getNaturalMobSpawnLevel(true) > bossLevel) + bossLevel = ElitePlayerInventory.playerInventories.get(entity.getUniqueId()).getNaturalMobSpawnLevel(false); + super.setLevel(bossLevel); + } + + private void startBossTrails() { + customBossTrail = new CustomBossTrail(this); + } + + private void mountEntity() { + mount = CustomBossMount.generateMount(this); + } + + private void startEscapeMechanismDelay() { + escapeMechanism = CustomBossEscapeMechanism.startEscape(customBossesConfigFields.getTimeout(), this); + } + + private void cullReinforcements(boolean cullGlobal) { + if (cullGlobal) + globalReinforcementEntities.forEach(customBossEntity -> customBossEntity.remove(RemovalReason.REINFORCEMENT_CULL)); + for (CustomBossEntity customBossEntity : eliteReinforcementEntities) + if (customBossEntity != null) + customBossEntity.remove(RemovalReason.REINFORCEMENT_CULL); + for (Entity entity : nonEliteReinforcementEntities) + if (entity != null) + entity.remove(); + + if (cullGlobal) + globalReinforcements.clear(); + eliteReinforcementEntities.clear(); + nonEliteReinforcementEntities.clear(); + } + + @Override + public Location getLocation() { + if (getLivingEntity() != null) return getLivingEntity().getLocation(); + else return persistentLocation; + } + + public double getDamageModifier(Material material) { + return customBossesConfigFields.getDamageModifier(material); + } + + public void resetLivingEntity(LivingEntity livingEntity, CreatureSpawnEvent.SpawnReason spawnReason) { + super.setLivingEntity(livingEntity, spawnReason); + new CustomBossMegaConsumer(this).applyBossFeatures(livingEntity); + } + + @Override + public boolean exists() { + return super.exists() || simplePersistentEntity != null; + } + + @Override + public void fullHeal() { + if (phaseBossEntity == null || phaseBossEntity.isInFirstPhase()) { + super.fullHeal(); + return; + } + phaseBossEntity.resetToFirstPhase(); + super.damagers.clear(); + } + + @Override + public void remove(RemovalReason removalReason) { + bossTrace.setRemove(removalReason); + if (DebugMessage.isDebugMode()) + if (this instanceof RegionalBossEntity && this.phaseBossEntity != null) + new DebugMessage("Regional + Phase boss removal. Reason: " + removalReason); + if (livingEntity != null) persistentLocation = livingEntity.getLocation(); + //Remove the living entity + super.remove(removalReason); + //Remove things tied to the living entity + if (customBossTrail != null) customBossTrail.terminateTrails(); + if (livingEntityMount != null) livingEntityMount.remove(); + if (customBossMount != null) customBossMount.remove(RemovalReason.REINFORCEMENT_CULL); + if (customBossesConfigFields.isCullReinforcements() || removalReason.equals(RemovalReason.PHASE_BOSS_RESET)) + cullReinforcements(false); + + if (removalReason.equals(RemovalReason.PHASE_BOSS_PHASE_END)) + if (inCombat) + new EventCaller(new EliteMobExitCombatEvent(this, EliteMobExitCombatEvent.EliteMobExitCombatReason.PHASE_SWITCH)); + + boolean bossInstanceEnd = removalReason.equals(RemovalReason.KILL_COMMAND) || + removalReason.equals(RemovalReason.DEATH) || + removalReason.equals(RemovalReason.BOSS_TIMEOUT) || + removalReason.equals(RemovalReason.WORLD_UNLOAD) || + removalReason.equals(RemovalReason.SHUTDOWN) || + removalReason.equals(RemovalReason.ARENA_RESET); + + if (!isPersistent) bossInstanceEnd = true; + + if (bossInstanceEnd) { + if (!(this instanceof RegionalBossEntity)) + EntityTracker.getEliteMobEntities().remove(super.eliteUUID); + new EventCaller(new EliteMobRemoveEvent(this, removalReason)); + if (escapeMechanism != null) Bukkit.getScheduler().cancelTask(escapeMechanism); + trackableCustomBosses.remove(this); + if (simplePersistentEntity != null) { + simplePersistentEntity.remove(); + simplePersistentEntity = null; + } + if (customBossBossBar != null) + customBossBossBar.remove(); + if (!removalReason.equals(RemovalReason.SHUTDOWN) && + !removalReason.equals(RemovalReason.DEATH) && + !removalReason.equals(RemovalReason.ARENA_RESET)) + if (phaseBossEntity != null) + phaseBossEntity.silentReset(); + globalReinforcements.forEach((bukkitTask -> { + if (bukkitTask != null) + bukkitTask.cancel(); + })); + globalReinforcements.clear(); + if (!removalReason.equals(RemovalReason.REINFORCEMENT_CULL)) { + if (summoningEntity != null) + summoningEntity.removeReinforcement(this); + if (customSpawn != null) + customSpawn.setKeepTrying(false); + } + + if (isPersistent && removalReason.equals(RemovalReason.WORLD_UNLOAD)) { + //if the world unloads, the location objects cease to be valid + spawnLocation.setWorld(null); + persistentLocation = spawnLocation; + simplePersistentEntity = new SimplePersistentEntity(this, spawnLocation); + } + + if (customBossesConfigFields.isCullReinforcements()) cullReinforcements(true); + + } else if (removalReason.equals(RemovalReason.CHUNK_UNLOAD)) + //when bosses get removed due to chunk unloads and are persistent they should remain stored + simplePersistentEntity = new SimplePersistentEntity(this, getLocation()); + + } + + @Override + public void chunkLoad() { + if (worldIsLoading) { + worldIsLoading = false; + return; + } + chunkLoad = true; + respawnOverrideLocation = persistentLocation; + spawn(true); + } + + @Override + public void chunkUnload() { + remove(RemovalReason.CHUNK_UNLOAD); + } + + @Override + public void worldLoad() { + worldIsLoading = true; + simplePersistentEntity = null; + Bukkit.getScheduler().runTaskLater(MetadataHandler.PLUGIN, () -> worldIsLoading = false, 1); + if (spawnLocation != null) { + spawnLocation.setWorld(Bukkit.getWorld(worldName)); + spawn(true); + } + } + + @Override + public void worldUnload() { + remove(RemovalReason.WORLD_UNLOAD); + } + + public static class CustomBossEntityEvents implements Listener { + @EventHandler(ignoreCancelled = true) + public void removeSlowEvent(EliteMobEnterCombatEvent eliteMobEnterCombatEvent) { + if (!(eliteMobEnterCombatEvent.getEliteMobEntity() instanceof CustomBossEntity)) return; + if (eliteMobEnterCombatEvent.getEliteMobEntity().getLivingEntity().getPotionEffect(PotionEffectType.SLOW) == null) + return; + if (Objects.requireNonNull(eliteMobEnterCombatEvent.getEliteMobEntity().getLivingEntity().getPotionEffect(PotionEffectType.SLOW)).getAmplifier() == 10) + return; + eliteMobEnterCombatEvent.getEliteMobEntity().getLivingEntity().removePotionEffect(PotionEffectType.SLOW); + } + + @EventHandler(ignoreCancelled = true) + public void onExitCombat(EliteMobExitCombatEvent event) { + if (!(event.getEliteMobEntity() instanceof CustomBossEntity)) return; + if (!((CustomBossEntity) event.getEliteMobEntity()).customBossesConfigFields.isCullReinforcements()) + return; + ((CustomBossEntity) event.getEliteMobEntity()).cullReinforcements(false); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/CustomBossEscapeMechanism.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/CustomBossEscapeMechanism.java new file mode 100644 index 000000000..61d1639a6 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/CustomBossEscapeMechanism.java @@ -0,0 +1,29 @@ +package com.magmaguy.elitemobs.mobconstructor.custombosses; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.internal.RemovalReason; +import com.magmaguy.elitemobs.thirdparty.discordsrv.DiscordSRVAnnouncement; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +public class CustomBossEscapeMechanism { + public static Integer startEscape(int timeout, CustomBossEntity customBossEntity) { + if (timeout < 1) return null; + return Bukkit.getScheduler().scheduleSyncDelayedTask(MetadataHandler.PLUGIN, () -> { + doEscapeMessage(customBossEntity); + }, 20L * 60L * timeout); + } + + public static void doEscapeMessage(CustomBossEntity customBossEntity) { + customBossEntity.remove(RemovalReason.BOSS_TIMEOUT); + if (customBossEntity.customBossesConfigFields.getEscapeMessage() == null) return; + if (customBossEntity.customBossesConfigFields.getEscapeMessage().isEmpty()) return; + if (customBossEntity.customBossesConfigFields.getAnnouncementPriority() < 1) return; + for (Player player : Bukkit.getOnlinePlayers()) + if (player.getWorld().equals(customBossEntity.getLocation().getWorld())) + player.sendMessage(ChatColorConverter.convert(customBossEntity.customBossesConfigFields.getEscapeMessage())); + if (customBossEntity.customBossesConfigFields.getAnnouncementPriority() < 3) return; + new DiscordSRVAnnouncement(ChatColorConverter.convert(customBossEntity.customBossesConfigFields.getEscapeMessage())); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/CustomBossMegaConsumer.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/CustomBossMegaConsumer.java new file mode 100644 index 000000000..ecd13da07 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/CustomBossMegaConsumer.java @@ -0,0 +1,185 @@ +package com.magmaguy.elitemobs.mobconstructor.custombosses; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.EliteMobs; +import com.magmaguy.elitemobs.config.DefaultConfig; +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import com.magmaguy.elitemobs.powers.meta.ElitePower; +import com.magmaguy.elitemobs.thirdparty.libsdisguises.DisguiseEntity; +import com.magmaguy.elitemobs.thirdparty.modelengine.CustomModel; +import com.magmaguy.elitemobs.thirdparty.worldguard.WorldGuardCompatibility; +import com.magmaguy.elitemobs.thirdparty.worldguard.WorldGuardFlagChecker; +import com.magmaguy.elitemobs.thirdparty.worldguard.WorldGuardSpawnEventBypasser; +import com.magmaguy.elitemobs.utils.WarningMessage; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.attribute.Attribute; +import org.bukkit.entity.*; +import org.bukkit.event.entity.CreatureSpawnEvent; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.HashSet; + +public class CustomBossMegaConsumer { + private final CustomBossesConfigFields customBossesConfigFields; + private final HashSet powers; + private final int level; + private final boolean bypassesWorldGuardSpawn; + private final Location spawnLocation; + CustomBossEntity customBossEntity; + + /** + * The objective of this class is to set as many fields as possible as a consumer for spawning a Custom Boss. + *

+ * By setting the values through a consumer, the entity shows up already modified by the time it gets to the spawn event. + * + * @param customBossEntity {@link CustomBossEntity spawning the {@link LivingEntity}} + */ + public CustomBossMegaConsumer(CustomBossEntity customBossEntity) { + this.customBossesConfigFields = customBossEntity.getCustomBossesConfigFields(); + this.customBossEntity = customBossEntity; + if (customBossEntity.getRespawnOverrideLocation() != null) { + this.spawnLocation = customBossEntity.getRespawnOverrideLocation(); + customBossEntity.setRespawnOverrideLocation(null); + } else { + this.spawnLocation = customBossEntity.getSpawnLocation(); + } + this.powers = customBossEntity.getElitePowers(); + this.level = customBossEntity.getLevel(); + this.bypassesWorldGuardSpawn = customBossEntity.getBypassesProtections(); + } + + /** + * Attempts to spawn a {@link CustomBossEntity} whose spawn location has already been set. + * + * @return Whether the spawn succeeded or not. + */ + public LivingEntity spawn() { + if (spawnLocation == null) { + new WarningMessage("Custom Boss Entity " + customBossesConfigFields.getFilename() + " tried to spawn without a valid spawn location getting assigned! Report this to the developer!"); + return null; + } + if (EliteMobs.worldGuardIsEnabled) { + if (!WorldGuardFlagChecker.checkFlag(spawnLocation, WorldGuardCompatibility.getEliteMobsSpawnFlag())) { + new WarningMessage("Attempted to spawn " + customBossesConfigFields.getFilename() + " in location " + + spawnLocation.toString() + " which is protected by WorldGuard with elitemobs-spawning deny! This should not have happened."); + return null; + } + if (bypassesWorldGuardSpawn || customBossEntity instanceof RegionalBossEntity) + WorldGuardSpawnEventBypasser.forceSpawn(); + } + + LivingEntity livingEntity = (LivingEntity) spawnLocation.getWorld().spawn(spawnLocation, + customBossesConfigFields.getEntityType().getEntityClass(), + entity -> applyBossFeatures((LivingEntity) entity)); + customBossEntity.setLivingEntity(livingEntity, CreatureSpawnEvent.SpawnReason.CUSTOM); + return livingEntity; + } + + public void applyBossFeatures(LivingEntity livingEntity) { + for (ElitePower elitePower : powers) + elitePower.applyPowers(livingEntity); + setEquipment(livingEntity); + setBaby(livingEntity); + setFrozen(livingEntity); + setDisguise(livingEntity); + setCustomModel(livingEntity); + setName(livingEntity); + setFollowRange(livingEntity); + setMovementSpeed(livingEntity); + + if (livingEntity.getType().equals(EntityType.ENDER_DRAGON)) { + ((EnderDragon) livingEntity).setPhase(EnderDragon.Phase.CIRCLING); + ((EnderDragon) livingEntity).getDragonBattle().generateEndPortal(false); + } + } + + private void setBaby(LivingEntity livingEntity) { + if (livingEntity instanceof Ageable) + if (customBossesConfigFields.isBaby()) + ((Ageable) livingEntity).setBaby(); + else + ((Ageable) livingEntity).setAdult(); + } + + + private void setDisguise(LivingEntity livingEntity) { + if (customBossesConfigFields.getDisguise() == null || + Bukkit.getPluginManager().isPluginEnabled("ModelEngine") && + customBossesConfigFields.getCustomModel() != null && + !customBossesConfigFields.getCustomModel().isEmpty()) + return; + if (!Bukkit.getPluginManager().isPluginEnabled("LibsDisguises")) return; + try { + DisguiseEntity.disguise(customBossesConfigFields.getDisguise(), livingEntity, customBossesConfigFields.getCustomDisguiseData(), customBossesConfigFields.getFilename()); + } catch (Exception ex) { + new WarningMessage("Failed to load LibsDisguises disguise correctly!"); + } + } + + private void setCustomModel(LivingEntity livingEntity) { + if (!Bukkit.getPluginManager().isPluginEnabled("ModelEngine")) return; + if (customBossesConfigFields.getCustomModel() == null || customBossesConfigFields.getCustomModel().isEmpty()) + return; + try { + customBossEntity.setCustomModel(CustomModel.generateCustomModel(livingEntity, customBossesConfigFields.getCustomModel(), customBossEntity.getName())); + } catch (Exception exception) { + customBossEntity.setCustomModel(null); + new WarningMessage("Failed to initialize Custom Model for Custom Boss " + customBossesConfigFields.getFilename()); + exception.printStackTrace(); + } + } + + private void setFrozen(LivingEntity livingEntity) { + if (!customBossesConfigFields.isFrozen()) return; + livingEntity.getAttribute(Attribute.GENERIC_MOVEMENT_SPEED).setBaseValue(0); + livingEntity.setCollidable(false); + //livingEntity.setGravity(false); + } + + private void setEquipment(LivingEntity livingEntity) { + try { + livingEntity.getEquipment().setHelmet(customBossesConfigFields.getHelmet()); + livingEntity.getEquipment().setChestplate(customBossesConfigFields.getChestplate()); + livingEntity.getEquipment().setLeggings(customBossesConfigFields.getLeggings()); + livingEntity.getEquipment().setBoots(customBossesConfigFields.getBoots()); + livingEntity.getEquipment().setItemInMainHand(customBossesConfigFields.getMainHand()); + livingEntity.getEquipment().setItemInOffHand(customBossesConfigFields.getOffHand()); + if (livingEntity.getEquipment().getHelmet() != null) { + ItemMeta helmetMeta = livingEntity.getEquipment().getHelmet().getItemMeta(); + if (helmetMeta != null) { + helmetMeta.setUnbreakable(true); + livingEntity.getEquipment().getHelmet().setItemMeta(helmetMeta); + } + } + } catch (Exception ex) { + new WarningMessage("Tried to assign a material slot to an invalid entity! Boss is from file" + customBossesConfigFields.getFilename()); + } + } + + private void setName(LivingEntity livingEntity) { + String parsedName = ChatColorConverter.convert(customBossesConfigFields.getName().replace("$level", this.level + "") + .replace("$normalLevel", ChatColorConverter.convert("&2[&a" + this.level + "&2]&f")) + .replace("$minibossLevel", ChatColorConverter.convert("&6〖&e" + this.level + "&6〗&f")) + .replace("$bossLevel", ChatColorConverter.convert("&4『&c" + this.level + "&4』&f")) + .replace("$reinforcementLevel", ChatColorConverter.convert("&8〔&7") + this.level + "&8〕&f") + .replace("$eventBossLevel", ChatColorConverter.convert("&4「&c" + this.level + "&4」&f"))); + livingEntity.setCustomName(parsedName); + livingEntity.setCustomNameVisible(DefaultConfig.isAlwaysShowNametags()); + DisguiseEntity.setDisguiseNameVisibility(DefaultConfig.isAlwaysShowNametags(), livingEntity); + customBossEntity.setName(parsedName, false); + } + + private void setFollowRange(LivingEntity livingEntity) { + if (customBossesConfigFields.getFollowDistance() != null && + customBossesConfigFields.getFollowDistance() > 0 && + livingEntity instanceof Mob) + livingEntity.getAttribute(Attribute.GENERIC_FOLLOW_RANGE).setBaseValue(customBossesConfigFields.getFollowDistance()); + } + + private void setMovementSpeed(LivingEntity livingEntity) { + if (customBossesConfigFields.getMovementSpeedAttribute() != null) + livingEntity.getAttribute(Attribute.GENERIC_MOVEMENT_SPEED).setBaseValue(customBossesConfigFields.getMovementSpeedAttribute()); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/CustomBossMount.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/CustomBossMount.java new file mode 100644 index 000000000..9ae67fd29 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/CustomBossMount.java @@ -0,0 +1,60 @@ +package com.magmaguy.elitemobs.mobconstructor.custombosses; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.combatsystem.antiexploit.PreventMountExploit; +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfig; +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import com.magmaguy.elitemobs.utils.WarningMessage; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.scheduler.BukkitRunnable; + +public class CustomBossMount { + private CustomBossMount() { + } + + public static CustomBossEntity generateMount(CustomBossEntity customBossEntity) { + if (customBossEntity.customBossesConfigFields.getMountedEntity() == null) return null; + try { + EntityType entityType = EntityType.valueOf(customBossEntity.customBossesConfigFields.getMountedEntity()); + LivingEntity livingEntity = (LivingEntity) customBossEntity.getLivingEntity().getWorld() + .spawnEntity(customBossEntity.getLivingEntity().getLocation(), entityType); + PreventMountExploit.bypass = true; + livingEntity.addPassenger(customBossEntity.getLivingEntity()); + livingEntity.setRemoveWhenFarAway(false); + customBossEntity.livingEntityMount = livingEntity; + + } catch (Exception ex) { + //This runs when it's not an API entity + CustomBossesConfigFields customBossesConfigFields = CustomBossesConfig.getCustomBoss(customBossEntity.customBossesConfigFields.getMountedEntity()); + if (customBossesConfigFields != null) { + CustomBossEntity mountEntity = CustomBossEntity.createCustomBossEntity(customBossEntity.customBossesConfigFields.getMountedEntity()); + if (mountEntity == null) { + new WarningMessage("Mount for boss " + customBossEntity.getCustomBossesConfigFields().getFilename() + " is not valid!"); + return null; + } + mountEntity.setSpawnLocation(customBossEntity.getLivingEntity().getLocation()); + mountEntity.setBypassesProtections(customBossEntity.getBypassesProtections()); + mountEntity.setPersistent(false); + mountEntity.setMount(true); + mountEntity.spawn(false); + + new BukkitRunnable() { + @Override + public void run() { + if (!mountEntity.isValid()) + return; + PreventMountExploit.bypass = true; + mountEntity.getLivingEntity().addPassenger(customBossEntity.getLivingEntity()); + customBossEntity.customBossMount = mountEntity; + } + }.runTaskLater(MetadataHandler.PLUGIN, 5); + return mountEntity; + } + + new WarningMessage("Attempted to make Custom Boss " + customBossEntity.customBossesConfigFields.getFilename() + " mount invalid" + + " entity or boss " + customBossEntity.customBossesConfigFields.getMountedEntity() + " . Fix this in the configuration file."); + } + return null; + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/CustomBossTaunts.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/CustomBossTaunts.java new file mode 100644 index 000000000..afa403a03 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/CustomBossTaunts.java @@ -0,0 +1,27 @@ +package com.magmaguy.elitemobs.mobconstructor.custombosses; + +import com.magmaguy.elitemobs.api.EliteMobDamagedEvent; +import com.magmaguy.elitemobs.api.PlayerDamagedByEliteMobEvent; +import com.magmaguy.elitemobs.powers.miscellaneouspowers.Taunt; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; + +public class CustomBossTaunts implements Listener { + @EventHandler + public void onDamagedMessages(EliteMobDamagedEvent eliteMobDamagedEvent) { + if (!(eliteMobDamagedEvent.getEliteMobEntity() instanceof CustomBossEntity)) return; + if (((CustomBossEntity) eliteMobDamagedEvent.getEliteMobEntity()).getCustomBossesConfigFields().getOnDamagedMessages().isEmpty()) + return; + Taunt.nameTagProcessor(eliteMobDamagedEvent.getEliteMobEntity(), eliteMobDamagedEvent.getEliteMobEntity().getLivingEntity(), + ((CustomBossEntity) eliteMobDamagedEvent.getEliteMobEntity()).getCustomBossesConfigFields().getOnDamagedMessages()); + } + + @EventHandler + public void onDamageMessages(PlayerDamagedByEliteMobEvent playerDamagedByEliteMobEvent) { + if (!(playerDamagedByEliteMobEvent.getEliteMobEntity() instanceof CustomBossEntity)) return; + if (((CustomBossEntity) playerDamagedByEliteMobEvent.getEliteMobEntity()).getCustomBossesConfigFields().getOnDamageMessages().isEmpty()) + return; + Taunt.nameTagProcessor(playerDamagedByEliteMobEvent.getEliteMobEntity(), playerDamagedByEliteMobEvent.getEliteMobEntity().getLivingEntity(), + ((CustomBossEntity) playerDamagedByEliteMobEvent.getEliteMobEntity()).getCustomBossesConfigFields().getOnDamageMessages()); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/CustomBossTrail.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/CustomBossTrail.java new file mode 100644 index 000000000..c6b14a35e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/CustomBossTrail.java @@ -0,0 +1,108 @@ +package com.magmaguy.elitemobs.mobconstructor.custombosses; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.internal.RemovalReason; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.powerstances.VisualItemInitializer; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import com.magmaguy.elitemobs.utils.VersionChecker; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Particle; +import org.bukkit.entity.Item; +import org.bukkit.entity.LivingEntity; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scheduler.BukkitTask; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.concurrent.ThreadLocalRandom; + +public class CustomBossTrail { + + private final CustomBossEntity customBossEntity; + private final ArrayList bukkitTasks = new ArrayList<>(); + private LivingEntity livingEntity; + + public CustomBossTrail(CustomBossEntity customBossEntity) { + this.customBossEntity = customBossEntity; + this.livingEntity = customBossEntity.getLivingEntity(); + startBossTrails(); + } + + private void startBossTrails() { + if (customBossEntity.customBossesConfigFields.getTrails() == null) return; + for (String string : customBossEntity.customBossesConfigFields.getTrails()) { + try { + Particle particle = Particle.valueOf(string); + doParticleTrail(particle); + } catch (Exception ex) { + } + try { + Material material = Material.valueOf(string); + doItemTrail(material); + } catch (Exception ex) { + } + } + } + + private void doParticleTrail(Particle particle) { + if (!VersionChecker.serverVersionOlderThan(18, 0) && particle.equals(Particle.BLOCK_MARKER)) + return; + bukkitTasks.add(new BukkitRunnable() { + @Override + public void run() { + //In case of boss death or chunk unload, stop the effect + if (!livingEntity.isValid()) { + cancel(); + return; + } + //All conditions cleared, do the boss flair effect + Location entityCenter = livingEntity.getLocation().clone().add(0, livingEntity.getHeight() / 2, 0); + livingEntity.getWorld().spawnParticle(particle, entityCenter, 1, 0.1, 0.1, 0.1, 0.05); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1)); + } + + private void doItemTrail(Material material) { + bukkitTasks.add(new BukkitRunnable() { + + @Override + public void run() { + //In case of boss death, stop the effect + if (!livingEntity.isValid()) { + cancel(); + return; + } + //All conditions cleared, do the boss flair effect + Location entityCenter = livingEntity.getLocation().clone().add(0, livingEntity.getHeight() / 2, 0); + Item item = VisualItemInitializer.initializeItem(ItemStackGenerator.generateItemStack + (material, "visualItem", Arrays.asList(ThreadLocalRandom.current().nextDouble() + "")), entityCenter); + item.setVelocity(new Vector( + ThreadLocalRandom.current().nextDouble() / 5 - 0.10, + ThreadLocalRandom.current().nextDouble() / 5 - 0.10, + ThreadLocalRandom.current().nextDouble() / 5 - 0.10)); + new BukkitRunnable() { + @Override + public void run() { + item.remove(); + EntityTracker.unregister(item, RemovalReason.EFFECT_TIMEOUT); + } + }.runTaskLater(MetadataHandler.PLUGIN, 20); + + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 5)); + } + + public void terminateTrails() { + for (BukkitTask bukkitTask : bukkitTasks) bukkitTask.cancel(); + bukkitTasks.clear(); + } + + public void restartTrails() { + this.livingEntity = customBossEntity.getLivingEntity(); + startBossTrails(); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/ElitePowerParser.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/ElitePowerParser.java new file mode 100644 index 000000000..20922af99 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/ElitePowerParser.java @@ -0,0 +1,42 @@ +package com.magmaguy.elitemobs.mobconstructor.custombosses; + +import com.magmaguy.elitemobs.powers.bosspowers.BonusCoins; +import com.magmaguy.elitemobs.powers.meta.CustomSummonPower; +import com.magmaguy.elitemobs.powers.meta.ElitePower; +import com.magmaguy.elitemobs.utils.WarningMessage; + +import java.util.HashSet; +import java.util.List; + +public class ElitePowerParser { + + public static HashSet parsePowers(List powers) { + HashSet elitePowers = new HashSet<>(); + CustomSummonPower customSummonPower = null; + for (String powerName : powers) { + if (powerName.split(":")[0].equalsIgnoreCase("summon") + || powerName.split(":")[0].equalsIgnoreCase("summonable")) + if (customSummonPower == null) { + customSummonPower = new CustomSummonPower(powerName); + elitePowers.add(customSummonPower); + } else + customSummonPower.addEntry(powerName); + else { + String[] parsedPowerName = powerName.split(":"); + if (ElitePower.getElitePower(parsedPowerName[0]) != null) { + ElitePower elitePower = ElitePower.getElitePower(parsedPowerName[0]); + elitePowers.add(elitePower); + if (elitePower instanceof BonusCoins) + if (parsedPowerName.length > 1) + try { + ((BonusCoins) elitePower).setCoinMultiplier(Double.parseDouble(parsedPowerName[1])); + } catch (Exception ex) { + new WarningMessage("Multiplier " + parsedPowerName[1] + " for Bonus Coins power is not a valid multiplier!"); + } + } else + new WarningMessage("Warning: power name " + powerName + " is not registered! Skipping it for custom mob construction..."); + } + } + return elitePowers; + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/PhaseBossEntity.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/PhaseBossEntity.java new file mode 100644 index 000000000..f190cbf2e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/PhaseBossEntity.java @@ -0,0 +1,122 @@ +package com.magmaguy.elitemobs.mobconstructor.custombosses; + +import com.magmaguy.elitemobs.api.EliteMobDamagedEvent; +import com.magmaguy.elitemobs.api.EliteMobDeathEvent; +import com.magmaguy.elitemobs.api.internal.RemovalReason; +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfig; +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import com.magmaguy.elitemobs.utils.WarningMessage; +import lombok.Getter; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; + +import java.util.ArrayList; +import java.util.List; + +public class PhaseBossEntity { + + private final CustomBossEntity customBossEntity; + @Getter + private List bossPhases = new ArrayList(); + private BossPhase currentPhase = null; + + public PhaseBossEntity(CustomBossEntity customBossEntity) { + this.customBossEntity = customBossEntity; + try { + ArrayList unsortedBossPhases = new ArrayList<>(); + unsortedBossPhases.add(new BossPhase(customBossEntity.getCustomBossesConfigFields(), 1)); + for (String phaseConfigFile : customBossEntity.getCustomBossesConfigFields().getPhases()) { + CustomBossesConfigFields customBossesConfigFields = CustomBossesConfig.getCustomBoss(phaseConfigFile.split(":")[0]); + if (customBossesConfigFields == null) { + new WarningMessage("Phase boss " + customBossEntity.getCustomBossesConfigFields() + " has an invalid config entry for phase " + phaseConfigFile + " - this file could not be found. The boss will not be able to do this phase until it is fixed!"); + } + double healthPercentage = Double.parseDouble(phaseConfigFile.split(":")[1]); + unsortedBossPhases.add(new BossPhase(customBossesConfigFields, healthPercentage)); + } + unsortedBossPhases.sort((o1, o2) -> (int) (o2.healthPercentage * 100 - o1.healthPercentage * 100)); + this.bossPhases = unsortedBossPhases; + currentPhase = bossPhases.get(0); + } catch (Exception ex) { + new WarningMessage("Your phase boss " + customBossEntity.customBossesConfigFields.getFilename() + " does not have a valid phases setup. Its phases will not work."); + } + } + + public boolean isInFirstPhase() { + return bossPhases.get(0).equals(currentPhase); + } + + private void switchPhase(BossPhase bossPhase, RemovalReason removalReason, double healthPercentage) { + if (bossPhase.equals(currentPhase)) { + new WarningMessage("Attempted to change the boss phase to what it already was.", true); + return; + } + customBossEntity.remove(removalReason); + if (bossPhase.customBossesConfigFields == null) { + new WarningMessage("A phase for phase boss " + bossPhases.get(0).customBossesConfigFields.getFilename() + " was not valid! The boss will not be able to switch phases until it is fixed."); + return; + } + customBossEntity.setCustomBossesConfigFields(bossPhase.customBossesConfigFields); + if (removalReason.equals(RemovalReason.PHASE_BOSS_RESET)) { + customBossEntity.spawn(true); + } else { + customBossEntity.setRespawnOverrideLocation(customBossEntity.getLocation()); + customBossEntity.spawn(true); + } + customBossEntity.setHealth(customBossEntity.getMaxHealth() * healthPercentage); + currentPhase = bossPhase; + if (customBossEntity.getCustomModel() != null) customBossEntity.getCustomModel().switchPhase(); + } + + public void resetToFirstPhase() { + switchPhase(bossPhases.get(0), RemovalReason.PHASE_BOSS_RESET, 1); + } + + public void silentReset() { + currentPhase = bossPhases.get(0); + customBossEntity.setCustomBossesConfigFields(currentPhase.customBossesConfigFields); + } + + /** + * Used to set the respawn time in the config file of Regional Bosses + * + * @return The configuration file for phase 1 of Phase Bosses + */ + public CustomBossesConfigFields getPhase1Config() { + return bossPhases.get(0).customBossesConfigFields; + } + + public void checkPhaseBossSwitch() { + if (bossPhases.indexOf(currentPhase) + 1 >= bossPhases.size()) return; + BossPhase nextBossPhase = bossPhases.get(bossPhases.indexOf(currentPhase) + 1); + if (customBossEntity.getHealth() / customBossEntity.getMaxHealth() > nextBossPhase.healthPercentage) return; + switchPhase(nextBossPhase, RemovalReason.PHASE_BOSS_PHASE_END, customBossEntity.getHealth() / customBossEntity.getMaxHealth()); + } + + public static class PhaseBossEntityListener implements Listener { + @EventHandler(ignoreCancelled = true) + public void onEliteDamaged(EliteMobDamagedEvent event) { + if (!(event.getEliteMobEntity() instanceof CustomBossEntity)) return; + if (((CustomBossEntity) event.getEliteMobEntity()).getPhaseBossEntity() == null) return; + ((CustomBossEntity) event.getEliteMobEntity()).getPhaseBossEntity().checkPhaseBossSwitch(); + } + + @EventHandler(priority = EventPriority.MONITOR) + public void onEliteDeath(EliteMobDeathEvent event) { + if (!(event.getEliteEntity() instanceof CustomBossEntity)) return; + CustomBossEntity customBossEntity = (CustomBossEntity) event.getEliteEntity(); + if (customBossEntity.getPhaseBossEntity() != null) + customBossEntity.phaseBossEntity.silentReset(); + } + } + + public class BossPhase { + public CustomBossesConfigFields customBossesConfigFields; + public double healthPercentage; + + public BossPhase(CustomBossesConfigFields customBossesConfigFields, double healthPercentage) { + this.customBossesConfigFields = customBossesConfigFields; + this.healthPercentage = healthPercentage; + } + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/RegionalBossEntity.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/RegionalBossEntity.java new file mode 100644 index 000000000..a738142fa --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/RegionalBossEntity.java @@ -0,0 +1,283 @@ +package com.magmaguy.elitemobs.mobconstructor.custombosses; + +import com.google.common.collect.ArrayListMultimap; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.internal.NewMinidungeonRelativeBossLocationEvent; +import com.magmaguy.elitemobs.api.internal.RemovalReason; +import com.magmaguy.elitemobs.config.ItemSettingsConfig; +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfig; +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.SimplePersistentEntityInterface; +import com.magmaguy.elitemobs.mobconstructor.custombosses.transitiveblocks.TransitiveBlock; +import com.magmaguy.elitemobs.powers.bosspowers.SpiritWalk; +import com.magmaguy.elitemobs.utils.ConfigurationLocation; +import com.magmaguy.elitemobs.utils.WarningMessage; +import lombok.Getter; +import lombok.Setter; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scheduler.BukkitTask; + +import javax.annotation.Nullable; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Objects; + +public class RegionalBossEntity extends CustomBossEntity implements SimplePersistentEntityInterface { + + private static final ArrayListMultimap regionalBossesFromConfigFields = ArrayListMultimap.create(); + private final double leashRadius; + //Format: worldName,x,y,z,pitch,yaw:unixTimeForRespawn + private String rawString; + private String rawLocationString; + private long ticksBeforeRespawn = 0; + private long unixRespawnTime; + private int respawnCoolDownInMinutes = 0; + private boolean isRespawning = false; + private BukkitTask leashTask; + @Getter + @Setter + private List onSpawnTransitiveBlocks; + @Getter + @Setter + private List onRemoveTransitiveBlocks; + private boolean leashIsRunning = false; + + + public RegionalBossEntity(CustomBossesConfigFields customBossesConfigFields, String rawString) { + super(customBossesConfigFields); + this.rawString = rawString; + this.rawLocationString = rawString.split(":")[0]; + this.respawnCoolDownInMinutes = customBossesConfigFields.getSpawnCooldown(); + this.leashRadius = customBossesConfigFields.getLeashRadius(); + this.onSpawnTransitiveBlocks = TransitiveBlock.serializeTransitiveBlocks(customBossesConfigFields.getOnSpawnBlockStates(), customBossesConfigFields.getFilename()); + this.onRemoveTransitiveBlocks = TransitiveBlock.serializeTransitiveBlocks(customBossesConfigFields.getOnRemoveBlockStates(), customBossesConfigFields.getFilename()); + + regionalBossesFromConfigFields.put(customBossesConfigFields, this); + + unixRespawnTime = 0; + if (rawString.contains(":")) + unixRespawnTime = Long.parseLong(rawString.split(":")[1]); + ticksBeforeRespawn = 0; + if (unixRespawnTime > 0) + ticksBeforeRespawn = (unixRespawnTime - System.currentTimeMillis()) / 1000 * 20 < 0 ? + 0 : (unixRespawnTime - System.currentTimeMillis()) / 1000 * 20; + super.worldName = rawLocationString.split(",")[0]; + super.spawnLocation = ConfigurationLocation.serialize(rawLocationString); + + super.setPersistent(true); + } + + public RegionalBossEntity(CustomBossesConfigFields customBossesConfigFields, Location location, boolean permanent) { + super(customBossesConfigFields); + this.onSpawnTransitiveBlocks = TransitiveBlock.serializeTransitiveBlocks(customBossesConfigFields.getOnSpawnBlockStates(), customBossesConfigFields.getFilename()); + this.onRemoveTransitiveBlocks = TransitiveBlock.serializeTransitiveBlocks(customBossesConfigFields.getOnRemoveBlockStates(), customBossesConfigFields.getFilename()); + this.onSpawnTransitiveBlocks = TransitiveBlock.serializeTransitiveBlocks(customBossesConfigFields.getOnSpawnBlockStates(), customBossesConfigFields.getFilename()); + this.onRemoveTransitiveBlocks = TransitiveBlock.serializeTransitiveBlocks(customBossesConfigFields.getOnRemoveBlockStates(), customBossesConfigFields.getFilename()); + super.setPersistent(permanent); + super.spawnLocation = location; + this.leashRadius = customBossesConfigFields.getLeashRadius(); + if (permanent) { + this.rawString = ConfigurationLocation.deserialize(location); + this.rawLocationString = rawString.split(":")[0]; + this.unixRespawnTime = 0; + this.respawnCoolDownInMinutes = customBossesConfigFields.getSpawnCooldown(); + regionalBossesFromConfigFields.put(customBossesConfigFields, this); + saveNewLocation(); + } + } + + public static void regionalBossesShutdown() { + regionalBossesFromConfigFields.clear(); + } + + public static List getRegionalBossEntities(CustomBossesConfigFields customBossesConfigFields) { + return regionalBossesFromConfigFields.get(customBossesConfigFields); + } + + public static Collection getRegionalBossEntities() { + return regionalBossesFromConfigFields.values(); + } + + public static void regionalDataSaver() { + new BukkitRunnable() { + @Override + public void run() { + save(); + } + }.runTaskTimerAsynchronously(MetadataHandler.PLUGIN, 20L * 5, 20L * 5); + } + + public static void save() { + for (CustomBossesConfigFields customBossesConfigFields : regionalBossesFromConfigFields.keySet()) { + if (!customBossesConfigFields.isFilesOutOfSync()) continue; + customBossesConfigFields.setFilesOutOfSync(false); + List spawnLocations = new ArrayList<>(); + for (RegionalBossEntity regionalBossEntity : regionalBossesFromConfigFields.get(customBossesConfigFields)) + spawnLocations.add(regionalBossEntity.rawString); + customBossesConfigFields.getFileConfiguration().set("spawnLocations", spawnLocations); + try { + customBossesConfigFields.getFileConfiguration().save(customBossesConfigFields.getFile()); + } catch (Exception ex) { + new WarningMessage("Failed to save respawn timer for " + customBossesConfigFields.getFileConfiguration().getName() + " !"); + } + } + } + + public static RegionalBossEntity getRegionalBoss(CustomBossesConfigFields customBossesConfigFields, Location spawnLocation) { + for (RegionalBossEntity regionalBossEntity : regionalBossesFromConfigFields.get(customBossesConfigFields)) + if (Objects.equals(regionalBossEntity.getSpawnLocation(), spawnLocation)) + return regionalBossEntity; + return null; + } + + public static List getRegionalBossEntitySet() { + return new ArrayList<>(regionalBossesFromConfigFields.values()); + } + + @Nullable + public static RegionalBossEntity createTemporaryRegionalBossEntity(String filename, Location spawnLocation) { + CustomBossesConfigFields customBossesConfigFields = CustomBossesConfig.getCustomBoss(filename); + if (customBossesConfigFields == null) + return null; + return new RegionalBossEntity(customBossesConfigFields, spawnLocation, false); + } + + public static RegionalBossEntity createPermanentRegionalBossEntity(CustomBossesConfigFields customBossesConfigFields, Location spawnLocation) { + RegionalBossEntity regionalBossEntity = new RegionalBossEntity(customBossesConfigFields, spawnLocation, true); + regionalBossEntity.initialize(); + return regionalBossEntity; + } + + public boolean isRespawning() { + return isRespawning; + } + + public void saveNewLocation() { + if (spawnLocation == null) { + new WarningMessage("Failed to save regional boss because it failed to spawn correctly!"); + } + customBossesConfigFields.setFilesOutOfSync(true); + rawString = ConfigurationLocation.deserialize(spawnLocation); + } + + public void initialize() { + queueSpawn(false); + } + + public void queueSpawn(boolean silent) { + RegionalBossEntity regionalBossEntity = this; + this.isRespawning = true; + Bukkit.getScheduler().scheduleSyncDelayedTask(MetadataHandler.PLUGIN, () -> { + if (phaseBossEntity != null) phaseBossEntity.silentReset(); + ticksBeforeRespawn = 0; + //Reminder: this might not spawn a living entity as it gets queued for when the chunk loads + regionalBossEntity.spawn(silent); + super.getDamagers().clear(); + }, ticksBeforeRespawn); + } + + public void respawn() { + this.isRespawning = true; + unixRespawnTime = (respawnCoolDownInMinutes * 60L * 1000L) + System.currentTimeMillis(); + ticksBeforeRespawn = respawnCoolDownInMinutes * 60L * 20L; + rawString = rawLocationString + ":" + unixRespawnTime; + if (phaseBossEntity != null) + phaseBossEntity.getPhase1Config().setFilesOutOfSync(true); + else + customBossesConfigFields.setFilesOutOfSync(true); + queueSpawn(false); + } + + public void checkLeash() { + if (leashRadius < 1) + return; + RegionalBossEntity regionalBossEntity = this; + if (leashIsRunning) return; + leashIsRunning = true; + leashTask = Bukkit.getScheduler().runTaskTimerAsynchronously(MetadataHandler.PLUGIN, () -> { + try { + if (!isValid()) { + cancelLeash(); + return; + } + if (getLivingEntity().getLocation().distanceSquared(spawnLocation) > Math.pow(leashRadius, 2)) + SpiritWalk.spiritWalkRegionalBossAnimation(regionalBossEntity, getLivingEntity().getLocation(), spawnLocation); + + } catch (Exception ex) { + new WarningMessage("Async leash task errored!"); + } + }, 20L * 3, 20L * 3); + } + + private void cancelLeash() { + if (leashTask == null) return; + leashTask.cancel(); + leashIsRunning = false; + } + + public void setLeashRadius(int leashRadius) { + getCustomBossesConfigFields().setLeashRadius(leashRadius); + getCustomBossesConfigFields().setFilesOutOfSync(true); + } + + @Override + public void spawn(boolean silent) { + super.spawn(silent); + this.isRespawning = false; + if (!ItemSettingsConfig.isRegionalBossesDropVanillaLoot()) + super.vanillaLoot = false; + if (livingEntity != null) { + checkLeash(); + getLivingEntity().addPotionEffect(new PotionEffect(PotionEffectType.SLOW, Integer.MAX_VALUE, 4)); + } + } + + @Override + public void remove(RemovalReason removalReason) { + cancelLeash(); + + super.remove(removalReason); + + switch (removalReason) { + case REMOVE_COMMAND: + if (phaseBossEntity != null) + phaseBossEntity.silentReset(); + EntityTracker.getEliteMobEntities().remove(super.eliteUUID); + regionalBossesFromConfigFields.remove(customBossesConfigFields, this); + getCustomBossesConfigFields().setFilesOutOfSync(true); + break; + case DEATH: + case BOSS_TIMEOUT: + respawn(); + break; + default: + break; + } + } + + /** + * Runs on chunk load. Should start repeating tasks that rely on the boss being loaded. + */ + @Override + public void chunkLoad() { + super.chunkLoad(); + checkLeash(); + } + + public static class RegionalBossEntityEvents implements Listener { + @EventHandler(ignoreCancelled = true) + public void onNewMinidungeonRelativeBossLocationEvent(NewMinidungeonRelativeBossLocationEvent event) { + new RegionalBossEntity(event.getCustomBossConfigFields(), ConfigurationLocation.deserialize(event.getRealLocation())); + event.getCustomBossConfigFields().setFilesOutOfSync(true); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/transitiveblocks/TransitiveBlock.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/transitiveblocks/TransitiveBlock.java new file mode 100644 index 000000000..340f2f6e8 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/transitiveblocks/TransitiveBlock.java @@ -0,0 +1,46 @@ +package com.magmaguy.elitemobs.mobconstructor.custombosses.transitiveblocks; + +import com.magmaguy.elitemobs.utils.WarningMessage; +import lombok.Getter; +import lombok.Setter; +import org.bukkit.Bukkit; +import org.bukkit.block.data.BlockData; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.List; + + +public class TransitiveBlock { + + @Getter + private BlockData blockData; + @Getter + private Vector relativeLocation; + @Getter + @Setter + private boolean isAir; + + public TransitiveBlock(BlockData blockData, Vector relativeLocation) { + this.blockData = blockData; + this.relativeLocation = relativeLocation; + } + + public static List serializeTransitiveBlocks(List deserializedList, String filename) { + List transitiveBlocks = new ArrayList<>(); + for (String deserializedString : deserializedList) { + try { + String[] elements = deserializedString.split("/"); + String[] vector = elements[0].split(","); + double x = Double.parseDouble(vector[0]); + double y = Double.parseDouble(vector[1]); + double z = Double.parseDouble(vector[2]); + BlockData blockData = Bukkit.getServer().createBlockData(elements[1]); + transitiveBlocks.add(new TransitiveBlock(blockData, new Vector(x, y, z))); + } catch (Exception ex) { + new WarningMessage("Failed to serialize Transitive Block! Issue with entry " + deserializedString + " in file " + filename); + } + } + return transitiveBlocks; + } +} \ No newline at end of file diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/transitiveblocks/TransitiveBlockCommand.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/transitiveblocks/TransitiveBlockCommand.java new file mode 100644 index 000000000..97e3bb341 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/transitiveblocks/TransitiveBlockCommand.java @@ -0,0 +1,277 @@ +package com.magmaguy.elitemobs.mobconstructor.custombosses.transitiveblocks; + +import com.magmaguy.elitemobs.config.DefaultConfig; +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfig; +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import com.magmaguy.elitemobs.mobconstructor.custombosses.PhaseBossEntity; +import com.magmaguy.elitemobs.mobconstructor.custombosses.RegionalBossEntity; +import com.magmaguy.elitemobs.utils.WarningMessage; +import lombok.Getter; +import lombok.Setter; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.Action; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class TransitiveBlockCommand { + + public static HashMap activePlayers = new HashMap<>(); + private Player player; + private CustomBossesConfigFields customBossesConfigFields; + private List transitiveBlockList = new ArrayList<>(); + private TransitiveBlockType transitiveBlockType; + private RegionalBossEntity regionalBossEntity; + @Getter + @Setter + private boolean regionalSelection = false; + private Location corner1, corner2; + + public TransitiveBlockCommand(Player player, CustomBossesConfigFields customBossesConfigFields, TransitiveBlockType transitiveBlockType, boolean edit) { + this.player = player; + this.customBossesConfigFields = customBossesConfigFields; + this.transitiveBlockType = transitiveBlockType; + List regionalBossEntities = RegionalBossEntity.getRegionalBossEntities(customBossesConfigFields); + if (regionalBossEntities.isEmpty()) { + //check phase bosses + for (RegionalBossEntity iteratedRegionalBossEntity : RegionalBossEntity.getRegionalBossEntitySet()) + if (iteratedRegionalBossEntity.getPhaseBossEntity() != null) + for (PhaseBossEntity.BossPhase bossPhase : iteratedRegionalBossEntity.getPhaseBossEntity().getBossPhases()) { + if (bossPhase.customBossesConfigFields == null) { + String message = "Could not find valid custom boss config fields for phase boss! This is probably a configuration issue. Check why your phase boss isn't valid on console logs on /em reload and make sure to test the phases in-game!"; + new WarningMessage(message); + player.sendMessage(message); + } + if (bossPhase.customBossesConfigFields.equals(customBossesConfigFields)) { + this.regionalBossEntity = iteratedRegionalBossEntity; + break; + } + } + if (this.regionalBossEntity == null) { + player.sendMessage(ChatColor.RED + "[EliteMobs] Transitive blocks require one Regional Boss from the configuration files to be placed in order to add transitive blocks relative to the spawn coordinates of that boss."); + player.sendMessage(ChatColor.RED + "[EliteMobs] Cancelling block registration!"); + return; + } + } + + if (this.regionalBossEntity == null) { + if (regionalBossEntities.size() > 1) { + player.sendMessage(ChatColor.RED + "[EliteMobs] Transitive blocks require having ONLY one Regional Boss from the configuration files to be placed in order to add transitive blocks relative to the spawn coordinates of that boss." + + " If there is more than one boss, the plugin can't determine which boss specifically should be getting the transitive blocks"); + player.sendMessage(ChatColor.RED + "[EliteMobs] If want multiple bosses to have transitive blocks, you will need one configuration file per boss that has them!"); + player.sendMessage(ChatColor.RED + "[EliteMobs] Cancelling block registration!"); + return; + } + this.regionalBossEntity = regionalBossEntities.get(0); + } + + if (edit) + switch (transitiveBlockType) { + case ON_SPAWN: + transitiveBlockList = TransitiveBlock.serializeTransitiveBlocks(customBossesConfigFields.getOnSpawnBlockStates(), customBossesConfigFields.getFilename()); + break; + case ON_REMOVE: + transitiveBlockList = TransitiveBlock.serializeTransitiveBlocks(customBossesConfigFields.getOnRemoveBlockStates(), customBossesConfigFields.getFilename()); + } + + + activePlayers.put(player, this); + player.sendMessage(ChatColor.GREEN + "[EliteMobs] Now registering " + transitiveBlockType.toString() + " blocks! " + ChatColor.DARK_GREEN + "Punch blocks to register air at that location, or right click blocks to register the block you right clicked!"); + player.sendMessage(ChatColor.GOLD + "[EliteMobs] Run the same command to stop registering blocks and save!"); + player.sendMessage(ChatColor.GOLD + "[EliteMobs] Or run the command " + "/em cancelblocks " + " to cancel the registration!"); + } + + public static TransitiveBlockCommand processCommand(Player player, String filename, String transitiveBlockType, boolean edit, boolean regionalSelection) { + TransitiveBlockCommand transitiveBlockCommand = processCommand(player, filename, transitiveBlockType, edit); + if (transitiveBlockCommand != null) + transitiveBlockCommand.setRegionalSelection(regionalSelection); + if (transitiveBlockCommand != null) + player.sendMessage("[EliteMobs] Now registering large selection for transitive blocks! Left click to set corner 1, right click to set corner 2! Run the same command again to stop registering blocks and run /em cancelblocks to cancel!"); + return transitiveBlockCommand; + } + + public static TransitiveBlockCommand processCommand(Player player, String filename, String transitiveBlockType, boolean edit) { + CustomBossesConfigFields customBossesConfigFields = CustomBossesConfig.getCustomBoss(filename); + if (customBossesConfigFields == null) { + player.sendMessage("Boss file isn't valid! Try again with a valid filename for your custom boss."); + return null; + } + if (!customBossesConfigFields.isRegionalBoss()) { + player.sendMessage(ChatColor.RED + "Boss file isn't for a regional boss! This feature only works for regional bosses."); + player.sendMessage(ChatColor.GREEN + "Ignore this warning if you are setting blocks for a phase boss whose first phase is a regional boss!"); + } + TransitiveBlockType tbt = null; + try { + tbt = TransitiveBlockType.valueOf(transitiveBlockType); + } catch (Exception ex) { + player.sendMessage("Not a valid transitive block type, use ON_SPAWN or ON_REMOVE !"); + return null; + } + if (activePlayers.containsKey(player)) { + activePlayers.get(player).commitLocations(); + return null; + } else + return new TransitiveBlockCommand(player, customBossesConfigFields, tbt, edit); + } + + /** + * Used for the cancel command + * + * @param player Player for whom registration should be cancelled + */ + public static void processCommand(Player player) { + activePlayers.remove(player); + player.sendMessage(ChatColor.RED + "[EliteMobs] Block registration successfully cancelled!"); + } + + public void setCorner(boolean leftClick, Location location) { + if (leftClick) { + corner1 = location; + player.sendMessage("Set corner 1!"); + } else { + corner2 = location; + player.sendMessage("Set corner 2!"); + } + + if (corner1 != null && corner2 != null && corner1.getWorld() == corner2.getWorld()) { + int blockCount = (int) ((Math.abs(corner1.getX() - corner2.getX()) + 1) * (Math.abs(corner1.getY() - corner2.getY()) + 1) * (Math.abs(corner1.getZ() - corner2.getZ()) + 1)); + if (blockCount > DefaultConfig.getDefaultTransitiveBlockLimiter()) + player.sendMessage("[EliteMobs] Current selection has " + blockCount + " blocks selected. For performance reasons, it is recommended you don't go over " + DefaultConfig.getDefaultTransitiveBlockLimiter() + " blocks!"); + } + + } + + private Vector getRelativeCoordinate(Location location) { + return new Vector(location.getX() - regionalBossEntity.getSpawnLocation().getX(), + location.getY() - regionalBossEntity.getSpawnLocation().getY(), + location.getZ() - regionalBossEntity.getSpawnLocation().getZ()); + } + + public void registerBlock(Block block) { + if (doubleEntryCheck(block, false)) return; + transitiveBlockList.add(new TransitiveBlock(block.getBlockData(), getRelativeCoordinate(block.getLocation()))); + player.sendMessage("Registered " + block.getType() + " block!"); + } + + public void registerAir(Block block) { + if (doubleEntryCheck(block, true)) return; + transitiveBlockList.add(new TransitiveBlock(Material.AIR.createBlockData(), getRelativeCoordinate(block.getLocation()))); + player.sendMessage("Registered air block!"); + } + + private boolean doubleEntryCheck(Block block, boolean isAir) { + TransitiveBlock transitiveBlock = null; + for (TransitiveBlock element : transitiveBlockList) + if (element.getRelativeLocation().equals(getRelativeCoordinate(block.getLocation()))) + if (element.isAir() && !isAir || !element.isAir() && isAir) { + transitiveBlock = element; + break; + } + if (transitiveBlock == null) return false; + transitiveBlockList.remove(transitiveBlock); + player.sendMessage("Unregistered block!"); + return true; + } + + public void commitLocations() { + activePlayers.remove(player); + player.sendMessage(ChatColor.GREEN + "[EliteMobs] Now saving " + transitiveBlockType.toString() + " blocks!"); + List deserializedData = new ArrayList<>(); + + if (regionalSelection) { + int blockCount = (int) ((Math.abs(corner1.getX() - corner2.getX()) + 1) * (Math.abs(corner1.getY() - corner2.getY()) + 1) * (Math.abs(corner1.getZ() - corner2.getZ()) + 1)); + if (blockCount > DefaultConfig.getDefaultTransitiveBlockLimiter()) { + player.sendMessage("[EliteMobs] You registered more than " + DefaultConfig.getDefaultTransitiveBlockLimiter() + " blocks at once. For performance reasons, it is recommended you keep the selections low. Avoid things like selecting a lot of unnecessary air blocks!"); + } + int lowestX, highestX, lowestY, highestY, lowestZ, highestZ; + lowestX = (int) Math.min(corner1.getX(), corner2.getX()); + highestX = (int) Math.max(corner1.getX(), corner2.getX()); + lowestY = (int) Math.min(corner1.getY(), corner2.getY()); + highestY = (int) Math.max(corner1.getY(), corner2.getY()); + lowestZ = (int) Math.min(corner1.getZ(), corner2.getZ()); + highestZ = (int) Math.max(corner1.getZ(), corner2.getZ()); + + for (int x = lowestX; x < highestX + 1; x++) + for (int y = lowestY; y < highestY + 1; y++) + for (int z = lowestZ; z < highestZ + 1; z++) { + Location blockLocation = new Location(player.getWorld(), x, y, z); + transitiveBlockList.add(new TransitiveBlock(blockLocation.getBlock().getBlockData(), getRelativeCoordinate(blockLocation))); + } + + player.sendMessage("Successfully registered " + transitiveBlockList.size() + " blocks between your corners!"); + + } + + for (TransitiveBlock transitiveBlock : transitiveBlockList) { + String deserializedString = transitiveBlock.getRelativeLocation().getX() + "," + + transitiveBlock.getRelativeLocation().getY() + "," + + transitiveBlock.getRelativeLocation().getZ() + "/" + + transitiveBlock.getBlockData().getAsString(); + deserializedData.add(deserializedString); + } + + switch (transitiveBlockType) { + case ON_SPAWN: + customBossesConfigFields.setOnSpawnBlockStates(deserializedData); + if (regionalBossEntity.getCustomBossesConfigFields().getFilename().equals(customBossesConfigFields.getFilename())) + regionalBossEntity.setOnSpawnTransitiveBlocks(TransitiveBlock.serializeTransitiveBlocks(deserializedData, customBossesConfigFields.getFilename())); + player.sendMessage("Locations registered correctly!"); + break; + case ON_REMOVE: + customBossesConfigFields.setOnRemoveBlockStates(deserializedData); + if (regionalBossEntity.getCustomBossesConfigFields().getFilename().equals(customBossesConfigFields.getFilename())) + regionalBossEntity.setOnRemoveTransitiveBlocks(TransitiveBlock.serializeTransitiveBlocks(deserializedData, customBossesConfigFields.getFilename())); + player.sendMessage("Locations registered correctly!"); + break; + default: + player.sendMessage("Failed to commit locations!"); + } + } + + public enum TransitiveBlockType { + ON_SPAWN, + ON_REMOVE + } + + public static class TemporaryBossBlockCommandEvents implements Listener { + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH) + public void onPlayerInteractBlockEvent(PlayerInteractEvent event) { + if (!activePlayers.containsKey(event.getPlayer())) return; + if (event.getHand() != EquipmentSlot.HAND) return; + if (event.getClickedBlock() == null) return; + if (event.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { + if (event.getClickedBlock().getType().isAir()) return; + if (activePlayers.get(event.getPlayer()).isRegionalSelection()) + activePlayers.get(event.getPlayer()).setCorner(false, event.getClickedBlock().getLocation()); + else + activePlayers.get(event.getPlayer()).registerBlock(event.getClickedBlock()); + event.setCancelled(true); + } else if (event.getAction().equals(Action.LEFT_CLICK_BLOCK)) { + if (activePlayers.get(event.getPlayer()).isRegionalSelection()) + activePlayers.get(event.getPlayer()).setCorner(true, event.getClickedBlock().getLocation()); + else + activePlayers.get(event.getPlayer()).registerAir(event.getClickedBlock()); + event.setCancelled(true); + } + } + + @EventHandler + public void onPlayerQuit(PlayerQuitEvent event) { + if (!activePlayers.containsKey(event.getPlayer())) return; + activePlayers.remove(event.getPlayer()); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/transitiveblocks/TransitiveBossBlock.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/transitiveblocks/TransitiveBossBlock.java new file mode 100644 index 000000000..7f85e5680 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/custombosses/transitiveblocks/TransitiveBossBlock.java @@ -0,0 +1,105 @@ +package com.magmaguy.elitemobs.mobconstructor.custombosses.transitiveblocks; + +import com.magmaguy.elitemobs.api.EliteMobRemoveEvent; +import com.magmaguy.elitemobs.api.EliteMobSpawnEvent; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import com.magmaguy.elitemobs.mobconstructor.custombosses.RegionalBossEntity; +import com.magmaguy.elitemobs.utils.WarningMessage; +import org.bukkit.Location; +import org.bukkit.block.BlockFace; +import org.bukkit.block.data.BlockData; +import org.bukkit.block.data.Directional; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.util.Vector; + +public class TransitiveBossBlock implements Listener { + + private static void setBlockData(CustomBossEntity customBossEntity, TransitiveBlock transitiveBlock, Location spawnLocation) { + Location location; + double rotation = 0; + if (customBossEntity.getMinidungeon() != null) + rotation = customBossEntity.getMinidungeon().getDungeonPackagerConfigFields().getRotation(); + BlockData blockData = transitiveBlock.getBlockData().clone(); + + if (rotation == 0) + location = new Location(spawnLocation.getWorld(), + spawnLocation.getX() + transitiveBlock.getRelativeLocation().getX(), + spawnLocation.getY() + transitiveBlock.getRelativeLocation().getY(), + spawnLocation.getZ() + transitiveBlock.getRelativeLocation().getZ()); + else { + location = customBossEntity.getMinidungeon().getRotatedFinalLocation(spawnLocation.getBlock().getLocation().clone().add(new Vector(0.5, 0.5, 0.5)), + transitiveBlock.getRelativeLocation().clone().add(new Vector(0.5, 0.5, 0.5))); + if (blockData instanceof Directional) + ((Directional) blockData).setFacing(rotateBlockFace(((Directional) blockData).getFacing(), rotation)); + } + + location.getBlock().setBlockData(blockData); + } + + /* + 1 = north + 2 = east + 3 = south + 4 = west + */ + private static int blockFaceToInt(BlockFace blockFace) { + switch (blockFace) { + case NORTH: + return 1; + case EAST: + return 2; + case SOUTH: + return 3; + case WEST: + return 4; + default: + new WarningMessage("Attempted to rotate a block through the transitive block system that does not have a north / south / east / west face. This is not currently supported."); + return 1; + } + } + + private static BlockFace intToBlockFace(int blockFaceValue) { + switch (blockFaceValue) { + case 1: + return BlockFace.NORTH; + case 2: + return BlockFace.EAST; + case 3: + return BlockFace.SOUTH; + case 4: + return BlockFace.WEST; + default: + new WarningMessage("Attempted to rotate a block through the transitive block system that does not have a north / south / east / west face. This is not currently supported."); + return BlockFace.NORTH; + } + } + + private static BlockFace rotateBlockFace(BlockFace blockFace, double rotation) { + int adjustedRotation = (int) (rotation / 90d); + int blockFaceInt = blockFaceToInt(blockFace); + int result = blockFaceInt + adjustedRotation; + if (result > 4) result -= 4; + if (result < 1) result += 4; + return intToBlockFace(result); + } + + @EventHandler + public void onBossSpawn(EliteMobSpawnEvent event) { + if (!(event.getEliteMobEntity() instanceof RegionalBossEntity)) return; + + RegionalBossEntity regionalBossEntity = (RegionalBossEntity) event.getEliteMobEntity(); + if (regionalBossEntity.getOnSpawnTransitiveBlocks() != null) + for (TransitiveBlock transitiveBlock : regionalBossEntity.getOnSpawnTransitiveBlocks()) + setBlockData(regionalBossEntity, transitiveBlock, regionalBossEntity.getSpawnLocation()); + } + + @EventHandler + public void onBossRemove(EliteMobRemoveEvent event) { + if (!(event.getEliteMobEntity() instanceof RegionalBossEntity)) return; + RegionalBossEntity regionalBossEntity = (RegionalBossEntity) event.getEliteMobEntity(); + if (regionalBossEntity.getOnRemoveTransitiveBlocks() != null) + for (TransitiveBlock transitiveBlock : regionalBossEntity.getOnRemoveTransitiveBlocks()) + setBlockData(regionalBossEntity, transitiveBlock, regionalBossEntity.getSpawnLocation()); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/displays/DamageDisplay.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/displays/DamageDisplay.java deleted file mode 100644 index 48ce5061e..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/displays/DamageDisplay.java +++ /dev/null @@ -1,126 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.mobconstructor.displays; - -import com.magmaguy.elitemobs.EntityTracker; -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Location; -import org.bukkit.entity.ArmorStand; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.LivingEntity; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageEvent; -import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.util.Vector; - -import java.util.Random; - -public class DamageDisplay implements Listener { - - @EventHandler(priority = EventPriority.LOWEST) - public void onHitArmorStand(EntityDamageEvent event) { - - if (!EntityTracker.getIsArmorStand(event.getEntity())) return; - event.setCancelled(true); - - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onHit(EntityDamageEvent event) { - - if (event.isCancelled()) return; - - if (!(event.getEntity() instanceof LivingEntity) || event.getEntity() instanceof ArmorStand) return; - - if (ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.ONLY_SHOW_DAMAGE_FOR_ELITE_MOBS)) { - - if (EntityTracker.isEliteMob(event.getEntity()) && event.getEntity() instanceof LivingEntity) { - - if (event.getDamage() > 0) displayDamage(event.getEntity(), event.getFinalDamage()); - - } - - } else { - - if (event.getDamage() > 0) displayDamage(event.getEntity(), event.getFinalDamage()); - - } - - } - - public static void displayDamage(Entity entity, double damage) { - - if (!ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.DISPLAY_DAMAGE_ON_HIT)) return; - - Location entityLocation = entity.getLocation(); - - Random random = new Random(); - double randomCoordX = (random.nextDouble() * 2) - 1 + entityLocation.getX(); - double randomCoordZ = (random.nextDouble() * 2) - 1 + entityLocation.getZ(); - - Location newLocation = new Location(entityLocation.getWorld(), randomCoordX, entityLocation.getY() + 1.7, randomCoordZ); - - /* - Dirty fix: armorstands don't render invisibly on their first tick, so it gets moved elsewhere temporarily - */ - ArmorStand armorStand = (ArmorStand) newLocation.getWorld().spawnEntity(newLocation.add(new Vector(0, 50, 0)), EntityType.ARMOR_STAND); - - armorStand.setVisible(false); - armorStand.setMarker(true); - int newDisplayDamage = (int) damage; - armorStand.setCustomName(ChatColor.RED + "" + ChatColor.BOLD + "" + newDisplayDamage + ""); - armorStand.setCustomNameVisible(true); - armorStand.setGravity(false); - EntityTracker.registerArmorStands(armorStand); - - new BukkitRunnable() { - - int taskTimer = 0; - - @Override - public void run() { - - if (taskTimer == 0) - armorStand.teleport(new Location(armorStand.getWorld(), armorStand.getLocation().getX(), - armorStand.getLocation().getY() - 50, armorStand.getLocation().getZ())); - else - armorStand.teleport(new Location(armorStand.getWorld(), armorStand.getLocation().getX(), - armorStand.getLocation().getY() + 0.1, armorStand.getLocation().getZ())); - - taskTimer++; - - if (taskTimer == 15) { - - cancel(); - EntityTracker.unregisterArmorStand(armorStand); - armorStand.remove(); - - } - - } - - }.runTaskTimer(Bukkit.getPluginManager().getPlugin(MetadataHandler.ELITE_MOBS), 0, 1); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/displays/DisplayMob.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/displays/DisplayMob.java deleted file mode 100644 index c74cac68c..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/displays/DisplayMob.java +++ /dev/null @@ -1,71 +0,0 @@ -package com.magmaguy.elitemobs.mobconstructor.displays; - -import org.bukkit.event.Listener; - -public class DisplayMob implements Listener { - -// public static List livingEntityList = new ArrayList<>(); -// private static String encodedKey = ChatColorConverter.convert("&D&d&d&d&D&d&d&f"); -// -// public static void nameEncoder(LivingEntity livingEntity) { -// -// new BukkitRunnable() { -// @Override -// public void run() { -// livingEntity.setCustomName(ChatColorConverter.convert(encodedKey + livingEntity.getCustomName())); -// MetadataHandler.registerMetadata(livingEntity, MetadataHandler.CUSTOM_NAME, true); -// MetadataHandler.registerMetadata(livingEntity, MetadataHandler.LIVINGENTITY_DISPLAY, true); -// MetadataHandler.registerMetadata(livingEntity, MetadataHandler.PERSISTENT_ENTITY, true); -// livingEntityList.add(livingEntity); -// } -// }.runTaskLater(MetadataHandler.PLUGIN, 1); -// -// } -// -// public static boolean hasNameKey(LivingEntity livingEntity) { -// -// if (livingEntity.getCustomName() == null) return false; -// return (livingEntity.getCustomName().contains(encodedKey)); -// -// } -// -// @EventHandler -// public void onChunkLoad(ChunkLoadEvent event) { -// -// for (Entity entity : event.getChunk().getEntities()) -// if (entity instanceof LivingEntity) -// if (hasNameKey((LivingEntity) entity)) -// if (!livingEntityList.contains(entity)) -// livingEntityList.add((LivingEntity) entity); -// -// } -// -// @EventHandler(priority = EventPriority.LOWEST) -// public void onDamage(EntityDamageEvent event) { -// if (event.getEntity().hasMetadata(MetadataHandler.LIVINGENTITY_DISPLAY)) -// if (!event.getCause().equals(EntityDamageEvent.DamageCause.ENTITY_ATTACK)) -// event.setCancelled(true); -// -// } -// -// @EventHandler(priority = EventPriority.LOWEST) -// public void onEntityDamage(EntityDamageByEntityEvent event) { -// -// if (event.getEntity().hasMetadata(MetadataHandler.LIVINGENTITY_DISPLAY)) -// if (event.getDamager().isOp()) { -// event.getEntity().remove(); -// event.setCancelled(true); -// } else -// event.setCancelled(true); -// -// } -// -// @EventHandler -// public void onFire(EntityCombustEvent event) { -// -// if (event.getEntity().hasMetadata(MetadataHandler.LIVINGENTITY_DISPLAY)) -// event.setCancelled(true); -// -// } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/displays/HealthDisplay.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/displays/HealthDisplay.java deleted file mode 100644 index bb77ed956..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/displays/HealthDisplay.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.mobconstructor.displays; - -import com.magmaguy.elitemobs.EntityTracker; -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Location; -import org.bukkit.entity.ArmorStand; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.LivingEntity; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageEvent; -import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.util.Vector; - -public class HealthDisplay implements Listener { - - @EventHandler(priority = EventPriority.MONITOR) - public void onHit(EntityDamageEvent event) { - - if (event.isCancelled()) return; - - if (!(event.getEntity() instanceof LivingEntity) || event.getEntity() instanceof ArmorStand) return; - - if (ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.ONLY_SHOW_HEALTH_FOR_ELITE_MOBS)) { - if (EntityTracker.isEliteMob(event.getEntity())) - displayHealth((LivingEntity) event.getEntity(), event.getFinalDamage()); - - } else - displayHealth((LivingEntity) event.getEntity(), event.getFinalDamage()); - - } - - public static void displayHealth(LivingEntity livingEntity, double damage) { - - if (!ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.DISPLAY_HEALTH_ON_HIT)) return; - - int maxHealth = (int) livingEntity.getMaxHealth(); - int currentHealth = (int) (livingEntity.getHealth() - damage); - - Location entityLocation = new Location(livingEntity.getWorld(), livingEntity.getLocation().getX(), - livingEntity.getLocation().getY() + livingEntity.getEyeHeight() + 0.5, livingEntity.getLocation().getZ()); - - /* - Dirty fix: armorstands don't render invisibly on their first tick, so it gets moved elsewhere temporarily - */ - ArmorStand armorStand = (ArmorStand) entityLocation.getWorld().spawnEntity(entityLocation.add(new Vector(0, 50, 0)), EntityType.ARMOR_STAND); - - armorStand.setVisible(false); - armorStand.setMarker(true); - armorStand.setCustomName(setHealthColor(currentHealth, maxHealth) + "" + currentHealth + "/" + maxHealth); - armorStand.setGravity(false); - EntityTracker.registerCullableEntity(armorStand); - - - new BukkitRunnable() { - - int taskTimer = 0; - - @Override - public void run() { - - armorStand.setCustomNameVisible(true); - - Location newLocation = new Location(livingEntity.getWorld(), livingEntity.getLocation().getX(), - livingEntity.getLocation().getY() + livingEntity.getEyeHeight() + 0.5, livingEntity.getLocation().getZ()); - - armorStand.teleport(newLocation); - - taskTimer++; - - if (taskTimer == 15) { - - cancel(); - EntityTracker.unregisterCullableEntity(armorStand); - armorStand.remove(); - - } - - } - - }.runTaskTimer(Bukkit.getPluginManager().getPlugin(MetadataHandler.ELITE_MOBS), 1, 1L); - - } - - /* - Color progression: Dark green - Green - Red - Dark red - */ - private static ChatColor setHealthColor(int currentHealth, int maxHealth) { - - double healthPercentage = currentHealth * 100 / maxHealth; - - if (healthPercentage > 75) { - - return ChatColor.DARK_GREEN; - - } - - if (healthPercentage > 50) { - - return ChatColor.GREEN; - - } - - if (healthPercentage > 25) { - - return ChatColor.RED; - - } - - if (healthPercentage > 0) { - - return ChatColor.DARK_RED; - - } - - return ChatColor.DARK_RED; - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/PluginMobProperties.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/PluginMobProperties.java index 2c0e1beb1..8d36e1c58 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/PluginMobProperties.java +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/PluginMobProperties.java @@ -1,6 +1,5 @@ package com.magmaguy.elitemobs.mobconstructor.mobdata; -import com.magmaguy.elitemobs.config.ConfigValues; import com.magmaguy.elitemobs.config.DefaultConfig; import com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs.EliteMobProperties; import com.magmaguy.elitemobs.mobconstructor.mobdata.passivemobs.SuperMobProperties; @@ -12,6 +11,12 @@ public abstract class PluginMobProperties { public String name; public EntityType entityType; public double defaultMaxHealth; + public double baseDamage; + + public static void initializePluginMobValues() { + SuperMobProperties.initializeSuperMobValues(); + EliteMobProperties.initializeEliteMobValues(); + } public boolean isEnabled() { return isEnabled; @@ -21,22 +26,20 @@ public String getName() { return this.name; } + public String getName(int level) { + return this.name.replace("$level", level + ""); + } + public EntityType getEntityType() { return this.entityType; } - public double getDefaultMaxHealth() { return defaultMaxHealth; } public double getSuperMobMaxHealth() { - return defaultMaxHealth * ConfigValues.defaultConfig.getInt(DefaultConfig.SUPERMOB_STACK_AMOUNT); - } - - public static void initializePluginMobValues() { - SuperMobProperties.initializeSuperMobValues(); - EliteMobProperties.initializeEliteMobValues(); + return defaultMaxHealth * DefaultConfig.getSuperMobStackAmount(); } } diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteBee.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteBee.java new file mode 100644 index 000000000..c7a1c669f --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteBee.java @@ -0,0 +1,20 @@ +package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; +import com.magmaguy.elitemobs.utils.VersionChecker; +import org.bukkit.entity.EntityType; + +public class EliteBee extends EliteMobProperties { + + public EliteBee() { + if (VersionChecker.serverVersionOlderThan(15, 0)) { + return; + } + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.BEE).getName(); + this.entityType = EntityType.BEE; + this.defaultMaxHealth = 10; + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.BEE).getBaseDamage(); + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.BEE).isEnabled(); + eliteMobData.add(this); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteBlaze.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteBlaze.java index fdac8be09..026279fdd 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteBlaze.java +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteBlaze.java @@ -1,30 +1,18 @@ package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.TranslationConfig; -import com.magmaguy.elitemobs.config.ValidMobsConfig; +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; import org.bukkit.entity.EntityType; public class EliteBlaze extends EliteMobProperties { public EliteBlaze() { - - this.name = ConfigValues.translationConfig.getString(TranslationConfig.NAME_BLAZE); - + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.BLAZE).getName(); this.entityType = EntityType.BLAZE; - this.defaultMaxHealth = 20; - - this.validDefensivePowers.addAll(super.getAllDefensivePowers()); - this.validOffensivePowers.addAll(super.getAllOffensivePowers()); - this.validMiscellaneousPowers.addAll(super.getAllMiscellaneousPowers()); - - this.isEnabled = ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.VALID_AGGRESSIVE_ELITEMOBS + getEntityType().toString()) && - ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.ALLOW_AGGRESSIVE_ELITEMOBS); - - if (this.isEnabled) - eliteMobData.add(this); - + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.BLAZE).getBaseDamage(); + super.addMajorPower("tracking_fireball.yml"); + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.BLAZE).isEnabled(); + eliteMobData.add(this); } } diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteCaveSpider.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteCaveSpider.java index b0f71d8c1..24538a02c 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteCaveSpider.java +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteCaveSpider.java @@ -1,30 +1,17 @@ package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.TranslationConfig; -import com.magmaguy.elitemobs.config.ValidMobsConfig; +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; import org.bukkit.entity.EntityType; public class EliteCaveSpider extends EliteMobProperties { public EliteCaveSpider() { - - this.name = ConfigValues.translationConfig.getString(TranslationConfig.NAME_CAVE_SPIDER); - + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.CAVE_SPIDER).getName(); this.entityType = EntityType.CAVE_SPIDER; - this.defaultMaxHealth = 12; - - this.validDefensivePowers.addAll(super.getAllDefensivePowers()); - this.validOffensivePowers.addAll(super.getAllOffensivePowers()); - this.validMiscellaneousPowers.addAll(super.getAllMiscellaneousPowers()); - - this.isEnabled = ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.VALID_AGGRESSIVE_ELITEMOBS + getEntityType().toString()) && - ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.ALLOW_AGGRESSIVE_ELITEMOBS); - - if (this.isEnabled) - eliteMobData.add(this); - + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.CAVE_SPIDER).getBaseDamage(); + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.CAVE_SPIDER).isEnabled(); + eliteMobData.add(this); } } diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteCreeper.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteCreeper.java index 71710c87e..fa520cf4e 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteCreeper.java +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteCreeper.java @@ -1,34 +1,19 @@ package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.TranslationConfig; -import com.magmaguy.elitemobs.config.ValidMobsConfig; -import com.magmaguy.elitemobs.mobpowers.defensivepowers.Invisibility; +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; +import com.magmaguy.elitemobs.powers.defensivepowers.Invisibility; import org.bukkit.entity.EntityType; public class EliteCreeper extends EliteMobProperties { public EliteCreeper() { - - this.name = ConfigValues.translationConfig.getString(TranslationConfig.NAME_CREEPER); - + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.CREEPER).getName(); this.entityType = EntityType.CREEPER; - this.defaultMaxHealth = 20; - - this.validDefensivePowers.addAll(super.getAllDefensivePowers()); - this.validOffensivePowers.addAll(super.getAllOffensivePowers()); - this.validMiscellaneousPowers.addAll(super.getAllMiscellaneousPowers()); - -// todo: add a way to configure powers per entity type - this.validMiscellaneousPowers.remove(new Invisibility()); - - isEnabled = ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.VALID_AGGRESSIVE_ELITEMOBS + getEntityType().toString()) && - ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.ALLOW_AGGRESSIVE_ELITEMOBS); - - if (this.isEnabled) - eliteMobData.add(this); - + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.CREEPER).getBaseDamage(); + super.removeDefensivePower(new Invisibility()); + isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.CREEPER).isEnabled(); + eliteMobData.add(this); } } diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteDrowned.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteDrowned.java new file mode 100644 index 000000000..9b40f6670 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteDrowned.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; +import org.bukkit.entity.EntityType; + +public class EliteDrowned extends EliteMobProperties { + + public EliteDrowned() { + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.DROWNED).getName(); + this.entityType = EntityType.DROWNED; + this.defaultMaxHealth = 20; + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.DROWNED).getBaseDamage(); + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.DROWNED).isEnabled(); + eliteMobData.add(this); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteElderGuardian.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteElderGuardian.java new file mode 100644 index 000000000..7d7d07960 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteElderGuardian.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; +import org.bukkit.entity.EntityType; + +public class EliteElderGuardian extends EliteMobProperties { + public EliteElderGuardian() { + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.ELDER_GUARDIAN).getName(); + this.entityType = EntityType.ELDER_GUARDIAN; + this.defaultMaxHealth = 80; + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.ELDER_GUARDIAN).getBaseDamage(); + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.ELDER_GUARDIAN).isEnabled(); + eliteMobData.add(this); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteEnderDragon.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteEnderDragon.java new file mode 100644 index 000000000..e2bd97794 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteEnderDragon.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; +import org.bukkit.entity.EntityType; + +public class EliteEnderDragon extends EliteMobProperties { + public EliteEnderDragon() { + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.ENDER_DRAGON).getName(); + this.entityType = EntityType.ENDER_DRAGON; + this.defaultMaxHealth = 200; + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.ENDER_DRAGON).getBaseDamage(); + isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.ENDER_DRAGON).isEnabled(); + eliteMobData.add(this); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteEnderman.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteEnderman.java index e4eb34031..8f539b8e8 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteEnderman.java +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteEnderman.java @@ -1,30 +1,17 @@ package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.TranslationConfig; -import com.magmaguy.elitemobs.config.ValidMobsConfig; +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; import org.bukkit.entity.EntityType; public class EliteEnderman extends EliteMobProperties { public EliteEnderman() { - - this.name = ConfigValues.translationConfig.getString(TranslationConfig.NAME_ENDERMAN); - + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.ENDERMAN).getName(); this.entityType = EntityType.ENDERMAN; - this.defaultMaxHealth = 40; - - this.validDefensivePowers.addAll(super.getAllDefensivePowers()); - this.validOffensivePowers.addAll(super.getAllOffensivePowers()); - this.validMiscellaneousPowers.addAll(super.getAllMiscellaneousPowers()); - - isEnabled = ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.VALID_AGGRESSIVE_ELITEMOBS + getEntityType().toString()) && - ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.ALLOW_AGGRESSIVE_ELITEMOBS); - - if (this.isEnabled) - eliteMobData.add(this); - + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.ENDERMAN).getBaseDamage(); + isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.ENDERMAN).isEnabled(); + eliteMobData.add(this); } } diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteEndermite.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteEndermite.java index 96beb4e9e..50698ab7d 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteEndermite.java +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteEndermite.java @@ -1,30 +1,17 @@ package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.TranslationConfig; -import com.magmaguy.elitemobs.config.ValidMobsConfig; +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; import org.bukkit.entity.EntityType; public class EliteEndermite extends EliteMobProperties { public EliteEndermite() { - - this.name = ConfigValues.translationConfig.getString(TranslationConfig.NAME_ENDERMITE); - + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.ENDERMITE).getName(); this.entityType = EntityType.ENDERMITE; - this.defaultMaxHealth = 8; - - this.validDefensivePowers.addAll(super.getAllDefensivePowers()); - this.validOffensivePowers.addAll(super.getAllOffensivePowers()); - this.validMiscellaneousPowers.addAll(super.getAllMiscellaneousPowers()); - - this.isEnabled = ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.VALID_AGGRESSIVE_ELITEMOBS + getEntityType().toString()) && - ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.ALLOW_AGGRESSIVE_ELITEMOBS); - - if (this.isEnabled) - eliteMobData.add(this); - + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.ENDERMITE).getBaseDamage(); + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.ENDERMITE).isEnabled(); + eliteMobData.add(this); } } diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteEvoker.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteEvoker.java new file mode 100644 index 000000000..e614eeb75 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteEvoker.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; +import org.bukkit.entity.EntityType; + +public class EliteEvoker extends EliteMobProperties { + public EliteEvoker() { + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.EVOKER).getName(); + this.entityType = EntityType.EVOKER; + this.defaultMaxHealth = 24; + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.EVOKER).getBaseDamage(); + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.EVOKER).isEnabled(); + eliteMobData.add(this); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteGhast.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteGhast.java new file mode 100644 index 000000000..d02c6bda3 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteGhast.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; +import org.bukkit.entity.EntityType; + +public class EliteGhast extends EliteMobProperties { + public EliteGhast() { + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.GHAST).getName(); + this.entityType = EntityType.GHAST; + this.defaultMaxHealth = 10; + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.GHAST).getBaseDamage(); + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.GHAST).isEnabled(); + eliteMobData.add(this); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteGoat.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteGoat.java new file mode 100644 index 000000000..ae30b8968 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteGoat.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; +import com.magmaguy.elitemobs.utils.VersionChecker; +import org.bukkit.entity.EntityType; + +public class EliteGoat extends EliteMobProperties { + public EliteGoat() { + if (VersionChecker.serverVersionOlderThan(17, 0)) { + return; + } + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.GOAT).getName(); + this.entityType = EntityType.GOAT; + this.defaultMaxHealth = 10; + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.GOAT).getBaseDamage(); + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.GOAT).isEnabled(); + eliteMobData.add(this); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteGuardian.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteGuardian.java new file mode 100644 index 000000000..de088ce10 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteGuardian.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; +import org.bukkit.entity.EntityType; + +public class EliteGuardian extends EliteMobProperties { + public EliteGuardian() { + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.GUARDIAN).getName(); + this.entityType = EntityType.GUARDIAN; + this.defaultMaxHealth = 30; + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.GUARDIAN).getBaseDamage(); + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.GUARDIAN).isEnabled(); + eliteMobData.add(this); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteHoglin.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteHoglin.java new file mode 100644 index 000000000..9e12f3fcf --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteHoglin.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; +import com.magmaguy.elitemobs.utils.VersionChecker; +import org.bukkit.entity.EntityType; + +public class EliteHoglin extends EliteMobProperties { + public EliteHoglin() { + if (VersionChecker.serverVersionOlderThan(16, 0)) { + return; + } + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.HOGLIN).getName(); + this.entityType = EntityType.HOGLIN; + this.defaultMaxHealth = 40; + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.HOGLIN).getBaseDamage(); + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.HOGLIN).isEnabled(); + eliteMobData.add(this); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteHusk.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteHusk.java index 4e90a0781..f599cbc6a 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteHusk.java +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteHusk.java @@ -1,30 +1,17 @@ package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.TranslationConfig; -import com.magmaguy.elitemobs.config.ValidMobsConfig; +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; import org.bukkit.entity.EntityType; public class EliteHusk extends EliteMobProperties { public EliteHusk() { - - this.name = ConfigValues.translationConfig.getString(TranslationConfig.NAME_HUSK); - + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.HUSK).getName(); this.entityType = EntityType.HUSK; - this.defaultMaxHealth = 20; - - this.validDefensivePowers.addAll(super.getAllDefensivePowers()); - this.validOffensivePowers.addAll(super.getAllOffensivePowers()); - this.validMiscellaneousPowers.addAll(super.getAllMiscellaneousPowers()); - - isEnabled = ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.VALID_AGGRESSIVE_ELITEMOBS + getEntityType().toString()) && - ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.ALLOW_AGGRESSIVE_ELITEMOBS); - - if (this.isEnabled) - eliteMobData.add(this); - + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.HUSK).getBaseDamage(); + isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.HUSK).isEnabled(); + eliteMobData.add(this); } } diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteIllusioner.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteIllusioner.java new file mode 100644 index 000000000..7e4992c76 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteIllusioner.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; +import org.bukkit.entity.EntityType; + +public class EliteIllusioner extends EliteMobProperties { + public EliteIllusioner() { + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.ILLUSIONER).getName(); + this.entityType = EntityType.ILLUSIONER; + this.defaultMaxHealth = 32; + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.ILLUSIONER).getBaseDamage(); + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.ILLUSIONER).isEnabled(); + eliteMobData.add(this); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteIronGolem.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteIronGolem.java index 195b44895..76807a989 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteIronGolem.java +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteIronGolem.java @@ -1,30 +1,17 @@ package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.TranslationConfig; -import com.magmaguy.elitemobs.config.ValidMobsConfig; +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; import org.bukkit.entity.EntityType; public class EliteIronGolem extends EliteMobProperties { public EliteIronGolem() { - - this.name = ConfigValues.translationConfig.getString(TranslationConfig.NAME_IRON_GOLEM); - + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.IRON_GOLEM).getName(); this.entityType = EntityType.IRON_GOLEM; - this.defaultMaxHealth = 100; - - this.validDefensivePowers.addAll(super.getAllDefensivePowers()); - this.validOffensivePowers.addAll(super.getAllOffensivePowers()); - this.validMiscellaneousPowers.addAll(super.getAllMiscellaneousPowers()); - - isEnabled = ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.VALID_AGGRESSIVE_ELITEMOBS + getEntityType().toString()) && - ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.ALLOW_AGGRESSIVE_ELITEMOBS); - - if (this.isEnabled) - eliteMobData.add(this); - + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.IRON_GOLEM).getBaseDamage(); + isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.IRON_GOLEM).isEnabled(); + eliteMobData.add(this); } } diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteKillerBunny.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteKillerBunny.java new file mode 100644 index 000000000..46b0977b4 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteKillerBunny.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; +import org.bukkit.entity.EntityType; + +public class EliteKillerBunny extends EliteMobProperties { + public EliteKillerBunny() { + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.RABBIT).getName(); + this.entityType = EntityType.RABBIT; + this.defaultMaxHealth = 3; + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.RABBIT).getBaseDamage(); + isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.RABBIT).isEnabled(); + eliteMobData.add(this); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteLlama.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteLlama.java new file mode 100644 index 000000000..57838c767 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteLlama.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; +import org.bukkit.entity.EntityType; + +public class EliteLlama extends EliteMobProperties { + public EliteLlama() { + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.LLAMA).getName(); + this.entityType = EntityType.LLAMA; + this.defaultMaxHealth = 30; + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.LLAMA).getBaseDamage(); + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.LLAMA).isEnabled(); + eliteMobData.add(this); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteMobProperties.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteMobProperties.java index 4f656174b..cdae453d0 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteMobProperties.java +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteMobProperties.java @@ -1,21 +1,19 @@ package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; +import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; import com.magmaguy.elitemobs.mobconstructor.mobdata.PluginMobProperties; -import com.magmaguy.elitemobs.mobpowers.defensivepowers.*; -import com.magmaguy.elitemobs.mobpowers.majorpowers.MajorPower; -import com.magmaguy.elitemobs.mobpowers.minorpowers.MinorPower; -import com.magmaguy.elitemobs.mobpowers.miscellaneouspowers.BonusLoot; -import com.magmaguy.elitemobs.mobpowers.miscellaneouspowers.MovementSpeed; -import com.magmaguy.elitemobs.mobpowers.miscellaneouspowers.Taunt; -import com.magmaguy.elitemobs.mobpowers.offensivepowers.*; +import com.magmaguy.elitemobs.powers.meta.ElitePower; +import com.magmaguy.elitemobs.powers.meta.MajorPower; +import com.magmaguy.elitemobs.powers.meta.MinorPower; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; -import java.util.Arrays; import java.util.HashSet; - -import static com.magmaguy.elitemobs.utils.VersionChecker.currentVersionIsUnder; +import java.util.Iterator; public abstract class EliteMobProperties extends PluginMobProperties { @@ -24,117 +22,82 @@ public abstract class EliteMobProperties extends PluginMobProperties { */ public static HashSet eliteMobData = new HashSet<>(); - public HashSet validMajorPowers = new HashSet<>(); - public HashSet validDefensivePowers = new HashSet<>(); - public HashSet validOffensivePowers = new HashSet<>(); - public HashSet validMiscellaneousPowers = new HashSet<>(); - - public HashSet getValidMajorPowers() { - return validMajorPowers; - } - - public HashSet getValidDefensivePowers() { - return validDefensivePowers; - } - - public HashSet getValidOffensivePowers() { - return validOffensivePowers; - } - - public HashSet getValidMiscellaneousPowers() { - return validMiscellaneousPowers; - } + private final HashSet validMajorPowers = new HashSet<>(); + private final HashSet validDefensivePowers = (HashSet) ElitePower.getDefensivePowers().clone(); + private final HashSet validOffensivePowers = (HashSet) ElitePower.getOffensivePowers().clone(); + private final HashSet validMiscellaneousPowers = (HashSet) ElitePower.getMiscellaneousPowers().clone(); - public HashSet getAllDefensivePowers() { - return new HashSet<>(Arrays.asList( - new Invisibility(), - new InvulnerabilityArrow(), - new InvulnerabilityFallDamage(), - new InvulnerabilityFire(), - new InvulnerabilityKnockback() - )); - } - - public HashSet getAllOffensivePowers() { - return new HashSet<>(Arrays.asList( - new AttackArrow(), - new AttackBlinding(), - new AttackConfusing(), - new AttackFire(), - new AttackFireball(), - new AttackFreeze(), - new AttackGravity(), - new AttackPoison(), - new AttackPush(), - new AttackWeakness(), - new AttackWeb(), - new AttackWither() - )); - } - - public HashSet getAllMiscellaneousPowers() { - return new HashSet<>(Arrays.asList( - new BonusLoot(), - new MovementSpeed(), - new Taunt() - )); + public static void initializeEliteMobValues() { + new EliteBlaze(); + new EliteCaveSpider(); + new EliteCreeper(); + new EliteDrowned(); + new EliteElderGuardian(); + new EliteGuardian(); + new EliteEnderman(); + new EliteIronGolem(); + new ElitePhantom(); + new EliteZombifiedPiglin(); + new ElitePillager(); + new EliteSilverfish(); + new EliteSkeleton(); + new EliteSpider(); + new EliteWitch(); + new EliteWitherSkeleton(); + new EliteZombie(); + new EliteEndermite(); + new EliteEvoker(); + new EliteStray(); + new EliteHusk(); + new EliteIllusioner(); + new EliteVex(); + new EliteVindicator(); + new ElitePolarBear(); + new EliteRavager(); + new EliteGhast(); + new EliteZoglin(); + new ElitePiglin(); + new EliteHoglin(); + new ElitePiglinBrute(); + new EliteBee(); + new EliteWolf(); + new EliteEnderDragon(); + new EliteShulker(); + new EliteKillerBunny(); + new EliteGoat(); + new EliteLlama(); } - public static void initializeEliteMobValues() { - EliteBlaze eliteBlaze = new EliteBlaze(); - EliteCaveSpider eliteCaveSpider = new EliteCaveSpider(); - EliteCreeper eliteCreeper = new EliteCreeper(); - EliteEnderman eliteEnderman = new EliteEnderman(); - EliteIronGolem eliteIronGolem = new EliteIronGolem(); - ElitePigZombie elitePigZombie = new ElitePigZombie(); - EliteSilverfish eliteSilverfish = new EliteSilverfish(); - EliteSkeleton eliteSkeleton = new EliteSkeleton(); - EliteSpider eliteSpider = new EliteSpider(); - EliteWitch eliteWitch = new EliteWitch(); - EliteWitherSkeleton eliteWitherSkeleton = new EliteWitherSkeleton(); - EliteZombie eliteZombie = new EliteZombie(); - /* - Post-1.8 - */ - if (!currentVersionIsUnder(1, 8)) { - EliteEndermite eliteEndermite = new EliteEndermite(); - } - /* - Post-1.11 - */ - if (!currentVersionIsUnder(1, 11)) { - EliteStray eliteStray = new EliteStray(); - EliteHusk eliteHusk = new EliteHusk(); - EliteVex eliteVex = new EliteVex(); - EliteVindicator eliteVindicator = new EliteVindicator(); - ElitePolarBear elitePolarBear = new ElitePolarBear(); - } + public static boolean isValidEliteMobType(Entity entity) { + if (entity instanceof LivingEntity) + return isValidEliteMobType(entity.getType()); + return false; } public static boolean isValidEliteMobType(EntityType entityType) { - for (EliteMobProperties eliteMobProperties : eliteMobData) if (eliteMobProperties.getEntityType().equals(entityType)) - return true; - - return false; - - } - - public static boolean isValidEliteMobType(Entity entity) { - if (entity instanceof LivingEntity) - return isValidEliteMobType(entity.getType()); + if (eliteMobProperties.isEnabled) + return true; return false; } public static EliteMobProperties getPluginData(EntityType entityType) { - for (EliteMobProperties eliteMobProperties : eliteMobData) if (eliteMobProperties.getEntityType().equals(entityType)) return eliteMobProperties; - return null; + } + + public static double getBaselineDamage(EntityType entityType, EliteEntity eliteEntity) { + if (eliteEntity instanceof CustomBossEntity && + ((CustomBossEntity) eliteEntity).isNormalizedCombat()) + return MobCombatSettingsConfig.getNormalizedBaselineDamage(); + return getBaselineDamage(entityType); + } + public static double getBaselineDamage(EntityType entityType) { + return getPluginData(entityType).baseDamage; } public static EliteMobProperties getPluginData(Entity entity) { @@ -148,4 +111,43 @@ public static HashSet getValidMobTypes() { return livingEntities; } + public void addMajorPower(String powerName) { + if (PowersConfig.getPower(powerName).isEnabled()) + validMajorPowers.add((MajorPower) ElitePower.getElitePower(powerName)); + } + + public void removeOffensivePower(MinorPower minorPower) { + for (Iterator iterator = validOffensivePowers.iterator(); iterator.hasNext(); ) { + MinorPower minorPower1 = iterator.next(); + if (minorPower1.getFileName().equalsIgnoreCase(minorPower.getFileName())) { + iterator.remove(); + return; + } + } + } + + public void removeDefensivePower(MinorPower minorPower) { + for (Iterator iterator = validDefensivePowers.iterator(); iterator.hasNext(); ) { + MinorPower minorPower1 = iterator.next(); + if (minorPower1.getFileName().equalsIgnoreCase(minorPower.getFileName())) + iterator.remove(); + } + } + + public HashSet getValidMajorPowers() { + return validMajorPowers; + } + + public HashSet getValidDefensivePowers() { + return validDefensivePowers; + } + + public HashSet getValidOffensivePowers() { + return validOffensivePowers; + } + + public HashSet getValidMiscellaneousPowers() { + return validMiscellaneousPowers; + } + } diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/ElitePhantom.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/ElitePhantom.java new file mode 100644 index 000000000..904e59f10 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/ElitePhantom.java @@ -0,0 +1,21 @@ +package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; +import com.magmaguy.elitemobs.powers.miscellaneouspowers.GroundPound; +import com.magmaguy.elitemobs.powers.offensivepowers.AttackLightning; +import org.bukkit.entity.EntityType; + +public class ElitePhantom extends EliteMobProperties { + + public ElitePhantom() { + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.PHANTOM).getName(); + this.entityType = EntityType.PHANTOM; + this.defaultMaxHealth = 20; + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.PHANTOM).getBaseDamage(); + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.PHANTOM).isEnabled(); + removeOffensivePower(new AttackLightning()); + super.removeDefensivePower(new GroundPound()); + eliteMobData.add(this); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/ElitePigZombie.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/ElitePigZombie.java deleted file mode 100644 index 2ada22e7f..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/ElitePigZombie.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; - -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.TranslationConfig; -import com.magmaguy.elitemobs.config.ValidMobsConfig; -import org.bukkit.entity.EntityType; - -public class ElitePigZombie extends EliteMobProperties { - - public ElitePigZombie() { - - this.name = ConfigValues.translationConfig.getString(TranslationConfig.NAME_PIG_ZOMBIE); - - this.entityType = EntityType.PIG_ZOMBIE; - - this.defaultMaxHealth = 20; - - this.validDefensivePowers.addAll(super.getAllDefensivePowers()); - this.validOffensivePowers.addAll(super.getAllOffensivePowers()); - this.validMiscellaneousPowers.addAll(super.getAllMiscellaneousPowers()); - - this.isEnabled = ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.VALID_AGGRESSIVE_ELITEMOBS + getEntityType().toString()) && - ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.ALLOW_AGGRESSIVE_ELITEMOBS); - - if (this.isEnabled) - eliteMobData.add(this); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/ElitePiglin.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/ElitePiglin.java new file mode 100644 index 000000000..87df9d21e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/ElitePiglin.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; +import com.magmaguy.elitemobs.utils.VersionChecker; +import org.bukkit.entity.EntityType; + +public class ElitePiglin extends EliteMobProperties { + public ElitePiglin() { + if (VersionChecker.serverVersionOlderThan(16, 0)) { + return; + } + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.PIGLIN).getName(); + this.entityType = EntityType.PIGLIN; + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.PIGLIN).getBaseDamage(); + this.defaultMaxHealth = 16; + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.PIGLIN).isEnabled(); + eliteMobData.add(this); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/ElitePiglinBrute.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/ElitePiglinBrute.java new file mode 100644 index 000000000..a915ac766 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/ElitePiglinBrute.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; +import com.magmaguy.elitemobs.utils.VersionChecker; +import org.bukkit.entity.EntityType; + +public class ElitePiglinBrute extends EliteMobProperties { + public ElitePiglinBrute() { + if (VersionChecker.serverVersionOlderThan(16, 2)) { + return; + } + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.PIGLIN_BRUTE).getName(); + this.entityType = EntityType.PIGLIN_BRUTE; + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.PIGLIN_BRUTE).getBaseDamage(); + this.defaultMaxHealth = 50; + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.PIGLIN_BRUTE).isEnabled(); + eliteMobData.add(this); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/ElitePillager.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/ElitePillager.java new file mode 100644 index 000000000..a83236a63 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/ElitePillager.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; +import org.bukkit.entity.EntityType; + +public class ElitePillager extends EliteMobProperties { + public ElitePillager() { + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.PILLAGER).getName(); + this.entityType = EntityType.PILLAGER; + this.defaultMaxHealth = 24; + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.PILLAGER).getBaseDamage(); + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.PILLAGER).isEnabled(); + eliteMobData.add(this); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/ElitePolarBear.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/ElitePolarBear.java index fa6ae96e2..b582b08bc 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/ElitePolarBear.java +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/ElitePolarBear.java @@ -1,30 +1,17 @@ package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.TranslationConfig; -import com.magmaguy.elitemobs.config.ValidMobsConfig; +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; import org.bukkit.entity.EntityType; public class ElitePolarBear extends EliteMobProperties { public ElitePolarBear() { - - this.name = ConfigValues.translationConfig.getString(TranslationConfig.NAME_POLAR_BEAR); - + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.POLAR_BEAR).getName(); this.entityType = EntityType.POLAR_BEAR; - this.defaultMaxHealth = 30; - - this.validDefensivePowers.addAll(super.getAllDefensivePowers()); - this.validOffensivePowers.addAll(super.getAllOffensivePowers()); - this.validMiscellaneousPowers.addAll(super.getAllMiscellaneousPowers()); - - this.isEnabled = ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.VALID_AGGRESSIVE_ELITEMOBS + getEntityType().toString()) && - ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.ALLOW_AGGRESSIVE_ELITEMOBS); - - if (this.isEnabled) - eliteMobData.add(this); - + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.POLAR_BEAR).getBaseDamage(); + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.POLAR_BEAR).isEnabled(); + eliteMobData.add(this); } } diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteRavager.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteRavager.java new file mode 100644 index 000000000..ea5d23785 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteRavager.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; +import org.bukkit.entity.EntityType; + +public class EliteRavager extends EliteMobProperties { + public EliteRavager() { + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.RAVAGER).getName(); + this.entityType = EntityType.RAVAGER; + this.defaultMaxHealth = 100; + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.RAVAGER).getBaseDamage(); + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.RAVAGER).isEnabled(); + eliteMobData.add(this); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteShulker.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteShulker.java new file mode 100644 index 000000000..19563d869 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteShulker.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; +import org.bukkit.entity.EntityType; + +public class EliteShulker extends EliteMobProperties { + public EliteShulker() { + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.SHULKER).getName(); + this.entityType = EntityType.SHULKER; + this.defaultMaxHealth = 30; + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.SHULKER).getBaseDamage(); + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.SHULKER).isEnabled(); + eliteMobData.add(this); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteSilverfish.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteSilverfish.java index 663e6b5d8..a13aa7e54 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteSilverfish.java +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteSilverfish.java @@ -1,30 +1,17 @@ package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.TranslationConfig; -import com.magmaguy.elitemobs.config.ValidMobsConfig; +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; import org.bukkit.entity.EntityType; public class EliteSilverfish extends EliteMobProperties { public EliteSilverfish() { - - this.name = ConfigValues.translationConfig.getString(TranslationConfig.NAME_SILVERFISH); - + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.SILVERFISH).getName(); this.entityType = EntityType.SILVERFISH; - - this.defaultMaxHealth = 20; - - this.validDefensivePowers.addAll(super.getAllDefensivePowers()); - this.validOffensivePowers.addAll(super.getAllOffensivePowers()); - this.validMiscellaneousPowers.addAll(super.getAllMiscellaneousPowers()); - - this.isEnabled = ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.VALID_AGGRESSIVE_ELITEMOBS + getEntityType().toString()) && - ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.ALLOW_AGGRESSIVE_ELITEMOBS); - - if (this.isEnabled) - eliteMobData.add(this); - + this.defaultMaxHealth = 8; + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.SILVERFISH).getBaseDamage(); + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.SILVERFISH).isEnabled(); + eliteMobData.add(this); } } diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteSkeleton.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteSkeleton.java index a2d957d1c..7dd77c301 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteSkeleton.java +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteSkeleton.java @@ -1,39 +1,19 @@ package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.TranslationConfig; -import com.magmaguy.elitemobs.config.ValidMobsConfig; -import com.magmaguy.elitemobs.mobpowers.majorpowers.SkeletonPillar; -import com.magmaguy.elitemobs.mobpowers.majorpowers.SkeletonTrackingArrow; +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; import org.bukkit.entity.EntityType; -import java.util.Arrays; -import java.util.HashSet; - public class EliteSkeleton extends EliteMobProperties { public EliteSkeleton() { - - this.name = ConfigValues.translationConfig.getString(TranslationConfig.NAME_SKELETON); - + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.SKELETON).getName(); this.entityType = EntityType.SKELETON; - this.defaultMaxHealth = 20; - - SkeletonTrackingArrow skeletonTrackingArrow = new SkeletonTrackingArrow(); - SkeletonPillar skeletonPillar = new SkeletonPillar(); - this.validMajorPowers = new HashSet<>(Arrays.asList(skeletonPillar, skeletonTrackingArrow)); - - this.validDefensivePowers.addAll(super.getAllDefensivePowers()); - this.validOffensivePowers.addAll(super.getAllOffensivePowers()); - this.validMiscellaneousPowers.addAll(super.getAllMiscellaneousPowers()); - - this.isEnabled = ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.VALID_AGGRESSIVE_ELITEMOBS + getEntityType().toString()) && - ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.ALLOW_AGGRESSIVE_ELITEMOBS); - - if (this.isEnabled) - eliteMobData.add(this); - + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.SKELETON).getBaseDamage(); + super.addMajorPower("skeleton_pillar.yml"); + super.addMajorPower("skeleton_tracking_arrow.yml"); + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.SKELETON).isEnabled(); + eliteMobData.add(this); } } diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteSpider.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteSpider.java index 931b1f80a..7bc0015ad 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteSpider.java +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteSpider.java @@ -1,30 +1,17 @@ package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.TranslationConfig; -import com.magmaguy.elitemobs.config.ValidMobsConfig; +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; import org.bukkit.entity.EntityType; public class EliteSpider extends EliteMobProperties { public EliteSpider() { - - this.name = ConfigValues.translationConfig.getString(TranslationConfig.NAME_SPIDER); - + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.SPIDER).getName(); this.entityType = EntityType.SPIDER; - this.defaultMaxHealth = 16; - - this.validDefensivePowers.addAll(super.getAllDefensivePowers()); - this.validOffensivePowers.addAll(super.getAllOffensivePowers()); - this.validMiscellaneousPowers.addAll(super.getAllMiscellaneousPowers()); - - this.isEnabled = ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.VALID_AGGRESSIVE_ELITEMOBS + getEntityType().toString()) && - ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.ALLOW_AGGRESSIVE_ELITEMOBS); - - if (this.isEnabled) - eliteMobData.add(this); - + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.SPIDER).getBaseDamage(); + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.SPIDER).isEnabled(); + eliteMobData.add(this); } } diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteStray.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteStray.java index fc0175c38..598078941 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteStray.java +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteStray.java @@ -1,30 +1,17 @@ package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.TranslationConfig; -import com.magmaguy.elitemobs.config.ValidMobsConfig; +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; import org.bukkit.entity.EntityType; public class EliteStray extends EliteMobProperties { public EliteStray() { - - this.name = ConfigValues.translationConfig.getString(TranslationConfig.NAME_STRAY); - + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.STRAY).getName(); this.entityType = EntityType.STRAY; - this.defaultMaxHealth = 20; - - this.validDefensivePowers.addAll(super.getAllDefensivePowers()); - this.validOffensivePowers.addAll(super.getAllOffensivePowers()); - this.validMiscellaneousPowers.addAll(super.getAllMiscellaneousPowers()); - - this.isEnabled = ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.VALID_AGGRESSIVE_ELITEMOBS + getEntityType().toString()) && - ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.ALLOW_AGGRESSIVE_ELITEMOBS); - - if (this.isEnabled) - eliteMobData.add(this); - + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.STRAY).getBaseDamage(); + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.STRAY).isEnabled(); + eliteMobData.add(this); } } diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteVex.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteVex.java index bf1a346c8..21bf98be4 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteVex.java +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteVex.java @@ -1,30 +1,19 @@ package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.TranslationConfig; -import com.magmaguy.elitemobs.config.ValidMobsConfig; +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; +import com.magmaguy.elitemobs.powers.miscellaneouspowers.GroundPound; import org.bukkit.entity.EntityType; public class EliteVex extends EliteMobProperties { public EliteVex() { - - this.name = ConfigValues.translationConfig.getString(TranslationConfig.NAME_VEX); - + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.VEX).getName(); this.entityType = EntityType.VEX; - this.defaultMaxHealth = 14; - - this.validDefensivePowers.addAll(super.getAllDefensivePowers()); - this.validOffensivePowers.addAll(super.getAllOffensivePowers()); - this.validMiscellaneousPowers.addAll(super.getAllMiscellaneousPowers()); - - this.isEnabled = ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.VALID_AGGRESSIVE_ELITEMOBS + getEntityType().toString()) && - ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.ALLOW_AGGRESSIVE_ELITEMOBS); - - if (this.isEnabled) - eliteMobData.add(this); - + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.VEX).getBaseDamage(); + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.VEX).isEnabled(); + super.removeDefensivePower(new GroundPound()); + eliteMobData.add(this); } } diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteVindicator.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteVindicator.java index e931beaef..18afb3a90 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteVindicator.java +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteVindicator.java @@ -1,30 +1,15 @@ package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.TranslationConfig; -import com.magmaguy.elitemobs.config.ValidMobsConfig; +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; import org.bukkit.entity.EntityType; public class EliteVindicator extends EliteMobProperties { - public EliteVindicator() { - - this.name = ConfigValues.translationConfig.getString(TranslationConfig.NAME_VINDICATOR); - + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.VINDICATOR).getName(); this.entityType = EntityType.VINDICATOR; - this.defaultMaxHealth = 24; - - this.validDefensivePowers.addAll(super.getAllDefensivePowers()); - this.validOffensivePowers.addAll(super.getAllOffensivePowers()); - this.validMiscellaneousPowers.addAll(super.getAllMiscellaneousPowers()); - - this.isEnabled = ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.VALID_AGGRESSIVE_ELITEMOBS + getEntityType().toString()) && - ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.ALLOW_AGGRESSIVE_ELITEMOBS); - - if (this.isEnabled) - eliteMobData.add(this); - + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.VINDICATOR).getBaseDamage(); + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.VINDICATOR).isEnabled(); + eliteMobData.add(this); } - } diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteWitch.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteWitch.java index 2cb112c0c..7a97e1c34 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteWitch.java +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteWitch.java @@ -1,30 +1,17 @@ package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.TranslationConfig; -import com.magmaguy.elitemobs.config.ValidMobsConfig; +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; import org.bukkit.entity.EntityType; public class EliteWitch extends EliteMobProperties { public EliteWitch() { - - this.name = ConfigValues.translationConfig.getString(TranslationConfig.NAME_WITCH); - + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.WITCH).getName(); this.entityType = EntityType.WITCH; - this.defaultMaxHealth = 26; - - this.validDefensivePowers.addAll(super.getAllDefensivePowers()); - this.validOffensivePowers.addAll(super.getAllOffensivePowers()); - this.validMiscellaneousPowers.addAll(super.getAllMiscellaneousPowers()); - - this.isEnabled = ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.VALID_AGGRESSIVE_ELITEMOBS + getEntityType().toString()) && - ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.ALLOW_AGGRESSIVE_ELITEMOBS); - - if (this.isEnabled) - eliteMobData.add(this); - + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.WITCH).getBaseDamage(); + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.WITCH).isEnabled(); + eliteMobData.add(this); } } diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteWitherSkeleton.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteWitherSkeleton.java index c5cb0dc0c..e1024409d 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteWitherSkeleton.java +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteWitherSkeleton.java @@ -1,30 +1,17 @@ package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.TranslationConfig; -import com.magmaguy.elitemobs.config.ValidMobsConfig; +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; import org.bukkit.entity.EntityType; public class EliteWitherSkeleton extends EliteMobProperties { public EliteWitherSkeleton() { - - this.name = ConfigValues.translationConfig.getString(TranslationConfig.NAME_WITHER_SKELETON); - + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.WITHER_SKELETON).getName(); this.entityType = EntityType.WITHER_SKELETON; - this.defaultMaxHealth = 20; - - this.validDefensivePowers.addAll(super.getAllDefensivePowers()); - this.validOffensivePowers.addAll(super.getAllOffensivePowers()); - this.validMiscellaneousPowers.addAll(super.getAllMiscellaneousPowers()); - - this.isEnabled = ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.VALID_AGGRESSIVE_ELITEMOBS + getEntityType().toString()) && - ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.ALLOW_AGGRESSIVE_ELITEMOBS); - - if (this.isEnabled) - eliteMobData.add(this); - + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.WITHER_SKELETON).getBaseDamage(); + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.WITHER_SKELETON).isEnabled(); + eliteMobData.add(this); } } diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteWolf.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteWolf.java new file mode 100644 index 000000000..95c7893ac --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteWolf.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; +import org.bukkit.entity.EntityType; + +public class EliteWolf extends EliteMobProperties { + + public EliteWolf() { + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.WOLF).getName(); + this.entityType = EntityType.WOLF; + this.defaultMaxHealth = 8; + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.WOLF).getBaseDamage(); + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.WOLF).isEnabled(); + eliteMobData.add(this); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteZoglin.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteZoglin.java new file mode 100644 index 000000000..0888caace --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteZoglin.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; +import com.magmaguy.elitemobs.utils.VersionChecker; +import org.bukkit.entity.EntityType; + +public class EliteZoglin extends EliteMobProperties { + public EliteZoglin() { + if (VersionChecker.serverVersionOlderThan(16, 0)) { + return; + } + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.ZOGLIN).getName(); + this.entityType = EntityType.ZOGLIN; + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.ZOGLIN).getBaseDamage(); + this.defaultMaxHealth = 40; + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.ZOGLIN).isEnabled(); + eliteMobData.add(this); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteZombie.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteZombie.java index 9a7497cdf..dfe993516 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteZombie.java +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteZombie.java @@ -1,41 +1,21 @@ package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.TranslationConfig; -import com.magmaguy.elitemobs.config.ValidMobsConfig; -import com.magmaguy.elitemobs.mobpowers.majorpowers.*; +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; import org.bukkit.entity.EntityType; -import java.util.Arrays; -import java.util.HashSet; - public class EliteZombie extends EliteMobProperties { public EliteZombie() { - - this.name = ConfigValues.translationConfig.getString(TranslationConfig.NAME_ZOMBIE); - + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.ZOMBIE).getName(); this.entityType = EntityType.ZOMBIE; - this.defaultMaxHealth = 20; - - ZombieBloat zombieBloat = new ZombieBloat(); - ZombieFriends zombieFriends = new ZombieFriends(); - ZombieNecronomicon zombieNecronomicon = new ZombieNecronomicon(); - ZombieParents zombieParents = new ZombieParents(); - ZombieTeamRocket zombieTeamRocket = new ZombieTeamRocket(); - this.validMajorPowers = new HashSet<>(Arrays.asList(zombieBloat, zombieFriends, zombieNecronomicon, zombieParents, zombieTeamRocket)); - - this.validDefensivePowers.addAll(super.getAllDefensivePowers()); - this.validOffensivePowers.addAll(super.getAllOffensivePowers()); - this.validMiscellaneousPowers.addAll(super.getAllMiscellaneousPowers()); - - this.isEnabled = ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.VALID_AGGRESSIVE_ELITEMOBS + getEntityType().toString()) && - ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.ALLOW_AGGRESSIVE_ELITEMOBS); - - if (this.isEnabled) - eliteMobData.add(this); - + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.ZOMBIE).getBaseDamage(); + super.addMajorPower("zombie_bloat.yml"); + super.addMajorPower("zombie_friends.yml"); + super.addMajorPower("zombie_necronomicon.yml"); + super.addMajorPower("zombie_parents.yml"); + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.ZOMBIE).isEnabled(); + eliteMobData.add(this); } } diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteZombifiedPiglin.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteZombifiedPiglin.java new file mode 100644 index 000000000..8d4635a7b --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/aggressivemobs/EliteZombifiedPiglin.java @@ -0,0 +1,19 @@ +package com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs; + +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; +import com.magmaguy.elitemobs.utils.VersionChecker; +import org.bukkit.entity.EntityType; + +public class EliteZombifiedPiglin extends EliteMobProperties { + public EliteZombifiedPiglin() { + if (VersionChecker.serverVersionOlderThan(16, 0)) { + return; + } + this.name = MobPropertiesConfig.getMobProperties().get(EntityType.ZOMBIFIED_PIGLIN).getName(); + this.entityType = EntityType.ZOMBIFIED_PIGLIN; + this.baseDamage = MobPropertiesConfig.getMobProperties().get(EntityType.ZOMBIFIED_PIGLIN).getBaseDamage(); + this.defaultMaxHealth = 20; + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.ZOMBIFIED_PIGLIN).isEnabled(); + eliteMobData.add(this); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/passivemobs/SuperChicken.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/passivemobs/SuperChicken.java index b2269423e..ac02adf4b 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/passivemobs/SuperChicken.java +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/passivemobs/SuperChicken.java @@ -1,22 +1,20 @@ package com.magmaguy.elitemobs.mobconstructor.mobdata.passivemobs; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.TranslationConfig; -import com.magmaguy.elitemobs.config.ValidMobsConfig; +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; import org.bukkit.entity.EntityType; public class SuperChicken extends SuperMobProperties { public SuperChicken() { - this.name = ConfigValues.translationConfig.getString(TranslationConfig.NAME_CHICKEN); + this.name = ChatColorConverter.convert(MobPropertiesConfig.getMobProperties().get(EntityType.CHICKEN).getName()); this.entityType = EntityType.CHICKEN; this.defaultMaxHealth = 4; - this.isEnabled = ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.VALID_SUPERMOBS + getEntityType().toString()) && - ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.ALLOW_PASSIVE_SUPERMOBS); + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.CHICKEN).isEnabled(); if (this.isEnabled) { superMobTypeList.add(this.entityType); diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/passivemobs/SuperCow.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/passivemobs/SuperCow.java index 16131fb47..492c9487c 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/passivemobs/SuperCow.java +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/passivemobs/SuperCow.java @@ -1,22 +1,20 @@ package com.magmaguy.elitemobs.mobconstructor.mobdata.passivemobs; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.TranslationConfig; -import com.magmaguy.elitemobs.config.ValidMobsConfig; +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; import org.bukkit.entity.EntityType; public class SuperCow extends SuperMobProperties { public SuperCow() { - this.name = ConfigValues.translationConfig.getString(TranslationConfig.NAME_COW); + this.name = ChatColorConverter.convert(MobPropertiesConfig.getMobProperties().get(EntityType.COW).getName()); this.entityType = EntityType.COW; this.defaultMaxHealth = 10; - this.isEnabled = ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.VALID_SUPERMOBS + getEntityType().toString()) && - ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.ALLOW_PASSIVE_SUPERMOBS); + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.COW).isEnabled(); if (this.isEnabled) { superMobTypeList.add(this.entityType); diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/passivemobs/SuperMushroomCow.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/passivemobs/SuperMushroomCow.java index 4aef0f914..9c74cd56c 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/passivemobs/SuperMushroomCow.java +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/passivemobs/SuperMushroomCow.java @@ -1,22 +1,20 @@ package com.magmaguy.elitemobs.mobconstructor.mobdata.passivemobs; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.TranslationConfig; -import com.magmaguy.elitemobs.config.ValidMobsConfig; +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; import org.bukkit.entity.EntityType; public class SuperMushroomCow extends SuperMobProperties { public SuperMushroomCow() { - this.name = ConfigValues.translationConfig.getString(TranslationConfig.NAME_MUSHROOM_COW); + this.name = ChatColorConverter.convert(MobPropertiesConfig.getMobProperties().get(EntityType.MUSHROOM_COW).getName()); this.entityType = EntityType.MUSHROOM_COW; this.defaultMaxHealth = 10; - this.isEnabled = ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.VALID_SUPERMOBS + getEntityType().toString()) && - ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.ALLOW_PASSIVE_SUPERMOBS); + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.MUSHROOM_COW).isEnabled(); if (this.isEnabled) { superMobTypeList.add(this.entityType); diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/passivemobs/SuperPig.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/passivemobs/SuperPig.java index 47ef4dd6b..f806b82b9 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/passivemobs/SuperPig.java +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/passivemobs/SuperPig.java @@ -1,22 +1,20 @@ package com.magmaguy.elitemobs.mobconstructor.mobdata.passivemobs; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.TranslationConfig; -import com.magmaguy.elitemobs.config.ValidMobsConfig; +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; import org.bukkit.entity.EntityType; public class SuperPig extends SuperMobProperties { public SuperPig() { - this.name = ConfigValues.translationConfig.getString(TranslationConfig.NAME_PIG); + this.name = ChatColorConverter.convert(MobPropertiesConfig.getMobProperties().get(EntityType.PIG).getName()); this.entityType = EntityType.PIG; this.defaultMaxHealth = 10; - this.isEnabled = ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.VALID_SUPERMOBS + getEntityType().toString()) && - ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.ALLOW_PASSIVE_SUPERMOBS); + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.PIG).isEnabled(); if (this.isEnabled) { superMobTypeList.add(this.entityType); diff --git a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/passivemobs/SuperSheep.java b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/passivemobs/SuperSheep.java index f29491706..4aa991fda 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/passivemobs/SuperSheep.java +++ b/src/main/java/com/magmaguy/elitemobs/mobconstructor/mobdata/passivemobs/SuperSheep.java @@ -1,22 +1,20 @@ package com.magmaguy.elitemobs.mobconstructor.mobdata.passivemobs; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.TranslationConfig; -import com.magmaguy.elitemobs.config.ValidMobsConfig; +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; import org.bukkit.entity.EntityType; public class SuperSheep extends SuperMobProperties { public SuperSheep() { - this.name = ConfigValues.translationConfig.getString(TranslationConfig.NAME_SHEEP); + this.name = ChatColorConverter.convert(MobPropertiesConfig.getMobProperties().get(EntityType.SHEEP).getName()); this.entityType = EntityType.SHEEP; this.defaultMaxHealth = 8; - this.isEnabled = ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.VALID_SUPERMOBS + getEntityType().toString()) && - ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.ALLOW_PASSIVE_SUPERMOBS); + this.isEnabled = MobPropertiesConfig.getMobProperties().get(EntityType.SHEEP).isEnabled(); if (this.isEnabled) { superMobTypeList.add(this.entityType); diff --git a/src/main/java/com/magmaguy/elitemobs/mobpowers/AggroPrevention.java b/src/main/java/com/magmaguy/elitemobs/mobpowers/AggroPrevention.java deleted file mode 100644 index 96b0a3762..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobpowers/AggroPrevention.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.magmaguy.elitemobs.mobpowers; - -import com.magmaguy.elitemobs.EntityTracker; -import org.bukkit.entity.IronGolem; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityTargetLivingEntityEvent; - -public class AggroPrevention implements Listener { - - @EventHandler - public void onTarget(EntityTargetLivingEntityEvent event) { - - if (EntityTracker.isEliteMob(event.getEntity()) && - event.getTarget() != null && EntityTracker.isEliteMob(event.getTarget()) && - !(event.getTarget() instanceof IronGolem) && !(event.getEntity() instanceof IronGolem)) - event.setCancelled(true); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobpowers/ElitePower.java b/src/main/java/com/magmaguy/elitemobs/mobpowers/ElitePower.java deleted file mode 100644 index 6d39ac018..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobpowers/ElitePower.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.magmaguy.elitemobs.mobpowers; - -import org.bukkit.entity.Entity; - -public abstract class ElitePower { - - public abstract void applyPowers(Entity entity); - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobpowers/ProjectileLocationGenerator.java b/src/main/java/com/magmaguy/elitemobs/mobpowers/ProjectileLocationGenerator.java deleted file mode 100644 index 52fa18eeb..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobpowers/ProjectileLocationGenerator.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.mobpowers; - -import org.bukkit.Location; -import org.bukkit.entity.LivingEntity; -import org.bukkit.util.Vector; - -public class ProjectileLocationGenerator { - - public static Location generateLocation(LivingEntity targetter, LivingEntity targetted) { - - Location targetterLocation = targetter.getLocation(); - Vector toTargetVector = targetted.getEyeLocation().subtract(targetterLocation).toVector().normalize(); - Location offsetLocation = new Location(targetterLocation.getWorld(), - targetterLocation.getX() + toTargetVector.getX(), - targetterLocation.getY() + 1, - targetterLocation.getZ() + toTargetVector.getZ()); - - return offsetLocation; - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobpowers/defensivepowers/Invisibility.java b/src/main/java/com/magmaguy/elitemobs/mobpowers/defensivepowers/Invisibility.java deleted file mode 100644 index 1c4647c49..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobpowers/defensivepowers/Invisibility.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.mobpowers.defensivepowers; - -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.mobpowers.minorpowers.MinorPower; -import org.bukkit.entity.Entity; -import org.bukkit.entity.LivingEntity; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; -import org.bukkit.scheduler.BukkitRunnable; - -/** - * Created by MagmaGuy on 28/04/2017. - */ -public class Invisibility extends MinorPower { - - @Override - public void applyPowers(Entity entity) { - new BukkitRunnable() { - @Override - public void run() { - ((LivingEntity) entity).addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, Integer.MAX_VALUE, 1)); - } - }.runTaskLater(MetadataHandler.PLUGIN, 1); - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobpowers/defensivepowers/InvulnerabilityArrow.java b/src/main/java/com/magmaguy/elitemobs/mobpowers/defensivepowers/InvulnerabilityArrow.java deleted file mode 100644 index e9dc8e4b8..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobpowers/defensivepowers/InvulnerabilityArrow.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.mobpowers.defensivepowers; - -import com.magmaguy.elitemobs.EntityTracker; -import com.magmaguy.elitemobs.mobpowers.minorpowers.MinorPower; -import org.bukkit.entity.Entity; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageEvent; - -/** - * Created by MagmaGuy on 05/11/2016. - */ -public class InvulnerabilityArrow extends MinorPower implements Listener { - - @Override - public void applyPowers(Entity entity) { - } - - @EventHandler - public void invulnerablityArrow(EntityDamageEvent event) { - - if (EntityTracker.hasPower(this, event.getEntity())) - if (event.getCause().equals(EntityDamageEvent.DamageCause.PROJECTILE)) - event.setCancelled(true); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobpowers/defensivepowers/InvulnerabilityFallDamage.java b/src/main/java/com/magmaguy/elitemobs/mobpowers/defensivepowers/InvulnerabilityFallDamage.java deleted file mode 100644 index 862900317..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobpowers/defensivepowers/InvulnerabilityFallDamage.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * 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 . - */ - - -package com.magmaguy.elitemobs.mobpowers.defensivepowers; - -import com.magmaguy.elitemobs.EntityTracker; -import com.magmaguy.elitemobs.mobpowers.minorpowers.MinorPower; -import org.bukkit.entity.Entity; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageEvent; - -/** - * Created by MagmaGuy on 28/11/2016. - */ -public class InvulnerabilityFallDamage extends MinorPower implements Listener { - - @Override - public void applyPowers(Entity entity) { - } - - @EventHandler - public void invulnerabilityFallDamage(EntityDamageEvent event) { - - if (event.getCause().equals(EntityDamageEvent.DamageCause.FALL) && EntityTracker.hasPower(this, event.getEntity())) - event.setCancelled(true); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobpowers/defensivepowers/InvulnerabilityFire.java b/src/main/java/com/magmaguy/elitemobs/mobpowers/defensivepowers/InvulnerabilityFire.java deleted file mode 100644 index d8b00a308..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobpowers/defensivepowers/InvulnerabilityFire.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.mobpowers.defensivepowers; - -import com.magmaguy.elitemobs.EntityTracker; -import com.magmaguy.elitemobs.mobpowers.minorpowers.MinorPower; -import org.bukkit.entity.Entity; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageEvent; - -/** - * Created by MagmaGuy on 05/11/2016. - */ -public class InvulnerabilityFire extends MinorPower implements Listener { - - @Override - public void applyPowers(Entity entity) { - } - - @EventHandler - public void invulnerabilityFire(EntityDamageEvent event) { - - if ((event.getCause().equals(EntityDamageEvent.DamageCause.FIRE) || - event.getCause().equals(EntityDamageEvent.DamageCause.FIRE_TICK)) && - EntityTracker.hasPower(this, event.getEntity())) - event.setCancelled(true); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobpowers/defensivepowers/InvulnerabilityKnockback.java b/src/main/java/com/magmaguy/elitemobs/mobpowers/defensivepowers/InvulnerabilityKnockback.java deleted file mode 100644 index a46beb457..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobpowers/defensivepowers/InvulnerabilityKnockback.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.mobpowers.defensivepowers; - -import com.magmaguy.elitemobs.EntityTracker; -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.mobpowers.minorpowers.MinorPower; -import org.bukkit.entity.Entity; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageEvent; -import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.util.Vector; - -/** - * Created by MagmaGuy on 30/04/2017. - */ -public class InvulnerabilityKnockback extends MinorPower implements Listener { - - @Override - public void applyPowers(Entity entity) { - } - - @EventHandler - public void invulnerabilityKnockback(EntityDamageEvent event) { - - if (EntityTracker.hasPower(this, event.getEntity())) { - - event.getEntity().setVelocity(new Vector(0, 0, 0)); - - new BukkitRunnable() { - @Override - public void run() { - event.getEntity().setVelocity(new Vector(0, 0, 0)); - } - }.runTaskLater(MetadataHandler.PLUGIN, 1); - - } - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobpowers/majorpowers/MajorPower.java b/src/main/java/com/magmaguy/elitemobs/mobpowers/majorpowers/MajorPower.java deleted file mode 100644 index a96aa30a8..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobpowers/majorpowers/MajorPower.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.mobpowers.majorpowers; - -import com.magmaguy.elitemobs.mobpowers.ElitePower; - -/** - * Created by MagmaGuy on 10/05/2017. - */ -public abstract class MajorPower extends ElitePower { - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobpowers/majorpowers/SkeletonPillar.java b/src/main/java/com/magmaguy/elitemobs/mobpowers/majorpowers/SkeletonPillar.java deleted file mode 100644 index 23da5e7ca..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobpowers/majorpowers/SkeletonPillar.java +++ /dev/null @@ -1,131 +0,0 @@ -package com.magmaguy.elitemobs.mobpowers.majorpowers; - -import com.magmaguy.elitemobs.EntityTracker; -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; -import com.magmaguy.elitemobs.mobpowers.PowerCooldown; -import com.magmaguy.elitemobs.powerstances.GenericRotationMatrixMath; -import org.bukkit.Location; -import org.bukkit.Particle; -import org.bukkit.entity.*; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.scheduler.BukkitRunnable; - -import java.util.HashSet; -import java.util.concurrent.ThreadLocalRandom; - -public class SkeletonPillar extends MajorPower implements Listener { - - private static HashSet cooldowns = new HashSet<>(); - - private static boolean isInCooldown(EliteMobEntity eliteMobEntity) { - return cooldowns.contains(eliteMobEntity); - } - - public static HashSet getCooldowns(EliteMobEntity eliteMobEntity) { - return cooldowns; - } - - @Override - public void applyPowers(Entity entity) { - } - - @EventHandler - public void onHit(EntityDamageByEntityEvent event) { - - if (event.isCancelled()) return; - if (!event.getEntity().getType().equals(EntityType.SKELETON)) return; - - /* - Run random check to see if the power should activate - */ - if (ThreadLocalRandom.current().nextDouble() > 0.20) return; - - EliteMobEntity eliteMobEntity = EntityTracker.getEliteMobEntity(event.getEntity()); - if (eliteMobEntity == null) return; - - if (!eliteMobEntity.hasPower(this)) return; - if (isInCooldown(eliteMobEntity)) return; - - eliteMobEntity.getLivingEntity().setAI(false); - PowerCooldown.startCooldownTimer(eliteMobEntity, cooldowns, 20 * 27); - - Location location1 = locationMover(eliteMobEntity.getLivingEntity().getLocation().clone(), 20, 7); - Location location2 = locationMover(eliteMobEntity.getLivingEntity().getLocation().clone(), 20, 7); - - new BukkitRunnable() { - - int timer = 1; - - @Override - public void run() { - - if (timer > 20 * 7 || !eliteMobEntity.getLivingEntity().isValid()) { - - eliteMobEntity.getLivingEntity().setAI(true); - cancel(); - - } else if (timer > 20 * 1 && timer < 20 * 7) { - - pillarEffect(location1, timer, 7); - pillarEffect(location2, timer, -7); - - } else { - - pillarWarningEffect(location1); - pillarWarningEffect(location2); - - } - - timer++; - - } - - }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); - - } - - private void pillarEffect(Location location, int timer, int offset) { - - location.getWorld().spawnParticle(Particle.EXPLOSION_NORMAL, location, 50, 0.1, 5, 0.1, 0.05); - locationMover(location, timer, offset); - pillarDamage(location); - - } - - private void pillarWarningEffect(Location location) { - - location.getWorld().spawnParticle(Particle.SMOKE_LARGE, location, 10, 0.1, 5, 0.1, 0.05); - - } - - private void pillarDamage(Location location) { - - for (Entity entity : location.getWorld().getNearbyEntities(location, 2, 5, 2)) - if (entity instanceof LivingEntity && !(entity instanceof Pig || entity instanceof Cow || entity instanceof Chicken || - entity instanceof Wolf || entity instanceof Llama || entity instanceof Ocelot || entity instanceof Horse || - entity instanceof Sheep || entity instanceof Rabbit || entity instanceof Parrot || entity instanceof Villager)) { - - LivingEntity livingEntity = (LivingEntity) entity; - - if (livingEntity.isValid()) - livingEntity.damage(1); - - } - - } - - private Location locationMover(Location location, int timer, int offset) { - - int numberOfPointsPerRotation = 20 * 3; - - Location newLocation = GenericRotationMatrixMath.applyRotation(0, 1, 0, numberOfPointsPerRotation, - 0, 0, offset, timer).toLocation(location.getWorld()); - - return newLocation.add(location); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobpowers/majorpowers/SkeletonTrackingArrow.java b/src/main/java/com/magmaguy/elitemobs/mobpowers/majorpowers/SkeletonTrackingArrow.java deleted file mode 100644 index 6c170fb31..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobpowers/majorpowers/SkeletonTrackingArrow.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * 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 . - */ - -/* - * 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 . - */ - -package com.magmaguy.elitemobs.mobpowers.majorpowers; - -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; -import com.magmaguy.elitemobs.mobpowers.minorpowers.EventValidator; -import com.magmaguy.elitemobs.mobpowers.offensivepowers.AttackArrow; -import com.magmaguy.elitemobs.utils.VersionChecker; -import org.bukkit.GameMode; -import org.bukkit.Particle; -import org.bukkit.entity.Arrow; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityTargetLivingEntityEvent; -import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.util.Vector; - -import java.util.HashSet; - -public class SkeletonTrackingArrow extends MajorPower implements Listener { - - private static HashSet currentlyFiringEntities = new HashSet<>(); - - @Override - public void applyPowers(Entity entity) { - - if (VersionChecker.currentVersionIsUnder(10, 0)) return; - - } - - @EventHandler - public void targetEvent(EntityTargetLivingEntityEvent event) { - - EliteMobEntity eliteMobEntity = EventValidator.getEventEliteMob(this, event); - if (eliteMobEntity == null) return; - if (currentlyFiringEntities.contains(eliteMobEntity)) return; - repeatingTrackingArrowTask(event.getEntity()); - currentlyFiringEntities.add(eliteMobEntity); - - } - - private void repeatingTrackingArrowTask(Entity entity) { - - new BukkitRunnable() { - - @Override - public void run() { - - if (!entity.isValid() || entity.isDead()) { - - cancel(); - return; - - } - - for (Entity nearbyEntity : entity.getNearbyEntities(20, 20, 20)) - if (nearbyEntity instanceof Player) - if (((Player) nearbyEntity).getGameMode().equals(GameMode.ADVENTURE) || - ((Player) nearbyEntity).getGameMode().equals(GameMode.SURVIVAL)) { - Arrow arrow = AttackArrow.shootArrow(entity, (Player) nearbyEntity); - arrow.setVelocity(arrow.getVelocity().multiply(0.1)); - arrow.setGravity(false); - trackingArrowLoop((Player) nearbyEntity, arrow); - } - - - } - - }.runTaskTimer(MetadataHandler.PLUGIN, 0, 20 * 8); - - } - - public static HashSet trackingArrowList = new HashSet<>(); - - private static void trackingArrowLoop(Player player, Arrow arrow) { - - trackingArrowList.add(arrow); - - new BukkitRunnable() { - - int counter = 0; - - @Override - public void run() { - - if (player.isValid() && !player.isDead() && arrow.isValid() && arrow.getWorld().equals(player.getWorld()) - && player.getLocation().distanceSquared(arrow.getLocation()) < 900 && !arrow.isOnGround()) { - - if (counter % 10 == 0) { - - arrow.setVelocity(arrow.getVelocity().add(arrowAdjustmentVector(arrow, player))); - - } - - arrow.getWorld().spawnParticle(Particle.FLAME, arrow.getLocation(), 10, 0.01, 0.01, 0.01, 0.01); - - } else { - - arrow.setGravity(true); - trackingArrowList.remove(arrow); - cancel(); - - } - - if (counter > 20 * 60) { - arrow.setGravity(true); - trackingArrowList.remove(arrow); - cancel(); - } - - counter++; - - } - - }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); - - } - - private static Vector arrowAdjustmentVector(Arrow arrow, Player player) { - - return player.getEyeLocation().subtract(arrow.getLocation()).toVector() - .normalize().multiply(0.1); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobpowers/majorpowers/ZombieFriends.java b/src/main/java/com/magmaguy/elitemobs/mobpowers/majorpowers/ZombieFriends.java deleted file mode 100644 index fee7fee16..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobpowers/majorpowers/ZombieFriends.java +++ /dev/null @@ -1,125 +0,0 @@ -package com.magmaguy.elitemobs.mobpowers.majorpowers; - -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; -import com.magmaguy.elitemobs.mobconstructor.ReinforcementMobEntity; -import com.magmaguy.elitemobs.mobpowers.minorpowers.EventValidator; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageEvent; -import org.bukkit.scheduler.BukkitRunnable; - -import java.util.HashSet; -import java.util.concurrent.ThreadLocalRandom; - -import static com.magmaguy.elitemobs.ChatColorConverter.convert; - -/** - * Created by MagmaGuy on 18/05/2017. - */ -public class ZombieFriends extends MajorPower implements Listener { - - public static HashSet activatedZombies = new HashSet<>(); - - @Override - public void applyPowers(Entity entity) { - } - - @EventHandler - public void onHit(EntityDamageEvent event) { - - EliteMobEntity eliteMobEntity = EventValidator.getEventEliteMob(this, event); - if (eliteMobEntity == null) return; - if (ThreadLocalRandom.current().nextDouble() > 0.01) return; - if (activatedZombies.contains(eliteMobEntity)) return; - activatedZombies.add(eliteMobEntity); - - ReinforcementMobEntity reinforcement1 = new ReinforcementMobEntity(EntityType.ZOMBIE, eliteMobEntity.getLivingEntity().getLocation(), - eliteMobEntity.getLevel(), ConfigValues.translationConfig.getString("ZombieFriends.Friend 1")); - - ReinforcementMobEntity reinforcement2 = new ReinforcementMobEntity(EntityType.ZOMBIE, eliteMobEntity.getLivingEntity().getLocation(), - eliteMobEntity.getLevel(), ConfigValues.translationConfig.getString("ZombieFriends.Friend 2")); - - new BukkitRunnable() { - @Override - public void run() { - if (!eliteMobEntity.getLivingEntity().isValid() || !reinforcement1.getLivingEntity().isValid() && !reinforcement2.getLivingEntity().isValid()) { - - if (reinforcement1.getLivingEntity().isValid()) { - - nameClearer(reinforcement1); - - reinforcement1.getLivingEntity().setCustomName(convert(ConfigValues.translationConfig.getStringList("ZombieFriends.DeathMessage"). - get(ThreadLocalRandom.current().nextInt(ConfigValues.translationConfig.getStringList("ZombieFriends.DeathMessage") - .size())))); - - } - - if (reinforcement2.getLivingEntity().isValid()) { - - - nameClearer(reinforcement2); - - reinforcement2.getLivingEntity().setCustomName(convert(ConfigValues.translationConfig.getStringList("ZombieFriends.DeathMessage"). - get(ThreadLocalRandom.current().nextInt(ConfigValues.translationConfig.getStringList("ZombieFriends.DeathMessage") - .size())))); - - } - - cancel(); - return; - - } else { - - if (ThreadLocalRandom.current().nextDouble() < 0.5) { - - nameClearer(eliteMobEntity); - - eliteMobEntity.getLivingEntity().setCustomName(convert(ConfigValues.translationConfig.getStringList("ZombieFriends.ZombieDialog"). - get(ThreadLocalRandom.current().nextInt(ConfigValues.translationConfig.getStringList("ZombieFriends.ZombieDialog") - .size())))); - - } - - if (ThreadLocalRandom.current().nextDouble() < 0.5 && reinforcement1.getLivingEntity().isValid()) { - - nameClearer(reinforcement1); - - reinforcement1.getLivingEntity().setCustomName(convert(ConfigValues.translationConfig.getStringList("ZombieFriends.FriendDialog"). - get(ThreadLocalRandom.current().nextInt(ConfigValues.translationConfig.getStringList("ZombieFriends.FriendDialog") - .size())))); - - } - - if (ThreadLocalRandom.current().nextDouble() < 0.5 && reinforcement2.getLivingEntity().isValid()) { - - nameClearer(reinforcement2); - - reinforcement2.getLivingEntity().setCustomName(convert(ConfigValues.translationConfig.getStringList("ZombieFriends.FriendDialog"). - get(ThreadLocalRandom.current().nextInt(ConfigValues.translationConfig.getStringList("ZombieFriends.FriendDialog") - .size())))); - - } - - } - } - }.runTaskTimer(MetadataHandler.PLUGIN, 20, 20 * 8); - - } - - private void nameClearer(EliteMobEntity eliteMobEntity) { - - new BukkitRunnable() { - @Override - public void run() { - if (eliteMobEntity.getLivingEntity().isValid()) - eliteMobEntity.setName(eliteMobEntity.getName()); - } - }.runTaskLater(MetadataHandler.PLUGIN, 20 * 3); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobpowers/majorpowers/ZombieNecronomicon.java b/src/main/java/com/magmaguy/elitemobs/mobpowers/majorpowers/ZombieNecronomicon.java deleted file mode 100644 index 3f6905818..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobpowers/majorpowers/ZombieNecronomicon.java +++ /dev/null @@ -1,330 +0,0 @@ -/* - * 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 . - */ - -/* - * 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 . - */ - -/* - * 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 . - */ - -package com.magmaguy.elitemobs.mobpowers.majorpowers; - -import com.magmaguy.elitemobs.ChatColorConverter; -import com.magmaguy.elitemobs.EntityTracker; -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; -import com.magmaguy.elitemobs.mobconstructor.ReinforcementMobEntity; -import com.magmaguy.elitemobs.mobpowers.minorpowers.EventValidator; -import com.magmaguy.elitemobs.powerstances.GenericRotationMatrixMath; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.entity.*; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDeathEvent; -import org.bukkit.event.entity.EntityTargetLivingEntityEvent; -import org.bukkit.inventory.ItemStack; -import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.util.Vector; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.concurrent.ThreadLocalRandom; - -import static com.magmaguy.elitemobs.ChatColorConverter.convert; - -/** - * Created by MagmaGuy on 18/05/2017. - */ -public class ZombieNecronomicon extends MajorPower implements Listener { - - private int chantIndex = 0; - private boolean summoningEffectOn = false; - private HashSet chantingMobs = new HashSet<>(); - - @Override - public void applyPowers(Entity entity) { - } - - @EventHandler - public void onPlayerDetect(EntityTargetLivingEntityEvent event) { - - EliteMobEntity eliteMobEntity = EventValidator.getEventEliteMob(this, event); - if (eliteMobEntity == null) return; - - if (chantingMobs.contains(eliteMobEntity)) return; - chantingMobs.add(eliteMobEntity); - - necronomiconVisualEffect(eliteMobEntity); - spawnReinforcements(eliteMobEntity, event.getTarget()); - - } - - private void necronomiconVisualEffect(EliteMobEntity eliteMobEntity) { - - Zombie zombie = (Zombie) eliteMobEntity.getLivingEntity(); - - zombie.setAI(false); - summoningEffectOn = true; - nameScroller(zombie); - - if (!ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.ENABLE_WARNING_VISUAL_EFFECTS)) - return; - - new BukkitRunnable() { - - int counter = 0; - HashMap> fourTrack = new HashMap(); - - @Override - public void run() { - - if (!zombie.isValid() || zombie.hasAI()) { - - for (List itemList : fourTrack.values()) - for (Item item : itemList) - item.remove(); - - if (zombie.isValid()) - zombie.setCustomName(EntityTracker.getEliteMobEntity(zombie).getName()); - - summoningEffectOn = false; - cancel(); - return; - - } - - if (counter == 0) { - - //establish 4tracks - for (int i = 0; i < 8; i++) { - - List itemList = new ArrayList<>(); - - for (int j = 0; j < 4; j++) { - - ItemStack itemStack = new ItemStack(Material.WRITTEN_BOOK, 1); - - Item item = zombie.getWorld().dropItem(zombie.getLocation(), itemStack); - item.setGravity(false); - item.setPickupDelay(Integer.MAX_VALUE); - EntityTracker.registerItemVisualEffects(item); -// MetadataHandler.registerMetadata(item, MetadataHandler.BETTERDROPS_COMPATIBILITY_MD, true); - - itemList.add(item); - - } - - fourTrack.put(i, itemList); - - } - - } else - itemMover(fourTrack, zombie, counter); - - - counter++; - - } - - }.runTaskTimer(MetadataHandler.PLUGIN, 5, 5); - - } - - private void itemMover(HashMap> xTrack, Entity entity, int counter) { - - double a = 0; - double b = 1; - double c = 0; - - double numberOfPointsPerFullRotation = 64; - - double x = 0; - double y = 0; - double z; - - for (int trackNumber : xTrack.keySet()) { - - List itemList = xTrack.get(trackNumber); - - for (Item item : itemList) { - - //each track is offset by 45 degrees - //items are then offset on the Z value depending on their position - - z = (itemList.indexOf(item) + 1); - - //to predict the counter offset value you have to divide 8 (for 8 tracks total) - - int newCounter = (int) (counter + trackNumber * (numberOfPointsPerFullRotation / 8)); - - Location currentLocation = item.getLocation(); - - Location centerLocationFixed = entity.getLocation().add(0, 3, 0); - - Vector vector = GenericRotationMatrixMath.applyRotation(a, b, c, numberOfPointsPerFullRotation, x, y, z, newCounter); - Location newLocation = new Location(entity.getWorld(), vector.getX(), vector.getY(), vector.getZ()).add(centerLocationFixed); - - Vector velocity = (newLocation.subtract(currentLocation)).toVector().multiply(0.3); - item.setVelocity(velocity); - - } - - } - - } - - private void nameScroller(Zombie zombie) { - - new BukkitRunnable() { - - String fullChant = convert(ConfigValues.translationConfig.getString("ZombieNecronomicon.Summoning chant")); - - @Override - public void run() { - - if (!zombie.isValid() || zombie.hasAI()) { - - cancel(); - return; - - } - - if (chantIndex + 31 > fullChant.length()) { - - chantIndex = 0; - - } - - String subString = fullChant.substring(chantIndex, chantIndex + 31); - - zombie.setCustomName(subString); - - chantIndex++; - - - } - - }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); - - } - - private void spawnReinforcements(EliteMobEntity eliteMobEntity, LivingEntity targetted) { - - LivingEntity targetter = eliteMobEntity.getLivingEntity(); - - new BukkitRunnable() { - - ArrayList entityList = new ArrayList<>(); - - @Override - public void run() { - - if (!targetted.isValid() || !targetter.isValid() || targetted.getWorld() != targetter.getWorld() - || targetted.getLocation().distance(targetter.getLocation()) > 30) { - - for (Entity entity : entityList) - if (entity.isValid()) - entity.remove(); - - targetter.setAI(true); - chantingMobs.remove(targetter); - cancel(); - return; - - } - - int randomizedNumber = ThreadLocalRandom.current().nextInt(5) + 1; - - entityList.removeIf(currentEntity -> !currentEntity.isValid()); - - if (entityList.size() < 11) { - - targetter.setAI(false); - - if (!summoningEffectOn) - necronomiconVisualEffect(eliteMobEntity); - - if (randomizedNumber < 5) { - - ReinforcementMobEntity trashMobEntity = new ReinforcementMobEntity(EntityType.ZOMBIE, targetter.getLocation(), eliteMobEntity.getLevel(), - ChatColorConverter.convert(ConfigValues.translationConfig.getString("ZombieNecronomicon.Summoned zombie"))); - - trashMobEntity.getLivingEntity().setVelocity(new Vector((ThreadLocalRandom.current().nextDouble() - 0.5) / 30, 0.5, - (ThreadLocalRandom.current().nextDouble() - 0.5) / 30)); - - entityList.add(trashMobEntity.getLivingEntity()); - - } else { - - ReinforcementMobEntity trashMobEntity = new ReinforcementMobEntity(EntityType.SKELETON, targetter.getLocation(), eliteMobEntity.getLevel(), - ChatColorConverter.convert(ConfigValues.translationConfig.getString("ZombieNecronomicon.Summoned skeleton"))); - - trashMobEntity.getLivingEntity().setVelocity(new Vector((ThreadLocalRandom.current().nextDouble() - 0.5) / 30, 0.5, - (ThreadLocalRandom.current().nextDouble() - 0.5) / 30)); - - entityList.add(trashMobEntity.getLivingEntity()); - - } - - } else - targetter.setAI(true); - - - } - - }.runTaskTimer(MetadataHandler.PLUGIN, 20 * 3, 20 * 5); - - } - - @EventHandler - public void onSummonedCreatureDeath(EntityDeathEvent event) { - - if (event.getEntity() instanceof Zombie && EntityTracker.isEliteMob(event.getEntity()) && event.getEntity().getCustomName() != null && - (event.getEntity().getCustomName().equals(ConfigValues.translationConfig.getString("ZombieNecronomicon.Summoned zombie")) || - event.getEntity().getCustomName().equals(ConfigValues.translationConfig.getString("ZombieNecronomicon.Summoned skeleton")))) - event.getDrops().clear(); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobpowers/majorpowers/ZombieParents.java b/src/main/java/com/magmaguy/elitemobs/mobpowers/majorpowers/ZombieParents.java deleted file mode 100644 index 868bb5d10..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobpowers/majorpowers/ZombieParents.java +++ /dev/null @@ -1,176 +0,0 @@ -/* - * 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 . - */ - -/* - * 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 . - */ - -/* - * 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 . - */ - -package com.magmaguy.elitemobs.mobpowers.majorpowers; - -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; -import com.magmaguy.elitemobs.mobconstructor.ReinforcementMobEntity; -import com.magmaguy.elitemobs.mobpowers.minorpowers.EventValidator; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.LivingEntity; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageEvent; -import org.bukkit.scheduler.BukkitRunnable; - -import java.util.HashSet; -import java.util.concurrent.ThreadLocalRandom; - -import static com.magmaguy.elitemobs.ChatColorConverter.convert; - -/** - * Created by MagmaGuy on 13/05/2017. - */ -public class ZombieParents extends MajorPower implements Listener { - - public static HashSet activatedZombies = new HashSet<>(); - - @Override - public void applyPowers(Entity entity) { - } - - @EventHandler - public void onHit(EntityDamageEvent event) { - - EliteMobEntity eliteMobEntity = EventValidator.getEventEliteMob(this, event); - if (eliteMobEntity == null) return; - if (ThreadLocalRandom.current().nextDouble() > 0.01) return; - if (activatedZombies.contains(eliteMobEntity)) return; - - ReinforcementMobEntity reinforcementMom = new ReinforcementMobEntity(EntityType.ZOMBIE, eliteMobEntity.getLivingEntity().getLocation(), eliteMobEntity.getLevel(), - ConfigValues.translationConfig.getString("ZombieParents.Mom Name")); - - LivingEntity zombieMom = reinforcementMom.getLivingEntity(); - - ReinforcementMobEntity reinforcementDad = new ReinforcementMobEntity(EntityType.ZOMBIE, eliteMobEntity.getLivingEntity().getLocation(), eliteMobEntity.getLevel(), - ConfigValues.translationConfig.getString("ZombieParents.Dad Name")); - - LivingEntity zombieDad = reinforcementDad.getLivingEntity(); - - new BukkitRunnable() { - - @Override - public void run() { - - if (!eliteMobEntity.getLivingEntity().isValid()) { - - if (zombieDad.isValid()) { - - nameClearer(reinforcementDad); - - zombieDad.setCustomName(convert(ConfigValues.translationConfig.getStringList("ZombieParents.DeathMessage"). - get(ThreadLocalRandom.current().nextInt(ConfigValues.translationConfig.getStringList("ZombieParents.DeathMessage") - .size())))); - - } - - if (zombieMom.isValid()) { - - nameClearer(reinforcementMom); - - zombieMom.setCustomName(convert(ConfigValues.translationConfig.getStringList("ZombieParents.DeathMessage"). - get(ThreadLocalRandom.current().nextInt(ConfigValues.translationConfig.getStringList("ZombieParents.DeathMessage") - .size())))); - - } - - cancel(); - - } else { - - if (ThreadLocalRandom.current().nextDouble() < 0.5) { - - nameClearer(eliteMobEntity); - - eliteMobEntity.getLivingEntity().setCustomName(convert(ConfigValues.translationConfig.getStringList("ZombieParents.ZombieDialog"). - get(ThreadLocalRandom.current().nextInt(ConfigValues.translationConfig.getStringList("ZombieParents.ZombieDialog") - .size())))); - - } - - if (ThreadLocalRandom.current().nextDouble() < 0.5 && zombieDad.isValid()) { - - nameClearer(reinforcementDad); - - zombieDad.setCustomName(convert(ConfigValues.translationConfig.getStringList("ZombieParents.ZombieDadDialog"). - get(ThreadLocalRandom.current().nextInt(ConfigValues.translationConfig.getStringList("ZombieParents.ZombieDadDialog") - .size())))); - - } - - if (ThreadLocalRandom.current().nextDouble() < 0.5 && zombieMom.isValid()) { - - nameClearer(reinforcementMom); - - zombieMom.setCustomName(convert(ConfigValues.translationConfig.getStringList("ZombieParents.ZombieMomDialog"). - get(ThreadLocalRandom.current().nextInt(ConfigValues.translationConfig.getStringList("ZombieParents.ZombieMomDialog") - .size())))); - - } - - } - - } - - }.runTaskTimer(MetadataHandler.PLUGIN, 20, 20 * 8); - - } - - private void nameClearer(EliteMobEntity eliteMobEntity) { - - new BukkitRunnable() { - @Override - public void run() { - if (eliteMobEntity.getLivingEntity().isValid()) - eliteMobEntity.setName(eliteMobEntity.getName()); - } - }.runTaskLater(MetadataHandler.PLUGIN, 20 * 3); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobpowers/majorpowers/ZombieTeamRocket.java b/src/main/java/com/magmaguy/elitemobs/mobpowers/majorpowers/ZombieTeamRocket.java deleted file mode 100644 index 59c567c42..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobpowers/majorpowers/ZombieTeamRocket.java +++ /dev/null @@ -1,252 +0,0 @@ -/* - * 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 . - */ - -/* - * 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 . - */ - -/* - * 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 . - */ - -package com.magmaguy.elitemobs.mobpowers.majorpowers; - -import com.magmaguy.elitemobs.EntityTracker; -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; -import com.magmaguy.elitemobs.mobconstructor.ReinforcementMobEntity; -import com.magmaguy.elitemobs.mobpowers.minorpowers.EventValidator; -import org.bukkit.Color; -import org.bukkit.Material; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Ocelot; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageEvent; -import org.bukkit.event.entity.EntityDeathEvent; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.LeatherArmorMeta; -import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.util.Vector; - -import java.util.HashSet; -import java.util.concurrent.ThreadLocalRandom; - -import static com.magmaguy.elitemobs.ChatColorConverter.convert; - -/** - * Created by MagmaGuy on 07/05/2017. - */ -public class ZombieTeamRocket extends MajorPower implements Listener { - - private static final ItemStack TEAM_ROCKET_CHESTPIECE = new ItemStack(Material.LEATHER_CHESTPLATE, 1); - private static final ItemStack TEAM_ROCKET_LEGGINGS = new ItemStack(Material.LEATHER_LEGGINGS, 1); - private static final ItemStack TEAM_ROCKET_BOOTS = new ItemStack(Material.LEATHER_BOOTS, 1); - private static final ItemStack TEAM_ROCKET_HELMET = new ItemStack(Material.LEATHER_HELMET, 1); - public static HashSet activatedZombies = new HashSet<>(); - - @Override - public void applyPowers(Entity entity) { - } - - @EventHandler - public void onHit(EntityDamageEvent event) { - - EliteMobEntity eliteMobEntity = EventValidator.getEventEliteMob(this, event); - if (eliteMobEntity == null) return; - if (ThreadLocalRandom.current().nextDouble() < 0.20) return; - if (activatedZombies.contains(eliteMobEntity)) return; - activatedZombies.add(eliteMobEntity); - - LeatherArmorMeta teamRocketChestpieceMeta = (LeatherArmorMeta) TEAM_ROCKET_CHESTPIECE.getItemMeta(); - teamRocketChestpieceMeta.setColor(Color.WHITE); - TEAM_ROCKET_CHESTPIECE.setItemMeta(teamRocketChestpieceMeta); - - LeatherArmorMeta teamRocketLeggingsMeta = (LeatherArmorMeta) TEAM_ROCKET_CHESTPIECE.getItemMeta(); - teamRocketLeggingsMeta.setColor(Color.WHITE); - TEAM_ROCKET_LEGGINGS.setItemMeta(teamRocketLeggingsMeta); - - LeatherArmorMeta teamRocketBootsMeta = (LeatherArmorMeta) TEAM_ROCKET_BOOTS.getItemMeta(); - teamRocketBootsMeta.setColor(Color.BLACK); - TEAM_ROCKET_BOOTS.setItemMeta(teamRocketBootsMeta); - - ItemStack jesseHelmet = TEAM_ROCKET_HELMET.clone(); - LeatherArmorMeta jesseHelmetMeta = (LeatherArmorMeta) jesseHelmet.getItemMeta(); - jesseHelmetMeta.setColor(Color.PURPLE); - jesseHelmet.setItemMeta(jesseHelmetMeta); - - ItemStack jamesHelmet = TEAM_ROCKET_HELMET.clone(); - LeatherArmorMeta jamesHelmetMeta = (LeatherArmorMeta) jamesHelmet.getItemMeta(); - jamesHelmetMeta.setColor(Color.BLUE); - jamesHelmet.setItemMeta(jamesHelmetMeta); - - ReinforcementMobEntity jesseReinforcement = new ReinforcementMobEntity(EntityType.ZOMBIE, eliteMobEntity.getLivingEntity().getLocation(), eliteMobEntity.getLevel(), "Jesse"); - jesseReinforcement.getLivingEntity().getEquipment().setHelmet(jesseHelmet); - jesseReinforcement.getLivingEntity().getEquipment().setChestplate(TEAM_ROCKET_CHESTPIECE); - jesseReinforcement.getLivingEntity().getEquipment().setLeggings(TEAM_ROCKET_LEGGINGS); - jesseReinforcement.getLivingEntity().getEquipment().setBoots(TEAM_ROCKET_BOOTS); - - ReinforcementMobEntity jamesReinforcement = new ReinforcementMobEntity(EntityType.ZOMBIE, eliteMobEntity.getLivingEntity().getLocation(), eliteMobEntity.getLevel(), "James"); - jamesReinforcement.getLivingEntity().getEquipment().setHelmet(jamesHelmet); - jamesReinforcement.getLivingEntity().getEquipment().setChestplate(TEAM_ROCKET_CHESTPIECE); - jamesReinforcement.getLivingEntity().getEquipment().setLeggings(TEAM_ROCKET_LEGGINGS); - jamesReinforcement.getLivingEntity().getEquipment().setBoots(TEAM_ROCKET_BOOTS); - - Ocelot meowth = (Ocelot) eliteMobEntity.getLivingEntity().getWorld().spawnEntity(eliteMobEntity.getLivingEntity().getLocation(), EntityType.OCELOT); - meowth.setCustomName("Meowth"); - - (eliteMobEntity.getLivingEntity()).getEquipment().setChestplate(TEAM_ROCKET_CHESTPIECE); - (eliteMobEntity.getLivingEntity()).getEquipment().setLeggings(TEAM_ROCKET_LEGGINGS); - (eliteMobEntity.getLivingEntity()).getEquipment().setBoots(TEAM_ROCKET_BOOTS); - eliteMobEntity.setHasCustomPowers(true); - - new BukkitRunnable() { - - int counter = 1; - - @Override - public void run() { - - switch (counter) { - - case 1: - jesseReinforcement.getLivingEntity().setCustomNameVisible(true); - jesseReinforcement.getLivingEntity().setCustomName(convert(ConfigValues.translationConfig.getStringList("ZombieTeamRocket.Intro").get(0))); - break; - case 2: - jesseReinforcement.getLivingEntity().setCustomNameVisible(false); - jamesReinforcement.getLivingEntity().setCustomName(convert(ConfigValues.translationConfig.getStringList("ZombieTeamRocket.Intro").get(1))); - jamesReinforcement.getLivingEntity().setCustomNameVisible(true); - break; - case 3: - jamesReinforcement.getLivingEntity().setCustomNameVisible(false); - jesseReinforcement.getLivingEntity().setCustomName(convert(ConfigValues.translationConfig.getStringList("ZombieTeamRocket.Intro").get(2))); - jesseReinforcement.getLivingEntity().setCustomNameVisible(true); - break; - case 4: - jesseReinforcement.getLivingEntity().setCustomName(convert(ConfigValues.translationConfig.getStringList("ZombieTeamRocket.Intro").get(3))); - break; - case 5: - jesseReinforcement.getLivingEntity().setCustomNameVisible(false); - jamesReinforcement.getLivingEntity().setCustomName(convert(ConfigValues.translationConfig.getStringList("ZombieTeamRocket.Intro").get(4))); - jamesReinforcement.getLivingEntity().setCustomNameVisible(true); - break; - case 6: - jamesReinforcement.getLivingEntity().setCustomName(convert(ConfigValues.translationConfig.getStringList("ZombieTeamRocket.Intro").get(5))); - break; - case 7: - jamesReinforcement.getLivingEntity().setCustomNameVisible(false); - jesseReinforcement.getLivingEntity().setCustomName(convert(ConfigValues.translationConfig.getStringList("ZombieTeamRocket.Intro").get(6))); - jesseReinforcement.getLivingEntity().setCustomNameVisible(true); - break; - case 8: - jesseReinforcement.getLivingEntity().setCustomName(convert(ConfigValues.translationConfig.getStringList("ZombieTeamRocket.Intro").get(7))); - break; - case 9: - jesseReinforcement.getLivingEntity().setCustomNameVisible(false); - jamesReinforcement.getLivingEntity().setCustomName(convert(ConfigValues.translationConfig.getStringList("ZombieTeamRocket.Intro").get(8))); - jamesReinforcement.getLivingEntity().setCustomNameVisible(true); - break; - case 10: - jamesReinforcement.getLivingEntity().setCustomName(convert(ConfigValues.translationConfig.getStringList("ZombieTeamRocket.Intro").get(9))); - break; - case 11: - jamesReinforcement.getLivingEntity().setCustomNameVisible(false); - jesseReinforcement.getLivingEntity().setCustomName(convert(ConfigValues.translationConfig.getStringList("ZombieTeamRocket.Intro").get(10))); - jesseReinforcement.getLivingEntity().setCustomNameVisible(true); - break; - case 12: - jesseReinforcement.getLivingEntity().setCustomNameVisible(false); - jamesReinforcement.getLivingEntity().setCustomName(convert(ConfigValues.translationConfig.getStringList("ZombieTeamRocket.Intro").get(11))); - jamesReinforcement.getLivingEntity().setCustomNameVisible(true); - break; - case 13: - jamesReinforcement.getLivingEntity().setCustomNameVisible(false); - jesseReinforcement.getLivingEntity().setCustomName(convert(ConfigValues.translationConfig.getStringList("ZombieTeamRocket.Intro").get(12))); - jesseReinforcement.getLivingEntity().setCustomNameVisible(true); - break; - case 14: - jesseReinforcement.getLivingEntity().setCustomName(convert(ConfigValues.translationConfig.getStringList("ZombieTeamRocket.Intro").get(13))); - break; - case 15: - jesseReinforcement.getLivingEntity().setCustomNameVisible(false); - jamesReinforcement.getLivingEntity().setCustomName(convert(ConfigValues.translationConfig.getStringList("ZombieTeamRocket.Intro").get(14))); - jamesReinforcement.getLivingEntity().setCustomNameVisible(true); - break; - case 16: - jamesReinforcement.getLivingEntity().setCustomName(convert(ConfigValues.translationConfig.getStringList("ZombieTeamRocket.Intro").get(15))); - break; - case 17: - jamesReinforcement.getLivingEntity().setCustomNameVisible(false); - meowth.setCustomName(convert(ConfigValues.translationConfig.getStringList("ZombieTeamRocket.Intro").get(16))); - meowth.setCustomNameVisible(true); - break; - case 18: - jesseReinforcement.getLivingEntity().setCustomName(convert(ConfigValues.translationConfig.getString("ZombieTeamRocket.Jesse name"))); - jesseReinforcement.getLivingEntity().setCustomNameVisible(true); - jamesReinforcement.getLivingEntity().setCustomName(convert(ConfigValues.translationConfig.getString("ZombieTeamRocket.James name"))); - jamesReinforcement.getLivingEntity().setCustomNameVisible(true); - meowth.setCustomName(convert(ConfigValues.translationConfig.getString("ZombieTeamRocket.Meowth name"))); - case 30: - meowth.remove(); - cancel(); - break; - - } - - counter++; - - } - - }.runTaskTimer(MetadataHandler.PLUGIN, 1, 15 * 2); - - - } - - @EventHandler - public void onDeath(EntityDeathEvent event) { - - if (!EntityTracker.hasPower(this, event.getEntity())) return; - - event.getEntity().setCustomName(convert(ConfigValues.translationConfig.getString("ZombieTeamRocket.DeathMessage"))); - event.getEntity().setVelocity(new Vector(0, 2, 0)); - - } - -} \ No newline at end of file diff --git a/src/main/java/com/magmaguy/elitemobs/mobpowers/minorpowers/EventValidator.java b/src/main/java/com/magmaguy/elitemobs/mobpowers/minorpowers/EventValidator.java deleted file mode 100644 index 624cdb1b5..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobpowers/minorpowers/EventValidator.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.mobpowers.minorpowers; - -import com.magmaguy.elitemobs.EntityTracker; -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; -import com.magmaguy.elitemobs.mobpowers.ElitePower; -import com.magmaguy.elitemobs.utils.EntityFinder; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.event.entity.EntityDamageEvent; -import org.bukkit.event.entity.EntityTargetLivingEntityEvent; - -public class EventValidator { - - /* - This class checks if the event is valid - It does so by checking if it isn't cancelled, if it contains an elite mob and if that elite mob has the relevant - power for that event - As such, the event should be cancelled at a power level when this returns null - */ - public static EliteMobEntity getEventEliteMob(ElitePower mobPower, EntityDamageByEntityEvent event) { - - if (event.isCancelled()) return null; - - Player player = EntityFinder.findPlayer(event); - - if (player == null) return null; - - LivingEntity livingEntity = EntityFinder.getRealDamager(event); - - if (livingEntity == null) return null; - - EliteMobEntity eliteMobEntity = EntityTracker.getEliteMobEntity(livingEntity); - - if (eliteMobEntity == null) return null; - - if (!EntityTracker.hasPower(mobPower, eliteMobEntity)) return null; - - return eliteMobEntity; - - } - - public static EliteMobEntity getEventEliteMob(ElitePower mobPower, EntityTargetLivingEntityEvent event) { - - if (event.isCancelled()) return null; - - Player player = EntityFinder.findPlayer(event); - - if (player == null) return null; - - LivingEntity livingEntity = EntityFinder.getRealDamager(event); - - if (livingEntity == null) return null; - - EliteMobEntity eliteMobEntity = EntityTracker.getEliteMobEntity(livingEntity); - - if (eliteMobEntity == null) return null; - - if (!EntityTracker.hasPower(mobPower, eliteMobEntity)) return null; - - return eliteMobEntity; - - } - - public static EliteMobEntity getEventEliteMob(ElitePower mobPower, EntityDamageEvent event) { - - if (event.isCancelled()) return null; - - if (!(event.getEntity() instanceof LivingEntity)) return null; - - EliteMobEntity eliteMobEntity = EntityTracker.getEliteMobEntity(event.getEntity()); - - if (eliteMobEntity == null) return null; - - if (!EntityTracker.hasPower(mobPower, eliteMobEntity)) return null; - - return eliteMobEntity; - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobpowers/minorpowers/MinorPower.java b/src/main/java/com/magmaguy/elitemobs/mobpowers/minorpowers/MinorPower.java deleted file mode 100644 index b9eb44337..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobpowers/minorpowers/MinorPower.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.mobpowers.minorpowers; - -import com.magmaguy.elitemobs.mobpowers.ElitePower; - -/** - * Created by MagmaGuy on 05/11/2016. - */ -public abstract class MinorPower extends ElitePower { - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobpowers/miscellaneouspowers/BonusLoot.java b/src/main/java/com/magmaguy/elitemobs/mobpowers/miscellaneouspowers/BonusLoot.java deleted file mode 100644 index 9ddb13be0..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobpowers/miscellaneouspowers/BonusLoot.java +++ /dev/null @@ -1,46 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.mobpowers.miscellaneouspowers; - -import com.magmaguy.elitemobs.EntityTracker; -import com.magmaguy.elitemobs.items.LootTables; -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; -import com.magmaguy.elitemobs.mobpowers.minorpowers.MinorPower; -import org.bukkit.entity.Entity; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDeathEvent; - -/** - * Created by MagmaGuy on 28/04/2017. - */ -public class BonusLoot extends MinorPower implements Listener { - - @Override - public void applyPowers(Entity entity) { - } - - @EventHandler - public void onDeath(EntityDeathEvent event) { - - EliteMobEntity eliteMobEntity = EntityTracker.getEliteMobEntity(event.getEntity()); - if (eliteMobEntity == null) return; - if (!eliteMobEntity.hasPower(this)) return; - LootTables.generateLoot(eliteMobEntity); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobpowers/miscellaneouspowers/MovementSpeed.java b/src/main/java/com/magmaguy/elitemobs/mobpowers/miscellaneouspowers/MovementSpeed.java deleted file mode 100644 index d53f99157..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobpowers/miscellaneouspowers/MovementSpeed.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.mobpowers.miscellaneouspowers; - -import com.magmaguy.elitemobs.mobpowers.minorpowers.MinorPower; -import org.bukkit.entity.Entity; -import org.bukkit.entity.LivingEntity; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; - -/** - * Created by MagmaGuy on 05/11/2016. - */ -public class MovementSpeed extends MinorPower { - - @Override - public void applyPowers(Entity entity) { - ((LivingEntity) entity).addPotionEffect(new PotionEffect(PotionEffectType.SPEED, Integer.MAX_VALUE, 2)); - } - -} \ No newline at end of file diff --git a/src/main/java/com/magmaguy/elitemobs/mobpowers/miscellaneouspowers/Taunt.java b/src/main/java/com/magmaguy/elitemobs/mobpowers/miscellaneouspowers/Taunt.java deleted file mode 100644 index f30a4e35e..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobpowers/miscellaneouspowers/Taunt.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.mobpowers.miscellaneouspowers; - -import com.magmaguy.elitemobs.EntityTracker; -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; -import com.magmaguy.elitemobs.mobpowers.minorpowers.EventValidator; -import com.magmaguy.elitemobs.mobpowers.minorpowers.MinorPower; -import org.bukkit.entity.Entity; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.event.entity.EntityDamageEvent; -import org.bukkit.event.entity.EntityDeathEvent; -import org.bukkit.event.entity.EntityTargetLivingEntityEvent; -import org.bukkit.scheduler.BukkitRunnable; - -import java.util.List; -import java.util.concurrent.ThreadLocalRandom; - -import static com.magmaguy.elitemobs.ChatColorConverter.convert; - -/** - * Created by MagmaGuy on 06/05/2017. - */ -public class Taunt extends MinorPower implements Listener { - - private final static List TARGET_TAUNT_LIST = ConfigValues.translationConfig.getStringList("Taunts.Target"); - private final static List GENERIC_DAMAGED_LIST = ConfigValues.translationConfig.getStringList("Taunts.Damaged"); - private final static List DAMAGED_BY_BOW_LIST = ConfigValues.translationConfig.getStringList("Taunts.BowDamaged"); - private final static List HIT_LIST = ConfigValues.translationConfig.getStringList("Taunts.Hit"); - private final static List DEATH_LIST = ConfigValues.translationConfig.getStringList("Taunts.Death"); - - @Override - public void applyPowers(Entity entity) { - } - - @EventHandler - public void onTarget(EntityTargetLivingEntityEvent event) { - - if (EntityTracker.hasPower(this, event.getEntity())) - if (event.getTarget() instanceof Player) { - Entity targetter = event.getEntity(); - nametagProcessor(targetter, TARGET_TAUNT_LIST); - } - - } - - @EventHandler - public void onDamaged(EntityDamageEvent event) { - - if (!(event.getEntity() instanceof LivingEntity) || - ((LivingEntity) event.getEntity()).getHealth() - event.getFinalDamage() <= 0 || - !event.getEntity().isValid()) - return; - - EliteMobEntity eliteMobEntity = EntityTracker.getEliteMobEntity(event.getEntity()); - if (eliteMobEntity == null) return; - if (EntityTracker.hasPower(this, event.getEntity())) { - Entity entity = event.getEntity(); - - if (event.getCause().equals(EntityDamageEvent.DamageCause.PROJECTILE)) - nametagProcessor(entity, DAMAGED_BY_BOW_LIST); - else - nametagProcessor(entity, GENERIC_DAMAGED_LIST); - - } - - } - - @EventHandler - public void onHit(EntityDamageByEntityEvent event) { - - EliteMobEntity eliteMobEntity = EventValidator.getEventEliteMob(this, event); - if (eliteMobEntity == null) return; - - nametagProcessor(eliteMobEntity.getLivingEntity(), HIT_LIST); - - } - - @EventHandler - public void onDeath(EntityDeathEvent event) { - - if (EntityTracker.hasPower(this, event.getEntity())) - nametagProcessor(event.getEntity(), DEATH_LIST); - - } - - private void nametagProcessor(Entity entity, List list) { - - int randomizedKey = ThreadLocalRandom.current().nextInt(list.size()); - String tempName = list.get(randomizedKey); - - entity.setCustomName(convert(tempName)); - - new BukkitRunnable() { - - @Override - public void run() { - - if (!entity.isValid()) - return; - - entity.setCustomName(EntityTracker.getEliteMobEntity(entity).getName()); - - } - - - }.runTaskLater(MetadataHandler.PLUGIN, 4 * 20); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackArrow.java b/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackArrow.java deleted file mode 100644 index 5fa6d711d..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackArrow.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.mobpowers.offensivepowers; - -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; -import com.magmaguy.elitemobs.mobpowers.ProjectileLocationGenerator; -import com.magmaguy.elitemobs.mobpowers.minorpowers.EventValidator; -import com.magmaguy.elitemobs.mobpowers.minorpowers.MinorPower; -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.entity.*; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityTargetLivingEntityEvent; -import org.bukkit.projectiles.ProjectileSource; -import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.util.Vector; - -import java.util.HashSet; - -/** - * Created by MagmaGuy on 06/05/2017. - */ -public class AttackArrow extends MinorPower implements Listener { - - private static HashSet currentlyFiringEntities = new HashSet<>(); - - @Override - - public void applyPowers(Entity entity) { - } - - @EventHandler - public void targetEvent(EntityTargetLivingEntityEvent event) { - EliteMobEntity eliteMobEntity = EventValidator.getEventEliteMob(this, event); - if (eliteMobEntity == null) return; - if (currentlyFiringEntities.contains(eliteMobEntity)) return; - repeatingArrowTask(eliteMobEntity); - currentlyFiringEntities.add(eliteMobEntity); - } - - private void repeatingArrowTask(EliteMobEntity eliteMobEntity) { - - new BukkitRunnable() { - - @Override - public void run() { - - if (!eliteMobEntity.getLivingEntity().isValid() || ((Monster) eliteMobEntity.getLivingEntity()).getTarget() == null) { - currentlyFiringEntities.remove(eliteMobEntity); - cancel(); - return; - } - - for (Entity nearbyEntity : eliteMobEntity.getLivingEntity().getNearbyEntities(20, 20, 20)) - if (nearbyEntity instanceof Player) - if (((Player) nearbyEntity).getGameMode().equals(GameMode.ADVENTURE) || - ((Player) nearbyEntity).getGameMode().equals(GameMode.SURVIVAL)) - shootArrow(eliteMobEntity.getLivingEntity(), (Player) nearbyEntity); - - } - - }.runTaskTimer(MetadataHandler.PLUGIN, 0, 20 * 8); - - } - - public static Arrow shootArrow(Entity entity, Player player) { - - Location offsetLocation = ProjectileLocationGenerator.generateLocation((LivingEntity) entity, player); - Arrow repeatingArrow = (Arrow) entity.getWorld().spawnEntity(offsetLocation, EntityType.ARROW); - Vector targetterToTargetted = player.getEyeLocation().subtract(repeatingArrow.getLocation()).toVector() - .normalize().multiply(2); - - repeatingArrow.setVelocity(targetterToTargetted); - repeatingArrow.setShooter((ProjectileSource) entity); - - return repeatingArrow; - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackBlinding.java b/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackBlinding.java deleted file mode 100644 index 0f930a8b1..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackBlinding.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.mobpowers.offensivepowers; - -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; -import com.magmaguy.elitemobs.mobpowers.PowerCooldown; -import com.magmaguy.elitemobs.mobpowers.minorpowers.EventValidator; -import com.magmaguy.elitemobs.mobpowers.minorpowers.MinorPower; -import com.magmaguy.elitemobs.utils.EntityFinder; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; - -import java.util.HashSet; - -/** - * Created by MagmaGuy on 30/04/2017. - */ -public class AttackBlinding extends MinorPower implements Listener { - - private static HashSet cooldownList = new HashSet<>(); - - @Override - public void applyPowers(Entity entity) { - } - - @EventHandler - public void attackBlinding(EntityDamageByEntityEvent event) { - - EliteMobEntity eliteMobEntity = EventValidator.getEventEliteMob(this, event); - if (eliteMobEntity == null) return; - Player player = EntityFinder.findPlayer(event); - if (PowerCooldown.isInCooldown(eliteMobEntity, cooldownList)) return; - player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 20 * 5, 3)); - PowerCooldown.startCooldownTimer(eliteMobEntity, cooldownList, 10 * 20); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackConfusing.java b/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackConfusing.java deleted file mode 100644 index 498bd82a8..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackConfusing.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.mobpowers.offensivepowers; - -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; -import com.magmaguy.elitemobs.mobpowers.PowerCooldown; -import com.magmaguy.elitemobs.mobpowers.minorpowers.EventValidator; -import com.magmaguy.elitemobs.mobpowers.minorpowers.MinorPower; -import com.magmaguy.elitemobs.utils.EntityFinder; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; - -import java.util.HashSet; - -/** - * Created by MagmaGuy on 30/04/2017. - */ -public class AttackConfusing extends MinorPower implements Listener { - - private static HashSet cooldowns = new HashSet<>(); - - @Override - public void applyPowers(Entity entity) { - } - - @EventHandler - public void attackConfusing(EntityDamageByEntityEvent event) { - - EliteMobEntity eliteMobEntity = EventValidator.getEventEliteMob(this, event); - if (eliteMobEntity == null) return; - Player player = EntityFinder.findPlayer(event); - if (PowerCooldown.isInCooldown(eliteMobEntity, cooldowns)) return; - - player.addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, 20 * 10, 3)); - PowerCooldown.startCooldownTimer(eliteMobEntity, cooldowns, 10 * 20); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackFire.java b/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackFire.java deleted file mode 100644 index 7d0dd17a1..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackFire.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.mobpowers.offensivepowers; - -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; -import com.magmaguy.elitemobs.mobpowers.PowerCooldown; -import com.magmaguy.elitemobs.mobpowers.minorpowers.EventValidator; -import com.magmaguy.elitemobs.mobpowers.minorpowers.MinorPower; -import com.magmaguy.elitemobs.utils.EntityFinder; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageByEntityEvent; - -import java.util.HashSet; - -/** - * Created by MagmaGuy on 28/04/2017. - */ -public class AttackFire extends MinorPower implements Listener { - - private static HashSet cooldownList = new HashSet<>(); - - @Override - public void applyPowers(Entity entity) { - } - - @EventHandler - public void attackFire(EntityDamageByEntityEvent event) { - - EliteMobEntity eliteMobEntity = EventValidator.getEventEliteMob(this, event); - if (eliteMobEntity == null) return; - Player player = EntityFinder.findPlayer(event); - if (PowerCooldown.isInCooldown(eliteMobEntity, cooldownList)) return; - - player.setFireTicks(40); - PowerCooldown.startCooldownTimer(eliteMobEntity, cooldownList, 10 * 20); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackFireball.java b/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackFireball.java deleted file mode 100644 index ef1466ecf..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackFireball.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.mobpowers.offensivepowers; - -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; -import com.magmaguy.elitemobs.mobpowers.minorpowers.EventValidator; -import com.magmaguy.elitemobs.mobpowers.minorpowers.MinorPower; -import org.bukkit.GameMode; -import org.bukkit.entity.*; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityTargetLivingEntityEvent; -import org.bukkit.projectiles.ProjectileSource; -import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.util.Vector; - -import java.util.HashSet; - -/** - * Created by MagmaGuy on 06/05/2017. - */ -public class AttackFireball extends MinorPower implements Listener { - - private static HashSet currentlyFiringEntities = new HashSet<>(); - - @Override - public void applyPowers(Entity entity) { - } - - @EventHandler - public void targetEvent(EntityTargetLivingEntityEvent event) { - EliteMobEntity eliteMobEntity = EventValidator.getEventEliteMob(this, event); - if (eliteMobEntity == null) return; - if (currentlyFiringEntities.contains(eliteMobEntity)) return; - repeatingFireballTask((Monster) event.getEntity()); - currentlyFiringEntities.add(eliteMobEntity); - } - - private void repeatingFireballTask(Monster monster) { - - new BukkitRunnable() { - - @Override - public void run() { - - if (!monster.isValid() || monster.getTarget() == null) { - cancel(); - return; - } - - for (Entity nearbyEntity : monster.getNearbyEntities(20, 20, 20)) - if (nearbyEntity instanceof Player) - if (((Player) nearbyEntity).getGameMode().equals(GameMode.ADVENTURE) || - ((Player) nearbyEntity).getGameMode().equals(GameMode.SURVIVAL)) - shootFireball(monster, (Player) nearbyEntity); - - } - - }.runTaskTimer(MetadataHandler.PLUGIN, 0, 20 * 8); - - } - - private static void shootFireball(Entity entity, Player player) { - - Fireball repeatingFireball = (Fireball) entity.getWorld().spawnEntity(entity.getLocation().add(0, 3, 0), EntityType.FIREBALL); - - Vector targetterToTargetted = player.getLocation().toVector().subtract(repeatingFireball.getLocation().toVector()).normalize(); - - repeatingFireball.setVelocity(targetterToTargetted); - repeatingFireball.setYield(1F); - repeatingFireball.setIsIncendiary(true); - repeatingFireball.setShooter((ProjectileSource) entity); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackFreeze.java b/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackFreeze.java deleted file mode 100644 index 5a3d73952..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackFreeze.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.mobpowers.offensivepowers; - -import com.magmaguy.elitemobs.ChatColorConverter; -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.MobPowersConfig; -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; -import com.magmaguy.elitemobs.mobpowers.PowerCooldown; -import com.magmaguy.elitemobs.mobpowers.minorpowers.EventValidator; -import com.magmaguy.elitemobs.mobpowers.minorpowers.MinorPower; -import com.magmaguy.elitemobs.utils.EntityFinder; -import net.md_5.bungee.api.ChatMessageType; -import net.md_5.bungee.api.chat.TextComponent; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; -import org.bukkit.scheduler.BukkitRunnable; - -import java.util.HashSet; - -/** - * Created by MagmaGuy on 28/04/2017. - */ -public class AttackFreeze extends MinorPower implements Listener { - - private static HashSet cooldowns = new HashSet<>(); - - @Override - public void applyPowers(Entity entity) { - } - - @EventHandler - public void attackFreeze(EntityDamageByEntityEvent event) { - - EliteMobEntity eliteMobEntity = EventValidator.getEventEliteMob(this, event); - if (eliteMobEntity == null) return; - Player player = EntityFinder.findPlayer(event); - if (PowerCooldown.isInCooldown(eliteMobEntity, cooldowns)) return; - - /* - Slow player down - */ - player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 20 * 3, 10)); - player.spigot().sendMessage(ChatMessageType.ACTION_BAR, - TextComponent.fromLegacyText( - ChatColorConverter.convert( - ConfigValues.mobPowerConfig.getString( - MobPowersConfig.FROZEN_MESSAGE)))); - - PowerCooldown.startCooldownTimer(eliteMobEntity, cooldowns, 20 * 15); - - /* - Add block effect - */ - Block block = player.getLocation().getBlock(); - Material originalMaterial = block.getType(); - - if (!originalMaterial.equals(Material.AIR)) - return; - - block.setType(Material.PACKED_ICE); - - new BukkitRunnable() { - @Override - public void run() { - block.setType(originalMaterial); - } - }.runTaskLater(MetadataHandler.PLUGIN, 20 * 3); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackGravity.java b/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackGravity.java deleted file mode 100644 index 69316c6e5..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackGravity.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.mobpowers.offensivepowers; - -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; -import com.magmaguy.elitemobs.mobpowers.PowerCooldown; -import com.magmaguy.elitemobs.mobpowers.minorpowers.EventValidator; -import com.magmaguy.elitemobs.mobpowers.minorpowers.MinorPower; -import com.magmaguy.elitemobs.utils.EntityFinder; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; - -import java.util.HashSet; - -/** - * Created by MagmaGuy on 05/11/2016. - */ -public class AttackGravity extends MinorPower implements Listener { - - private static HashSet cooldowns = new HashSet<>(); - - @Override - public void applyPowers(Entity entity) { - } - - @EventHandler - public void attackGravity(EntityDamageByEntityEvent event) { - - EliteMobEntity eliteMobEntity = EventValidator.getEventEliteMob(this, event); - if (eliteMobEntity == null) return; - Player player = EntityFinder.findPlayer(event); - if (PowerCooldown.isInCooldown(eliteMobEntity, cooldowns)) return; - - player.addPotionEffect(new PotionEffect(PotionEffectType.LEVITATION, 2 * 20, 3)); - PowerCooldown.startCooldownTimer(eliteMobEntity, cooldowns, 10 * 20); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackPoison.java b/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackPoison.java deleted file mode 100644 index 7a65b799a..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackPoison.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.mobpowers.offensivepowers; - -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; -import com.magmaguy.elitemobs.mobpowers.PowerCooldown; -import com.magmaguy.elitemobs.mobpowers.minorpowers.EventValidator; -import com.magmaguy.elitemobs.mobpowers.minorpowers.MinorPower; -import com.magmaguy.elitemobs.utils.EntityFinder; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; - -import java.util.HashSet; - -/** - * Created by MagmaGuy on 12/12/2016. - */ -public class AttackPoison extends MinorPower implements Listener { - - private static HashSet cooldowns = new HashSet<>(); - - @Override - public void applyPowers(Entity entity) { - } - - @EventHandler - public void onHit(EntityDamageByEntityEvent event) { - - EliteMobEntity eliteMobEntity = EventValidator.getEventEliteMob(this, event); - if (eliteMobEntity == null) return; - Player player = EntityFinder.findPlayer(event); - if (PowerCooldown.isInCooldown(eliteMobEntity, cooldowns)) return; - - player.addPotionEffect(new PotionEffect(PotionEffectType.POISON, 50, 3)); - PowerCooldown.startCooldownTimer(eliteMobEntity, cooldowns, 10 * 20); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackPush.java b/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackPush.java deleted file mode 100644 index 9d55af287..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackPush.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.mobpowers.offensivepowers; - -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; -import com.magmaguy.elitemobs.mobpowers.PowerCooldown; -import com.magmaguy.elitemobs.mobpowers.minorpowers.EventValidator; -import com.magmaguy.elitemobs.mobpowers.minorpowers.MinorPower; -import com.magmaguy.elitemobs.utils.EntityFinder; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.util.Vector; - -import java.util.HashSet; - -/** - * Created by MagmaGuy on 05/11/2016. - */ -public class AttackPush extends MinorPower implements Listener { - - private static HashSet cooldownList = new HashSet<>(); - - @Override - public void applyPowers(Entity entity) { - } - - @EventHandler - public void attackPush(EntityDamageByEntityEvent event) { - - EliteMobEntity eliteMobEntity = EventValidator.getEventEliteMob(this, event); - if (eliteMobEntity == null) return; - Player player = EntityFinder.findPlayer(event); - if (PowerCooldown.isInCooldown(eliteMobEntity, cooldownList)) return; - - Vector pushbackDirection = player.getLocation().subtract(eliteMobEntity.getLivingEntity().getLocation()).toVector(); - Vector pushbackApplied = pushbackDirection.normalize().multiply(3); - - player.setVelocity(pushbackApplied); - - PowerCooldown.startCooldownTimer(eliteMobEntity, cooldownList, 10 * 20); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackWeakness.java b/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackWeakness.java deleted file mode 100644 index 8f6251a86..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackWeakness.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.mobpowers.offensivepowers; - -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; -import com.magmaguy.elitemobs.mobpowers.PowerCooldown; -import com.magmaguy.elitemobs.mobpowers.minorpowers.EventValidator; -import com.magmaguy.elitemobs.mobpowers.minorpowers.MinorPower; -import com.magmaguy.elitemobs.utils.EntityFinder; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; - -import java.util.HashSet; - -/** - * Created by MagmaGuy on 06/05/2017. - */ -public class AttackWeakness extends MinorPower implements Listener { - - private static HashSet cooldownList = new HashSet<>(); - - @Override - public void applyPowers(Entity entity) { - } - - @EventHandler - public void attackWeakness(EntityDamageByEntityEvent event) { - - EliteMobEntity eliteMobEntity = EventValidator.getEventEliteMob(this, event); - if (eliteMobEntity == null) return; - Player player = EntityFinder.findPlayer(event); - if (PowerCooldown.isInCooldown(eliteMobEntity, cooldownList)) return; - - player.addPotionEffect(new PotionEffect(PotionEffectType.WEAKNESS, 20 * 3, 0)); - - PowerCooldown.startCooldownTimer(eliteMobEntity, cooldownList, 10 * 20); - - } - - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackWeb.java b/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackWeb.java deleted file mode 100644 index da1218ca2..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackWeb.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.mobpowers.offensivepowers; - -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; -import com.magmaguy.elitemobs.mobpowers.PowerCooldown; -import com.magmaguy.elitemobs.mobpowers.minorpowers.EventValidator; -import com.magmaguy.elitemobs.mobpowers.minorpowers.MinorPower; -import com.magmaguy.elitemobs.utils.EntityFinder; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.scheduler.BukkitRunnable; - -import java.util.HashSet; - -/** - * Created by MagmaGuy on 28/04/2017. - */ -public class AttackWeb extends MinorPower implements Listener { - - private static HashSet cooldownList = new HashSet<>(); - - @Override - public void applyPowers(Entity entity) { - } - - @EventHandler - public void attackWeb(EntityDamageByEntityEvent event) { - - EliteMobEntity eliteMobEntity = EventValidator.getEventEliteMob(this, event); - if (eliteMobEntity == null) return; - Player player = EntityFinder.findPlayer(event); - if (PowerCooldown.isInCooldown(eliteMobEntity, cooldownList)) return; - - Block block = player.getLocation().getBlock(); - Material originalMaterial = block.getType(); - - if (!originalMaterial.equals(Material.AIR)) - return; - - block.setType(Material.WEB); - - new BukkitRunnable() { - @Override - public void run() { - block.setType(originalMaterial); - } - }.runTaskLater(MetadataHandler.PLUGIN, 20 * 3); - - PowerCooldown.startCooldownTimer(eliteMobEntity, cooldownList, 3 * 20); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackWither.java b/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackWither.java deleted file mode 100644 index b350be366..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobpowers/offensivepowers/AttackWither.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.mobpowers.offensivepowers; - -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; -import com.magmaguy.elitemobs.mobpowers.PowerCooldown; -import com.magmaguy.elitemobs.mobpowers.minorpowers.EventValidator; -import com.magmaguy.elitemobs.mobpowers.minorpowers.MinorPower; -import com.magmaguy.elitemobs.utils.EntityFinder; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; - -import java.util.HashSet; - -/** - * Created by MagmaGuy on 12/12/2016. - */ -public class AttackWither extends MinorPower implements Listener { - - private static HashSet cooldownList = new HashSet<>(); - - @Override - public void applyPowers(Entity entity) { - } - - @EventHandler - public void onHit(EntityDamageByEntityEvent event) { - - EliteMobEntity eliteMobEntity = EventValidator.getEventEliteMob(this, event); - if (eliteMobEntity == null) return; - Player player = EntityFinder.findPlayer(event); - if (PowerCooldown.isInCooldown(eliteMobEntity, cooldownList)) return; - player.addPotionEffect(new PotionEffect(PotionEffectType.WITHER, 50, 1)); - PowerCooldown.startCooldownTimer(eliteMobEntity, cooldownList, 10 * 20); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobs/passive/ChickenHandler.java b/src/main/java/com/magmaguy/elitemobs/mobs/passive/ChickenHandler.java index 57177bbac..f61e0bce3 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobs/passive/ChickenHandler.java +++ b/src/main/java/com/magmaguy/elitemobs/mobs/passive/ChickenHandler.java @@ -15,64 +15,51 @@ package com.magmaguy.elitemobs.mobs.passive; -import com.magmaguy.elitemobs.EntityTracker; import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.SuperMobDamageEvent; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; import com.magmaguy.elitemobs.items.ItemDropVelocity; import org.bukkit.Material; import org.bukkit.entity.*; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.event.entity.EntityDeathEvent; -import org.bukkit.event.entity.EntitySpawnEvent; -import org.bukkit.event.entity.ItemMergeEvent; import org.bukkit.event.inventory.InventoryPickupItemEvent; -import org.bukkit.event.world.ChunkUnloadEvent; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.scheduler.BukkitRunnable; import java.util.*; +import static org.bukkit.Material.CHICKEN; import static org.bukkit.Material.FEATHER; -import static org.bukkit.Material.RAW_CHICKEN; /** * Created by MagmaGuy on 19/12/2016. */ public class ChickenHandler implements Listener { - public static List activeChickenList = new ArrayList<>(); - /* Augmented egg drops There's no egg dropping event and listening for new eggs can be extremely inaccurate due to high chicken density Use events to add and remove loaded chicken and use the scanner to update the list of active chicken */ - @EventHandler(priority = EventPriority.HIGHEST) - public void superDrops(EntityDamageByEntityEvent event) { - - if (event.isCancelled()) { - - return; - - } + private final List lore = new ArrayList<>(Arrays.asList("SuperChicken Egg")); - if (event.getFinalDamage() < 1) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void superDrops(SuperMobDamageEvent event) { + if (event.getEntityDamageEvent().getFinalDamage() < 1) return; - } - - if (event.getEntity() instanceof Chicken && EntityTracker.isSuperMob(event.getEntity())) { + if (event.getLivingEntity().getType().equals(EntityType.CHICKEN)) { Random random = new Random(); - Chicken chicken = (Chicken) event.getEntity(); + Chicken chicken = (Chicken) event.getLivingEntity(); - double damage = event.getFinalDamage(); + double damage = event.getEntityDamageEvent().getFinalDamage(); //health is hardcoded here, maybe change it at some point? double dropChance = damage / 4; double dropRandomizer = random.nextDouble(); @@ -80,7 +67,7 @@ public void superDrops(EntityDamageByEntityEvent event) { int dropMinAmount = (int) dropChance; ItemStack featherStack = new ItemStack(FEATHER, (random.nextInt(2) + 1)); - ItemStack poultryStack = new ItemStack(RAW_CHICKEN, 1); + ItemStack poultryStack = new ItemStack(CHICKEN, 1); for (int i = 0; i < dropMinAmount; i++) { @@ -106,75 +93,21 @@ public void superDrops(EntityDamageByEntityEvent event) { } - @EventHandler - public void superChickenAppearEvent(EntitySpawnEvent event) { - - if (event.getEntityType().equals(EntityType.CHICKEN)) { - - Chicken chicken = (Chicken) event.getEntity(); - - if (EntityTracker.isSuperMob(chicken)) { - - if (!activeChickenList.contains(chicken)) { - - activeChickenList.add(chicken); - - } - - } - - } - - } - - @EventHandler - public void superChickenDeathEvent(EntityDeathEvent event) { - - if (event.getEntityType().equals(EntityType.CHICKEN)) { - - Chicken chicken = (Chicken) event.getEntity(); - - activeChickenList.remove(chicken); - - } - - } - - @EventHandler - public void superChickenChunkUnloadEvent(ChunkUnloadEvent event) { - - Entity[] entityList = event.getChunk().getEntities(); - - for (Entity entity : entityList) { - - if (entity instanceof Chicken && EntityTracker.isSuperMob(entity)) { - - activeChickenList.remove(entity); - - } - - } - - } - - private List lore = new ArrayList<>(Arrays.asList("SuperChicken Egg")); - //Egg drop chance is based on the underlying timer public void dropEggs() { - if (activeChickenList.isEmpty()) return; - ItemStack eggStack = new ItemStack(Material.EGG, 1); ItemMeta eggMeta = eggStack.getItemMeta(); eggMeta.setLore(lore); eggStack.setItemMeta(eggMeta); - Iterator superChickenIterator = activeChickenList.iterator(); + Iterator superChickenIterator = EntityTracker.getSuperMobs().iterator(); while (superChickenIterator.hasNext()) { - Chicken chicken = superChickenIterator.next(); + LivingEntity chicken = superChickenIterator.next(); + if (!(chicken instanceof Chicken)) continue; if (chicken == null || !chicken.isValid()) { @@ -217,29 +150,4 @@ public void onHopperSuperEggPickup(InventoryPickupItemEvent event) { } - @EventHandler - public void onSuperEggMerge(ItemMergeEvent event) { - - if (event.getEntity().getItemStack().hasItemMeta() && event.getEntity().getItemStack().getItemMeta().hasLore() && - event.getEntity().getItemStack().getItemMeta().getLore().equals(lore)) { - - new BukkitRunnable() { - - @Override - public void run() { - - if (event.getTarget().isValid()) { - - event.getTarget().remove(); - - } - - } - - }.runTaskLater(MetadataHandler.PLUGIN, 20 * 60); - - } - - } - } diff --git a/src/main/java/com/magmaguy/elitemobs/mobs/passive/CowHandler.java b/src/main/java/com/magmaguy/elitemobs/mobs/passive/CowHandler.java index a618b4484..085ababc8 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobs/passive/CowHandler.java +++ b/src/main/java/com/magmaguy/elitemobs/mobs/passive/CowHandler.java @@ -1,69 +1,45 @@ -/* - * 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 . - */ - package com.magmaguy.elitemobs.mobs.passive; -import com.magmaguy.elitemobs.EntityTracker; +import com.magmaguy.elitemobs.api.SuperMobDamageEvent; import com.magmaguy.elitemobs.items.ItemDropVelocity; import org.bukkit.entity.Cow; +import org.bukkit.entity.EntityType; import org.bukkit.entity.ExperienceOrb; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.inventory.ItemStack; import java.util.Random; +import static org.bukkit.Material.BEEF; import static org.bukkit.Material.LEATHER; -import static org.bukkit.Material.RAW_BEEF; /** * Created by MagmaGuy on 19/12/2016. */ public class CowHandler implements Listener { - @EventHandler(priority = EventPriority.HIGHEST) - public void superDrops(EntityDamageByEntityEvent event) { - - if (event.isCancelled()) { - - return; - - } - - if (event.getFinalDamage() < 1) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void superDrops(SuperMobDamageEvent event) { + if (event.getEntityDamageEvent().getFinalDamage() < 1) return; - } - - if (event.getEntity() instanceof Cow && EntityTracker.isSuperMob(event.getEntity())) { + if (event.getLivingEntity().getType().equals(EntityType.COW)) { Random random = new Random(); - Cow cow = (Cow) event.getEntity(); + Cow cow = (Cow) event.getLivingEntity(); - double damage = event.getFinalDamage(); + double damage = event.getEntityDamageEvent().getFinalDamage(); //health is hardcoded here, maybe change it at some point? double dropChance = damage / 10; double dropRandomizer = random.nextDouble(); //this rounds down int dropMinAmount = (int) dropChance; - ItemStack beefStack = new ItemStack(RAW_BEEF, (random.nextInt(3) + 1)); + ItemStack beefStack = new ItemStack(BEEF, (random.nextInt(3) + 1)); //leather can drop 0, meaning that it could create visual artifacts. Have to filter that out. ItemStack leatherStack = new ItemStack(LEATHER, (random.nextInt(2))); diff --git a/src/main/java/com/magmaguy/elitemobs/runnables/EggRunnable.java b/src/main/java/com/magmaguy/elitemobs/mobs/passive/EggRunnable.java similarity index 75% rename from src/main/java/com/magmaguy/elitemobs/runnables/EggRunnable.java rename to src/main/java/com/magmaguy/elitemobs/mobs/passive/EggRunnable.java index 333f571e5..2840dd5b7 100644 --- a/src/main/java/com/magmaguy/elitemobs/runnables/EggRunnable.java +++ b/src/main/java/com/magmaguy/elitemobs/mobs/passive/EggRunnable.java @@ -1,6 +1,5 @@ -package com.magmaguy.elitemobs.runnables; +package com.magmaguy.elitemobs.mobs.passive; -import com.magmaguy.elitemobs.mobs.passive.ChickenHandler; import org.bukkit.scheduler.BukkitRunnable; public class EggRunnable extends BukkitRunnable { diff --git a/src/main/java/com/magmaguy/elitemobs/mobs/passive/MushroomCowHandler.java b/src/main/java/com/magmaguy/elitemobs/mobs/passive/MushroomCowHandler.java index 0e34c8d15..1090528b0 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobs/passive/MushroomCowHandler.java +++ b/src/main/java/com/magmaguy/elitemobs/mobs/passive/MushroomCowHandler.java @@ -15,14 +15,14 @@ package com.magmaguy.elitemobs.mobs.passive; -import com.magmaguy.elitemobs.EntityTracker; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; import com.magmaguy.elitemobs.items.ItemDropVelocity; import org.bukkit.entity.ExperienceOrb; import org.bukkit.entity.MushroomCow; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.event.player.PlayerShearEntityEvent; import org.bukkit.inventory.ItemStack; @@ -35,15 +35,12 @@ */ public class MushroomCowHandler implements Listener { - @EventHandler(priority = EventPriority.HIGHEST) - public void superDrops(EntityDamageByEntityEvent event) { - - if (event.getFinalDamage() < 1) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void superDrops(EntityDamageEvent event) { + if (event.getFinalDamage() < 1) return; - } - if (event.getEntity() instanceof MushroomCow && EntityTracker.isSuperMob(event.getEntity())) { Random random = new Random(); @@ -57,7 +54,7 @@ public void superDrops(EntityDamageByEntityEvent event) { //this rounds down int dropMinAmount = (int) dropChance; - ItemStack beefStack = new ItemStack(RAW_BEEF, (random.nextInt(3) + 1)); + ItemStack beefStack = new ItemStack(BEEF, (random.nextInt(3) + 1)); //leather can drop 0, meaning that it could create visual artifacts. Have to filter that out. ItemStack leatherStack = new ItemStack(LEATHER, (random.nextInt(2))); diff --git a/src/main/java/com/magmaguy/elitemobs/mobs/passive/PassiveEliteMobDeathHandler.java b/src/main/java/com/magmaguy/elitemobs/mobs/passive/PassiveEliteMobDeathHandler.java index be031b33f..978c21220 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobs/passive/PassiveEliteMobDeathHandler.java +++ b/src/main/java/com/magmaguy/elitemobs/mobs/passive/PassiveEliteMobDeathHandler.java @@ -15,12 +15,27 @@ package com.magmaguy.elitemobs.mobs.passive; -import com.magmaguy.elitemobs.EntityTracker; +import com.magmaguy.elitemobs.config.DefaultConfig; +import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.SuperMobConstructor; +import com.magmaguy.elitemobs.mobconstructor.mobdata.passivemobs.SuperMobProperties; +import org.bukkit.World; +import org.bukkit.attribute.Attribute; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.EntityDeathEvent; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.Objects; +import java.util.concurrent.ThreadLocalRandom; + +import static com.magmaguy.elitemobs.EliteMobs.validWorldList; + /** * Created by MagmaGuy on 03/05/2017. */ @@ -28,14 +43,66 @@ public class PassiveEliteMobDeathHandler implements Listener { @EventHandler(priority = EventPriority.LOWEST) public void onDeath(EntityDeathEvent event) { - if (EntityTracker.isSuperMob(event.getEntity())) { - event.getEntity().getLocation().getWorld().spawnEntity(event.getEntity().getLocation(), event.getEntityType()); event.getEntity().getLocation().getWorld().spawnEntity(event.getEntity().getLocation(), event.getEntityType()); + } + } + public static class SuperMobScanner { + private static final int passiveRange = MobCombatSettingsConfig.getSuperMobsStackRange(); + + public static void scanSuperMobs() { + for (World world : validWorldList) { + if (world.getLivingEntities().isEmpty()) continue; + Iterator iterator = world.getLivingEntities().iterator(); + while (iterator.hasNext()) { + LivingEntity livingEntity = iterator.next(); + if (!SuperMobProperties.isValidSuperMobType(livingEntity)) continue; + /* + Re-register lost passive mob + */ + checkLostSuperMob(livingEntity); + /* + Check passive mobs to register new super mobs + */ + newSuperMobScan(livingEntity); + } + } } - } + private static void checkLostSuperMob(LivingEntity livingEntity) { + if (Objects.requireNonNull(livingEntity.getAttribute(Attribute.GENERIC_MAX_HEALTH)).getValue() != + SuperMobProperties.getSuperMobMaxHealth(livingEntity)) + return; + if (!EntityTracker.isSuperMob(livingEntity)) + EntityTracker.registerSuperMob(livingEntity); + } + + public static void newSuperMobScan(LivingEntity livingEntity) { + if (livingEntity.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue() == + SuperMobProperties.getSuperMobMaxHealth(livingEntity)) + return; + if (ThreadLocalRandom.current().nextDouble() < 1 / (DefaultConfig.getSuperMobStackAmount() + 0D)) + return; + ArrayList livingEntities = new ArrayList<>(); + for (Entity entity : livingEntity.getNearbyEntities(passiveRange, passiveRange, passiveRange)) { + if (!entity.getType().equals(livingEntity.getType())) continue; + if (EntityTracker.isSuperMob(entity)) continue; + livingEntities.add((LivingEntity) entity); + if (livingEntities.size() >= DefaultConfig.getSuperMobStackAmount()) + break; + } + + if (livingEntities.size() < DefaultConfig.getSuperMobStackAmount()) + return; + + SuperMobConstructor.constructSuperMob(livingEntity); + for (Entity entity : livingEntities) { + entity.remove(); + } + } + + } } diff --git a/src/main/java/com/magmaguy/elitemobs/mobs/passive/PigHandler.java b/src/main/java/com/magmaguy/elitemobs/mobs/passive/PigHandler.java index 8a6bab31e..799099ac4 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobs/passive/PigHandler.java +++ b/src/main/java/com/magmaguy/elitemobs/mobs/passive/PigHandler.java @@ -1,86 +1,60 @@ -/* - * 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 . - */ - package com.magmaguy.elitemobs.mobs.passive; -import com.magmaguy.elitemobs.EntityTracker; +import com.magmaguy.elitemobs.api.SuperMobDamageEvent; import com.magmaguy.elitemobs.items.ItemDropVelocity; +import org.bukkit.entity.EntityType; import org.bukkit.entity.ExperienceOrb; import org.bukkit.entity.Pig; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageByEntityEvent; import org.bukkit.inventory.ItemStack; import java.util.Random; -import static org.bukkit.Material.PORK; +import static org.bukkit.Material.PORKCHOP; /** * Created by MagmaGuy on 19/12/2016. */ public class PigHandler implements Listener { - @EventHandler(priority = EventPriority.HIGHEST) - public void superDrops(EntityDamageByEntityEvent event) { - - if (event.isCancelled()) { - - return; - - } - - if (event.getFinalDamage() < 1) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void superDrops(SuperMobDamageEvent event) { + if (event.getEntityDamageEvent().getFinalDamage() < 1) return; - } - - if (event.getEntity() instanceof Pig && EntityTracker.isSuperMob(event.getEntity())) { - - Random random = new Random(); + if (!event.getLivingEntity().getType().equals(EntityType.PIG)) return; - Pig pig = (Pig) event.getEntity(); + Random random = new Random(); - double damage = event.getFinalDamage(); - //health is hardcoded here, maybe change it at some point? - double dropChance = damage / 10; - double dropRandomizer = random.nextDouble(); - //this rounds down - int dropMinAmount = (int) dropChance; + Pig pig = (Pig) event.getLivingEntity(); - ItemStack porkchopStack = new ItemStack(PORK, random.nextInt(3) + 1); + double damage = event.getEntityDamageEvent().getFinalDamage(); + //health is hardcoded here, maybe change it at some point? + double dropChance = damage / 10; + double dropRandomizer = random.nextDouble(); + //this rounds down + int dropMinAmount = (int) dropChance; - for (int i = 0; i < dropMinAmount; i++) { + ItemStack porkchopStack = new ItemStack(PORKCHOP, random.nextInt(3) + 1); - pig.getWorld().dropItem(pig.getLocation(), porkchopStack).setVelocity(ItemDropVelocity.ItemDropVelocity()); + for (int i = 0; i < dropMinAmount; i++) { - ExperienceOrb xpDrop = pig.getWorld().spawn(pig.getLocation(), ExperienceOrb.class); - xpDrop.setExperience(random.nextInt(3) + 1); + pig.getWorld().dropItem(pig.getLocation(), porkchopStack).setVelocity(ItemDropVelocity.ItemDropVelocity()); - } + ExperienceOrb xpDrop = pig.getWorld().spawn(pig.getLocation(), ExperienceOrb.class); + xpDrop.setExperience(random.nextInt(3) + 1); - if (dropChance > dropRandomizer) { + } - pig.getWorld().dropItem(pig.getLocation(), porkchopStack).setVelocity(ItemDropVelocity.ItemDropVelocity()); + if (dropChance > dropRandomizer) { - ExperienceOrb xpDrop = pig.getWorld().spawn(pig.getLocation(), ExperienceOrb.class); - xpDrop.setExperience(random.nextInt(3) + 1); + pig.getWorld().dropItem(pig.getLocation(), porkchopStack).setVelocity(ItemDropVelocity.ItemDropVelocity()); - } + ExperienceOrb xpDrop = pig.getWorld().spawn(pig.getLocation(), ExperienceOrb.class); + xpDrop.setExperience(random.nextInt(3) + 1); } diff --git a/src/main/java/com/magmaguy/elitemobs/mobs/passive/SheepHandler.java b/src/main/java/com/magmaguy/elitemobs/mobs/passive/SheepHandler.java index eefc2a7fa..ce3b37cdf 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobs/passive/SheepHandler.java +++ b/src/main/java/com/magmaguy/elitemobs/mobs/passive/SheepHandler.java @@ -1,28 +1,14 @@ -/* - * 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 . - */ - package com.magmaguy.elitemobs.mobs.passive; -import com.magmaguy.elitemobs.EntityTracker; +import com.magmaguy.elitemobs.api.SuperMobDamageEvent; +import com.magmaguy.elitemobs.api.SuperMobDeathEvent; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; import com.magmaguy.elitemobs.items.ItemDropVelocity; +import org.bukkit.entity.EntityType; import org.bukkit.entity.Sheep; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageByEntityEvent; -import org.bukkit.event.entity.EntityDeathEvent; import org.bukkit.event.player.PlayerShearEntityEvent; import org.bukkit.inventory.ItemStack; @@ -36,196 +22,171 @@ */ public class SheepHandler implements Listener { - @EventHandler(priority = EventPriority.HIGHEST) - public void superDrops(EntityDamageByEntityEvent event) { - - if (event.isCancelled()) { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void superDrops(SuperMobDamageEvent event) { + if (event.getEntityDamageEvent().getFinalDamage() < 1) return; - } + if (!event.getLivingEntity().getType().equals(EntityType.SHEEP)) return; - if (event.getFinalDamage() < 1) { + Random random = new Random(); - return; + Sheep sheep = (Sheep) event.getLivingEntity(); - } + double damage = event.getEntityDamageEvent().getFinalDamage(); + //health is hardcoded here, maybe change it at some point? + double dropChance = damage / 8; + double dropRandomizer = random.nextDouble(); + //this rounds down + int dropMinAmount = (int) dropChance; - if (EntityTracker.isSuperMob(event.getEntity()) && event.getEntity() instanceof Sheep) { - - Random random = new Random(); - - Sheep sheep = (Sheep) event.getEntity(); - - double damage = event.getFinalDamage(); - //health is hardcoded here, maybe change it at some point? - double dropChance = damage / 8; - double dropRandomizer = random.nextDouble(); - //this rounds down - int dropMinAmount = (int) dropChance; - - ItemStack muttonStack = new ItemStack(MUTTON, random.nextInt(2) + 1); - ItemStack woolStack = new ItemStack(WOOL, 1); - - //for different wool colors - switch (sheep.getColor()) { - case WHITE: - woolStack = new ItemStack(WOOL, 1); - break; - case ORANGE: - woolStack = new ItemStack(WOOL, 1, (short) 1); - break; - case MAGENTA: - woolStack = new ItemStack(WOOL, 1, (short) 2); - break; - case LIGHT_BLUE: - woolStack = new ItemStack(WOOL, 1, (short) 3); - break; - case YELLOW: - woolStack = new ItemStack(WOOL, 1, (short) 4); - break; - case LIME: - woolStack = new ItemStack(WOOL, 1, (short) 5); - break; - case PINK: - woolStack = new ItemStack(WOOL, 1, (short) 6); - break; - case GRAY: - woolStack = new ItemStack(WOOL, 1, (short) 7); - break; - case SILVER: - woolStack = new ItemStack(WOOL, 1, (short) 8); - break; - case CYAN: - woolStack = new ItemStack(WOOL, 1, (short) 9); - break; - case PURPLE: - woolStack = new ItemStack(WOOL, 1, (short) 10); - break; - case BLUE: - woolStack = new ItemStack(WOOL, 1, (short) 11); - break; - case BROWN: - woolStack = new ItemStack(WOOL, 1, (short) 12); - break; - case GREEN: - woolStack = new ItemStack(WOOL, 1, (short) 13); - break; - case RED: - woolStack = new ItemStack(WOOL, 1, (short) 14); - break; - case BLACK: - woolStack = new ItemStack(WOOL, 1, (short) 15); - break; - default: - getLogger().info("Something went wrong with the sheep colors, one is missing. Contact the dev."); - break; - } - - for (int i = 0; i < dropMinAmount; i++) { - - sheep.getWorld().dropItem(sheep.getLocation(), muttonStack).setVelocity(ItemDropVelocity.ItemDropVelocity()); - sheep.getWorld().dropItem(sheep.getLocation(), woolStack).setVelocity(ItemDropVelocity.ItemDropVelocity()); - - } - - if (dropChance > dropRandomizer) { - - sheep.getWorld().dropItem(sheep.getLocation(), muttonStack).setVelocity(ItemDropVelocity.ItemDropVelocity()); - sheep.getWorld().dropItem(sheep.getLocation(), woolStack).setVelocity(ItemDropVelocity.ItemDropVelocity()); - - } + ItemStack muttonStack = new ItemStack(MUTTON, random.nextInt(2) + 1); + ItemStack woolStack = new ItemStack(WHITE_WOOL, 1); + //for different wool colors + switch (sheep.getColor()) { + case WHITE: + woolStack = new ItemStack(WHITE_WOOL, 1); + break; + case ORANGE: + woolStack = new ItemStack(ORANGE_WOOL, 1); + break; + case MAGENTA: + woolStack = new ItemStack(MAGENTA_WOOL, 1); + break; + case LIGHT_BLUE: + woolStack = new ItemStack(LIGHT_BLUE_WOOL, 1); + break; + case YELLOW: + woolStack = new ItemStack(YELLOW_WOOL, 1); + break; + case LIME: + woolStack = new ItemStack(LIME_WOOL, 1); + break; + case PINK: + woolStack = new ItemStack(PINK_WOOL, 1); + break; + case GRAY: + woolStack = new ItemStack(GRAY_WOOL, 1); + break; + case LIGHT_GRAY: + woolStack = new ItemStack(LIGHT_GRAY_WOOL, 1); + break; + case CYAN: + woolStack = new ItemStack(CYAN_WOOL, 1); + break; + case PURPLE: + woolStack = new ItemStack(PURPLE_WOOL, 1); + break; + case BLUE: + woolStack = new ItemStack(BLUE_WOOL, 1); + break; + case BROWN: + woolStack = new ItemStack(BROWN_WOOL, 1); + break; + case GREEN: + woolStack = new ItemStack(GREEN_WOOL, 1); + break; + case RED: + woolStack = new ItemStack(RED_WOOL, 1); + break; + case BLACK: + woolStack = new ItemStack(BLACK_WOOL, 1); + break; + default: + getLogger().info("Something went wrong with the sheep colors, one is missing. Contact the dev."); + break; } - } + for (int i = 0; i < dropMinAmount; i++) { - @EventHandler - public void onDeath(EntityDeathEvent event) { + sheep.getWorld().dropItem(sheep.getLocation(), muttonStack).setVelocity(ItemDropVelocity.ItemDropVelocity()); + sheep.getWorld().dropItem(sheep.getLocation(), woolStack).setVelocity(ItemDropVelocity.ItemDropVelocity()); - if (event.getEntity() instanceof Sheep && EntityTracker.isSuperMob(event.getEntity())) { + } - Sheep sheep = (Sheep) event.getEntity(); + if (dropChance > dropRandomizer) { - ItemStack sheepMonsterEgg = new ItemStack(MONSTER_EGG, 2, (short) 91); - sheep.getWorld().dropItem(sheep.getLocation(), sheepMonsterEgg); + sheep.getWorld().dropItem(sheep.getLocation(), muttonStack).setVelocity(ItemDropVelocity.ItemDropVelocity()); + sheep.getWorld().dropItem(sheep.getLocation(), woolStack).setVelocity(ItemDropVelocity.ItemDropVelocity()); } } - @EventHandler - public void onShear(PlayerShearEntityEvent event) { - - if (event.getEntity() instanceof Sheep && EntityTracker.isSuperMob(event.getEntity())) { - - Sheep sheep = (Sheep) event.getEntity(); - - for (int i = 0; i < 50; i++) { - - sheep.getWorld().dropItem(sheep.getLocation(), woolStackRandomizer(sheep)).setVelocity(ItemDropVelocity.ItemDropVelocity()); - - } + @EventHandler(ignoreCancelled = true) + public void onDeath(SuperMobDeathEvent event) { + if (!event.getLivingEntity().getType().equals(EntityType.SHEEP)) return; + Sheep sheep = (Sheep) event.getLivingEntity(); + ItemStack sheepMonsterEgg = new ItemStack(SHEEP_SPAWN_EGG, 2); + sheep.getWorld().dropItem(sheep.getLocation(), sheepMonsterEgg); + } - } + @EventHandler(ignoreCancelled = true) + public void onShear(PlayerShearEntityEvent event) { + if (!event.getEntity().getType().equals(EntityType.SHEEP)) return; + if (!EntityTracker.isSuperMob(event.getEntity())) return; + Sheep sheep = (Sheep) event.getEntity(); + for (int i = 0; i < 50; i++) + sheep.getWorld().dropItem(sheep.getLocation(), woolStackRandomizer(sheep)).setVelocity(ItemDropVelocity.ItemDropVelocity()); } public ItemStack woolStackRandomizer(Sheep sheep) { - Random random = new Random(); - ItemStack woolStack = new ItemStack(WOOL, ((random.nextInt(3) + 1) * 50)); + ItemStack woolStack = new ItemStack(WHITE_WOOL, ((random.nextInt(3) + 1) * 50)); switch (sheep.getColor()) { case WHITE: - woolStack = new ItemStack(WOOL, (random.nextInt(3) + 1)); + woolStack = new ItemStack(WHITE_WOOL, (random.nextInt(3) + 1)); break; case ORANGE: - woolStack = new ItemStack(WOOL, ((random.nextInt(3) + 1)), (short) 1); + woolStack = new ItemStack(ORANGE_WOOL, ((random.nextInt(3) + 1))); break; case MAGENTA: - woolStack = new ItemStack(WOOL, ((random.nextInt(3) + 1)), (short) 2); + woolStack = new ItemStack(MAGENTA_WOOL, ((random.nextInt(3) + 1))); break; case LIGHT_BLUE: - woolStack = new ItemStack(WOOL, ((random.nextInt(3) + 1)), (short) 3); + woolStack = new ItemStack(LIGHT_BLUE_WOOL, ((random.nextInt(3) + 1))); break; case YELLOW: - woolStack = new ItemStack(WOOL, ((random.nextInt(3) + 1)), (short) 4); + woolStack = new ItemStack(YELLOW_WOOL, ((random.nextInt(3) + 1))); break; case LIME: - woolStack = new ItemStack(WOOL, ((random.nextInt(3) + 1)), (short) 5); + woolStack = new ItemStack(LIME_WOOL, ((random.nextInt(3) + 1))); break; case PINK: - woolStack = new ItemStack(WOOL, ((random.nextInt(3) + 1)), (short) 6); + woolStack = new ItemStack(PINK_WOOL, ((random.nextInt(3) + 1))); break; case GRAY: - woolStack = new ItemStack(WOOL, ((random.nextInt(3) + 1)), (short) 7); + woolStack = new ItemStack(GRAY_WOOL, ((random.nextInt(3) + 1))); break; - case SILVER: - woolStack = new ItemStack(WOOL, ((random.nextInt(3) + 1)), (short) 8); + case LIGHT_GRAY: + woolStack = new ItemStack(LIGHT_GRAY_WOOL, ((random.nextInt(3) + 1))); break; case CYAN: - woolStack = new ItemStack(WOOL, ((random.nextInt(3) + 1)), (short) 9); + woolStack = new ItemStack(CYAN_WOOL, ((random.nextInt(3) + 1))); break; case PURPLE: - woolStack = new ItemStack(WOOL, ((random.nextInt(3) + 1)), (short) 10); + woolStack = new ItemStack(PURPLE_WOOL, ((random.nextInt(3) + 1))); break; case BLUE: - woolStack = new ItemStack(WOOL, ((random.nextInt(3) + 1)), (short) 11); + woolStack = new ItemStack(BLUE_WOOL, ((random.nextInt(3) + 1))); break; case BROWN: - woolStack = new ItemStack(WOOL, ((random.nextInt(3) + 1)), (short) 12); + woolStack = new ItemStack(BROWN_WOOL, ((random.nextInt(3) + 1))); break; case GREEN: - woolStack = new ItemStack(WOOL, ((random.nextInt(3) + 1)), (short) 13); + woolStack = new ItemStack(GREEN_WOOL, ((random.nextInt(3) + 1))); break; case RED: - woolStack = new ItemStack(WOOL, ((random.nextInt(3) + 1)), (short) 14); + woolStack = new ItemStack(RED_WOOL, ((random.nextInt(3) + 1))); break; case BLACK: - woolStack = new ItemStack(WOOL, ((random.nextInt(3) + 1)), (short) 15); + woolStack = new ItemStack(BLACK_WOOL, ((random.nextInt(3) + 1))); break; default: getLogger().info("Something went wrong with the sheep colors, one is missing. Contact the dev."); diff --git a/src/main/java/com/magmaguy/elitemobs/mobscanner/EliteMobScanner.java b/src/main/java/com/magmaguy/elitemobs/mobscanner/EliteMobScanner.java deleted file mode 100644 index e4ab9e76f..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobscanner/EliteMobScanner.java +++ /dev/null @@ -1,115 +0,0 @@ -package com.magmaguy.elitemobs.mobscanner; - -import com.magmaguy.elitemobs.EntityTracker; -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; -import com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs.EliteMobProperties; -import org.bukkit.World; -import org.bukkit.attribute.Attribute; -import org.bukkit.entity.Entity; -import org.bukkit.entity.LivingEntity; -import org.bukkit.scheduler.BukkitRunnable; - -import java.util.Iterator; - -import static com.magmaguy.elitemobs.EliteMobs.validWorldList; - -public class EliteMobScanner { - - private static int aggressiveRange = ConfigValues.mobCombatSettingsConfig.getInt(MobCombatSettingsConfig.AGGRESSIVE_STACK_RANGE); - - public static void scanElites() { - - for (World world : validWorldList) { - - if (world.getLivingEntities().isEmpty()) continue; - - Iterator iterator = world.getLivingEntities().iterator(); - - new BukkitRunnable() { - - @Override - public void run() { - - while (iterator.hasNext()) { - - LivingEntity livingEntity = iterator.next(); - - if (!EliteMobProperties.isValidEliteMobType(livingEntity)) continue; - - if (ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.STACK_AGGRESSIVE_NATURAL_MOBS)) - if (EntityTracker.isNaturalEntity(livingEntity)) - scanValidAggressiveLivingEntity(livingEntity); - - } - - } - - }.runTask(MetadataHandler.PLUGIN); - - } - - } - - public static void scanValidAggressiveLivingEntity(LivingEntity livingEntity) { - - if (!EntityTracker.isNaturalEntity(livingEntity) && - !ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.STACK_AGGRESSIVE_SPAWNER_MOBS)) - return; - if (EntityTracker.isNaturalEntity(livingEntity) && - !ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.STACK_AGGRESSIVE_NATURAL_MOBS)) - return; - - for (Entity secondEntity : livingEntity.getNearbyEntities(aggressiveRange, aggressiveRange, aggressiveRange)) { - - if (!secondEntity.getType().equals(livingEntity.getType())) continue; - if (!livingEntity.isValid() || !secondEntity.isValid()) continue; - - if (!EntityTracker.isNaturalEntity(secondEntity) && - !ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.STACK_AGGRESSIVE_SPAWNER_MOBS)) - return; - if (EntityTracker.isNaturalEntity(secondEntity) && - !ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.STACK_AGGRESSIVE_NATURAL_MOBS)) - return; - - - EliteMobEntity eliteMobEntity1 = null; - EliteMobEntity eliteMobEntity2 = null; - - int level1 = 1; - int level2 = 1; - - if (EntityTracker.isEliteMob(livingEntity)) { - eliteMobEntity1 = EntityTracker.getEliteMobEntity(livingEntity); - if (!eliteMobEntity1.canStack()) continue; - level1 = eliteMobEntity1.getLevel(); - } - - if (EntityTracker.isEliteMob(secondEntity)) { - eliteMobEntity2 = EntityTracker.getEliteMobEntity(secondEntity); - if (!eliteMobEntity2.canStack()) continue; - level2 = eliteMobEntity2.getLevel(); - } - - int newLevel = level1 + level2; - - if (newLevel > ConfigValues.mobCombatSettingsConfig.getInt(MobCombatSettingsConfig.ELITEMOB_STACKING_CAP)) - return; - - double healthPercentage = (livingEntity.getHealth() / livingEntity.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue() + - ((LivingEntity) secondEntity).getHealth() / ((LivingEntity) secondEntity).getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue()) / 2; - - /* - This is a bit of a dirty hack - It won't register the entity twice, but it will overwrite the existing method - */ - eliteMobEntity1 = new EliteMobEntity(livingEntity, newLevel, healthPercentage); - secondEntity.remove(); - - } - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobscanner/SuperMobScanner.java b/src/main/java/com/magmaguy/elitemobs/mobscanner/SuperMobScanner.java deleted file mode 100644 index fb35fc20d..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobscanner/SuperMobScanner.java +++ /dev/null @@ -1,107 +0,0 @@ -package com.magmaguy.elitemobs.mobscanner; - -import com.magmaguy.elitemobs.EntityTracker; -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.DefaultConfig; -import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; -import com.magmaguy.elitemobs.mobconstructor.SuperMobConstructor; -import com.magmaguy.elitemobs.mobconstructor.mobdata.passivemobs.SuperMobProperties; -import org.bukkit.World; -import org.bukkit.attribute.Attribute; -import org.bukkit.entity.Entity; -import org.bukkit.entity.LivingEntity; -import org.bukkit.scheduler.BukkitRunnable; - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.concurrent.ThreadLocalRandom; - -import static com.magmaguy.elitemobs.EliteMobs.validWorldList; - -public class SuperMobScanner { - - private static int passiveRange = ConfigValues.mobCombatSettingsConfig.getInt(MobCombatSettingsConfig.PASSIVE_STACK_RANGE); - - public static void scanSuperMobs() { - - for (World world : validWorldList) { - - if (world.getLivingEntities().isEmpty()) continue; - - Iterator iterator = world.getLivingEntities().iterator(); - - new BukkitRunnable() { - - @Override - public void run() { - - while (iterator.hasNext()) { - - LivingEntity livingEntity = iterator.next(); - - if (!SuperMobProperties.isValidSuperMobType(livingEntity)) continue; - - /* - Re-register lost passive mob - */ - checkLostSuperMob(livingEntity); - - /* - Check passive mobs to register new super mobs - */ - newSuperMobScan(livingEntity); - - } - - } - - }.runTask(MetadataHandler.PLUGIN); - - } - - } - - private static void checkLostSuperMob(LivingEntity livingEntity) { - - if (livingEntity.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue() != - SuperMobProperties.getSuperMobMaxHealth(livingEntity)) - return; - - if (!EntityTracker.isSuperMob(livingEntity)) - EntityTracker.registerSuperMob(livingEntity); - - } - - public static void newSuperMobScan(LivingEntity livingEntity) { - - if (livingEntity.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue() == - SuperMobProperties.getSuperMobMaxHealth(livingEntity)) - return; - - if (ThreadLocalRandom.current().nextDouble() < 1 / ConfigValues.defaultConfig.getDouble(DefaultConfig.SUPERMOB_STACK_AMOUNT)) - return; - - ArrayList livingEntities = new ArrayList<>(); - - for (Entity entity : livingEntity.getNearbyEntities(passiveRange, passiveRange, passiveRange)) { - - if (!entity.getType().equals(livingEntity.getType())) continue; - if (EntityTracker.isSuperMob(entity)) continue; - livingEntities.add((LivingEntity) entity); - if (livingEntities.size() >= ConfigValues.defaultConfig.getInt(DefaultConfig.SUPERMOB_STACK_AMOUNT)) - break; - - } - - if (livingEntities.size() < ConfigValues.defaultConfig.getInt(DefaultConfig.SUPERMOB_STACK_AMOUNT)) - return; - - SuperMobConstructor.constructSuperMob(livingEntity); - for (Entity entity : livingEntities) { - entity.remove(); - } - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobspawning/MobLevelCalculator.java b/src/main/java/com/magmaguy/elitemobs/mobspawning/MobLevelCalculator.java deleted file mode 100644 index c65dcdf1f..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobspawning/MobLevelCalculator.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.magmaguy.elitemobs.mobspawning; - -import com.magmaguy.elitemobs.adventurersguild.GuildRank; -import com.magmaguy.elitemobs.items.ItemTierFinder; -import com.magmaguy.elitemobs.items.MobTierFinder; -import org.bukkit.entity.Player; - -public class MobLevelCalculator { - - public static int determineMobLevel(Player player) { - - //Add selected player gear tier modifier - double perPlayerEliteMobLevel = ItemTierFinder.findPlayerTier(player); - //Add selected guild rank modifier - perPlayerEliteMobLevel += (GuildRank.getGuildRank(player.getUniqueId()) - 10) * 0.2; - - int finalTieredMobLevel = (int) (perPlayerEliteMobLevel * MobTierFinder.PER_TIER_LEVEL_INCREASE); - - return finalTieredMobLevel; - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobspawning/NaturalEliteMobSpawnEventHandler.java b/src/main/java/com/magmaguy/elitemobs/mobspawning/NaturalEliteMobSpawnEventHandler.java deleted file mode 100644 index a45a9f99b..000000000 --- a/src/main/java/com/magmaguy/elitemobs/mobspawning/NaturalEliteMobSpawnEventHandler.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.mobspawning; - -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; -import com.magmaguy.elitemobs.items.MobTierFinder; -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; -import org.bukkit.Bukkit; -import org.bukkit.GameMode; -import org.bukkit.entity.Entity; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; -import org.bukkit.event.Listener; - -import java.util.ArrayList; -import java.util.List; - -/** - * Created by MagmaGuy on 10/10/2016. - */ -public class NaturalEliteMobSpawnEventHandler implements Listener { - - private static int range = Bukkit.getServer().getViewDistance() * 16; - - /* - This manages elite mob entities that are spawned naturally - */ - public static void naturalMobProcessor(Entity entity) { - - List closePlayers = new ArrayList<>(); - - for (Player player : Bukkit.getOnlinePlayers()) - if (player.getWorld().equals(entity.getWorld()) && player.getLocation().distanceSquared(entity.getLocation()) < Math.pow(range, 2)) - if (!player.getGameMode().equals(GameMode.SPECTATOR) && (!player.hasMetadata(MetadataHandler.VANISH_NO_PACKET) || - player.hasMetadata(MetadataHandler.VANISH_NO_PACKET) && !player.getMetadata(MetadataHandler.VANISH_NO_PACKET).get(0).asBoolean())) - closePlayers.add(player); - - int eliteMobLevel = 1; - int playerCount = 0; - - for (Player player : closePlayers) { - - int individualPlayerThreat = MobLevelCalculator.determineMobLevel(player); - playerCount++; - - if (individualPlayerThreat > eliteMobLevel) - eliteMobLevel = individualPlayerThreat; - - } - - /* - Add in party system modifier - Each player adds a +0.2 tier bonus - */ - eliteMobLevel += playerCount * 0.2 * MobTierFinder.PER_TIER_LEVEL_INCREASE; - - if (ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.INCREASE_DIFFICULTY_WITH_SPAWN_DISTANCE)) { - - int levelIncrement = SpawnRadiusDifficultyIncrementer.distanceFromSpawnLevelIncrease((LivingEntity) entity); - eliteMobLevel += levelIncrement; - - } - - if (playerCount == 0 || eliteMobLevel < 1) return; - - EliteMobEntity eliteMobEntity = new EliteMobEntity((LivingEntity) entity, eliteMobLevel); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/mobspawning/NaturalMobSpawnEventHandler.java b/src/main/java/com/magmaguy/elitemobs/mobspawning/NaturalMobSpawnEventHandler.java index 5084889ad..36db30e49 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobspawning/NaturalMobSpawnEventHandler.java +++ b/src/main/java/com/magmaguy/elitemobs/mobspawning/NaturalMobSpawnEventHandler.java @@ -1,141 +1,179 @@ -/* - * 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 . - */ - package com.magmaguy.elitemobs.mobspawning; -import com.magmaguy.elitemobs.EntityTracker; -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.config.*; -import com.magmaguy.elitemobs.items.customenchantments.CustomEnchantmentCache; +import com.magmaguy.elitemobs.EliteMobs; +import com.magmaguy.elitemobs.adventurersguild.GuildRank; +import com.magmaguy.elitemobs.config.AdventurersGuildConfig; +import com.magmaguy.elitemobs.config.DefaultConfig; +import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; +import com.magmaguy.elitemobs.config.ValidWorldsConfig; +import com.magmaguy.elitemobs.config.mobproperties.MobPropertiesConfig; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.gamemodes.zoneworld.Grid; +import com.magmaguy.elitemobs.items.MobTierCalculator; +import com.magmaguy.elitemobs.items.customenchantments.HunterEnchantment; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; import com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs.EliteMobProperties; -import org.bukkit.Bukkit; -import org.bukkit.entity.Entity; +import com.magmaguy.elitemobs.playerdata.ElitePlayerInventory; +import com.magmaguy.elitemobs.playerdata.database.PlayerData; +import com.magmaguy.elitemobs.thirdparty.worldguard.WorldGuardCompatibility; +import com.magmaguy.elitemobs.thirdparty.worldguard.WorldGuardFlagChecker; +import com.magmaguy.elitemobs.thirdparty.worldguard.WorldGuardSpawnEventBypasser; +import com.magmaguy.elitemobs.utils.PlayerScanner; +import com.magmaguy.elitemobs.utils.VersionChecker; +import org.bukkit.Location; +import org.bukkit.entity.EntityType; import org.bukkit.entity.LivingEntity; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.entity.CreatureSpawnEvent; -import org.bukkit.inventory.ItemStack; +import java.util.List; import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.atomic.AtomicInteger; import static org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.CUSTOM; -import static org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.NATURAL; +import static org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason.DROWNED; /** * Created by MagmaGuy on 24/04/2017. */ public class NaturalMobSpawnEventHandler implements Listener { - private static int range = Bukkit.getServer().getViewDistance() * 16; - private static boolean ignoreMob = false; + /** + * This gets the level the natural Elite Mob should have. This level is determined by the power of the armor and weapons + * the players are wearing, as well as by how many players are in the area. + * + * @param spawnLocation Location to scan around for players + * @return + */ + public static int getNaturalMobLevel(Location spawnLocation, List nearbyPlayers) { - public static void setIgnoreMob(boolean bool) { - ignoreMob = bool; - } + int eliteMobLevel = 1; + int playerCount = 0; + + for (Player player : nearbyPlayers) { + int individualPlayerThreat = ElitePlayerInventory.playerInventories.get(player.getUniqueId()).getNaturalMobSpawnLevel(true); + playerCount++; + + if (individualPlayerThreat > eliteMobLevel) + eliteMobLevel = individualPlayerThreat; + } + + /* + Party system modifier + Each player adds a +2 tier bonus + */ + eliteMobLevel += playerCount * 2 * MobTierCalculator.PER_TIER_LEVEL_INCREASE; + + if (MobCombatSettingsConfig.isIncreaseDifficultyWithSpawnDistance()) { + int levelIncrement = SpawnRadiusDifficultyIncrementer.distanceFromSpawnLevelIncrease(spawnLocation); + eliteMobLevel += levelIncrement; + } + + if (playerCount == 0 || eliteMobLevel < 1) return 0; + + //add wiggle room + int wiggle = ThreadLocalRandom.current().nextInt(5) - 2; + eliteMobLevel = Math.max(wiggle + eliteMobLevel, 1); + + return eliteMobLevel; - private static boolean getIgnoreMob() { - return ignoreMob; } - @EventHandler(priority = EventPriority.HIGHEST) + @EventHandler(priority = EventPriority.HIGH, ignoreCancelled = true) public void onSpawn(CreatureSpawnEvent event) { - if (getIgnoreMob()) { - setIgnoreMob(false); + if (event.getSpawnReason().equals(DROWNED)) return; + + if (!VersionChecker.serverVersionOlderThan(15, 0)) + if (event.getEntity().getType().equals(EntityType.BEE)) + return; + + + if (MobPropertiesConfig.getMobProperties().get(event.getEntityType()) == null || + !MobPropertiesConfig.getMobProperties().get(event.getEntityType()).isEnabled()) return; - } - if (event.isCancelled()) return; + if (EliteMobs.worldGuardIsEnabled) + if (!WorldGuardFlagChecker.checkFlag(event.getLocation(), WorldGuardCompatibility.getEliteMobsSpawnFlag())) + return; + + //This fires for custom bosses, so don't override those spawns + if (WorldGuardSpawnEventBypasser.isForcedSpawn()) return; + /* Deal with entities spawned within the plugin */ if (EntityTracker.isEliteMob(event.getEntity())) return; - if (!ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.NATURAL_MOB_SPAWNING)) - return; - if (!ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.ALLOW_AGGRESSIVE_ELITEMOBS)) + if (!MobCombatSettingsConfig.isDoNaturalMobSpawning()) return; - if (!ConfigValues.validWorldsConfig.getBoolean("Valid worlds." + event.getEntity().getWorld().getName())) + if (!ValidWorldsConfig.getFileConfiguration().getBoolean("Valid worlds." + event.getEntity().getWorld().getName())) return; - if (event.getSpawnReason().equals(CreatureSpawnEvent.SpawnReason.SPAWNER) && !ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.SPAWNERS_SPAWN_ELITE_MOBS)) + if (event.getSpawnReason().equals(CreatureSpawnEvent.SpawnReason.SPAWNER) && + !MobCombatSettingsConfig.isDoSpawnersSpawnEliteMobs() || event.getSpawnReason() == CUSTOM && DefaultConfig.isDoStrictSpawningRules()) return; - if (event.getEntity().getCustomName() != null && ConfigValues.defaultConfig.getBoolean(DefaultConfig.PREVENT_ELITE_MOB_CONVERSION_OF_NAMED_MOBS)) + if (event.getEntity().getCustomName() != null && DefaultConfig.isPreventEliteMobConversionOfNamedMobs()) return; - if (!(event.getSpawnReason() == NATURAL || event.getSpawnReason() == CUSTOM && !ConfigValues.defaultConfig.getBoolean(DefaultConfig.STRICT_SPAWNING_RULES))) - return; if (!EliteMobProperties.isValidEliteMobType(event.getEntityType())) return; LivingEntity livingEntity = event.getEntity(); - int huntingGearChanceAdder = getHuntingGearBonus(livingEntity); - Double validChance = (ConfigValues.mobCombatSettingsConfig.getDouble(MobCombatSettingsConfig.AGGRESSIVE_MOB_CONVERSION_PERCENTAGE) + - huntingGearChanceAdder) / 100; + double validChance = MobCombatSettingsConfig.getAggressiveMobConversionPercentage(); - if (!(ThreadLocalRandom.current().nextDouble() < validChance)) - return; + List nearbyPlayers = PlayerScanner.getNearbyPlayers(livingEntity.getLocation()); - NaturalEliteMobSpawnEventHandler.naturalMobProcessor(livingEntity); + double huntingGearChanceAdder = HunterEnchantment.getHuntingGearBonus(nearbyPlayers); + validChance += huntingGearChanceAdder; - } - - private static int getHuntingGearBonus(Entity entity) { + if (ValidWorldsConfig.getNightmareWorlds().contains(event.getEntity().getWorld().getName())) + validChance += DefaultConfig.getNightmareWorldSpawnBonus(); - int huntingGearChanceAdder = 0; + AtomicInteger peacefulModeDebuffs = new AtomicInteger(); + nearbyPlayers.forEach(player -> { + //Handles situations where fake players got caught in the detection + if (PlayerData.getPlayerData(player.getUniqueId()) != null && GuildRank.getActiveGuildRank(player) == 0) + peacefulModeDebuffs.getAndIncrement(); + }); - for (Player player : Bukkit.getOnlinePlayers()) { + validChance -= peacefulModeDebuffs.get() * AdventurersGuildConfig.getPeacefulModeEliteChanceDecrease(); - if (player.getWorld().equals(entity.getWorld()) && - (!player.hasMetadata(MetadataHandler.VANISH_NO_PACKET) || - player.hasMetadata(MetadataHandler.VANISH_NO_PACKET) && !player.getMetadata(MetadataHandler.VANISH_NO_PACKET).get(0).asBoolean())) { + if (ThreadLocalRandom.current().nextDouble() >= validChance) return; - if (player.getLocation().distance(entity.getLocation()) < range) { - - ItemStack helmet = player.getInventory().getHelmet(); - ItemStack chestplate = player.getInventory().getChestplate(); - ItemStack leggings = player.getInventory().getLeggings(); - ItemStack boots = player.getInventory().getBoots(); - ItemStack heldItem = player.getInventory().getItemInMainHand(); - ItemStack offHandItem = player.getInventory().getItemInOffHand(); + if (ValidWorldsConfig.getZoneBasedWorlds().contains(livingEntity.getWorld().getName())) { + int eliteMobLevel = (int) (Grid.getMobTierFromLocation(livingEntity.getLocation())); + EliteEntity eliteEntity = new EliteEntity(livingEntity, eliteMobLevel, event.getSpawnReason()); + if (event.getSpawnReason().equals(CreatureSpawnEvent.SpawnReason.SPAWNER)) + eliteEntity.setEliteLoot(false); + return; + } - if (CustomEnchantmentCache.hunterEnchantment.hasCustomEnchantment(helmet)) - huntingGearChanceAdder += CustomEnchantmentCache.hunterEnchantment.getCustomEnchantmentLevel(helmet); - if (CustomEnchantmentCache.hunterEnchantment.hasCustomEnchantment(chestplate)) - huntingGearChanceAdder += CustomEnchantmentCache.hunterEnchantment.getCustomEnchantmentLevel(chestplate); - if (CustomEnchantmentCache.hunterEnchantment.hasCustomEnchantment(leggings)) - huntingGearChanceAdder += CustomEnchantmentCache.hunterEnchantment.getCustomEnchantmentLevel(leggings); - if (CustomEnchantmentCache.hunterEnchantment.hasCustomEnchantment(boots)) - huntingGearChanceAdder += CustomEnchantmentCache.hunterEnchantment.getCustomEnchantmentLevel(boots); - if (CustomEnchantmentCache.hunterEnchantment.hasCustomEnchantment(heldItem)) - huntingGearChanceAdder += CustomEnchantmentCache.hunterEnchantment.getCustomEnchantmentLevel(heldItem); - if (CustomEnchantmentCache.hunterEnchantment.hasCustomEnchantment(offHandItem)) - huntingGearChanceAdder += CustomEnchantmentCache.hunterEnchantment.getCustomEnchantmentLevel(offHandItem); + int eliteMobLevel = getNaturalMobLevel(livingEntity.getLocation(), nearbyPlayers); - } + //Takes worldguard minimum and maximum level flags into account + if (EliteMobs.worldGuardIsEnabled) { + Integer minLevel = WorldGuardFlagChecker.getRegionMinimumLevel(livingEntity.getLocation()); + Integer maxLevel = WorldGuardFlagChecker.getRegionMaximumLevel(livingEntity.getLocation()); + if (minLevel != null) + eliteMobLevel = minLevel > eliteMobLevel ? minLevel : eliteMobLevel; + if (maxLevel != null) + eliteMobLevel = maxLevel < eliteMobLevel ? maxLevel : eliteMobLevel; + } - } + if (eliteMobLevel < 0) return; - } + if (eliteMobLevel > MobCombatSettingsConfig.getNaturalEliteMobLevelCap()) + eliteMobLevel = MobCombatSettingsConfig.getNaturalEliteMobLevelCap(); - huntingGearChanceAdder = huntingGearChanceAdder * ConfigValues.customEnchantmentsConfig.getInt(CustomEnchantmentsConfig.HUNTER_SPAWN_BONUS); + EliteEntity eliteEntity = new EliteEntity(livingEntity, eliteMobLevel, event.getSpawnReason()); - return huntingGearChanceAdder; + if (event.getSpawnReason().equals(CreatureSpawnEvent.SpawnReason.SPAWNER)) + eliteEntity.setEliteLoot(false); } diff --git a/src/main/java/com/magmaguy/elitemobs/mobspawning/SpawnRadiusDifficultyIncrementer.java b/src/main/java/com/magmaguy/elitemobs/mobspawning/SpawnRadiusDifficultyIncrementer.java index 2f37f71ba..f009956fa 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobspawning/SpawnRadiusDifficultyIncrementer.java +++ b/src/main/java/com/magmaguy/elitemobs/mobspawning/SpawnRadiusDifficultyIncrementer.java @@ -1,40 +1,21 @@ -/* - * 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 . - */ - package com.magmaguy.elitemobs.mobspawning; -import com.magmaguy.elitemobs.config.ConfigValues; import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; import org.bukkit.Location; -import org.bukkit.entity.LivingEntity; public class SpawnRadiusDifficultyIncrementer { - public static int distanceFromSpawnLevelIncrease(LivingEntity livingEntity) { + public static int distanceFromSpawnLevelIncrease(Location location) { - double distanceUnit = ConfigValues.mobCombatSettingsConfig.getDouble(MobCombatSettingsConfig.DISTANCE_TO_INCREMENT); - double levelToIncrement = ConfigValues.mobCombatSettingsConfig.getDouble(MobCombatSettingsConfig.LEVEL_TO_INCREMENT); + double distanceUnit = MobCombatSettingsConfig.getDistanceToIncrement(); + double levelToIncrement = MobCombatSettingsConfig.getLevelToIncrement(); - Location spawnLocation = livingEntity.getWorld().getSpawnLocation(); - Location entityLocation = livingEntity.getLocation(); + Location spawnLocation = location.getWorld().getSpawnLocation(); + Location entityLocation = location; double distanceFromSpawn = spawnLocation.distance(entityLocation); - int levelIncrease = (int) (distanceFromSpawn / distanceUnit * levelToIncrement); - - return levelIncrease; + return (int) (distanceFromSpawn / distanceUnit * levelToIncrement); } diff --git a/src/main/java/com/magmaguy/elitemobs/npcs/NPCDamageEvent.java b/src/main/java/com/magmaguy/elitemobs/npcs/NPCDamageEvent.java new file mode 100644 index 000000000..fc57f2726 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/npcs/NPCDamageEvent.java @@ -0,0 +1,16 @@ +package com.magmaguy.elitemobs.npcs; + +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageEvent; + +public class NPCDamageEvent implements Listener { + + @EventHandler + public void onNPCDamage(EntityDamageEvent event) { + if (!EntityTracker.isNPCEntity(event.getEntity())) return; + event.setCancelled(true); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/npcs/NPCEntity.java b/src/main/java/com/magmaguy/elitemobs/npcs/NPCEntity.java new file mode 100644 index 000000000..2f39fef20 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/npcs/NPCEntity.java @@ -0,0 +1,288 @@ +package com.magmaguy.elitemobs.npcs; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.internal.RemovalReason; +import com.magmaguy.elitemobs.config.npcs.NPCsConfig; +import com.magmaguy.elitemobs.config.npcs.NPCsConfigFields; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.SimplePersistentEntity; +import com.magmaguy.elitemobs.mobconstructor.SimplePersistentEntityInterface; +import com.magmaguy.elitemobs.npcs.chatter.NPCChatBubble; +import com.magmaguy.elitemobs.thirdparty.libsdisguises.DisguiseEntity; +import com.magmaguy.elitemobs.thirdparty.modelengine.CustomModel; +import com.magmaguy.elitemobs.thirdparty.worldguard.WorldGuardSpawnEventBypasser; +import com.magmaguy.elitemobs.utils.ChunkLocationChecker; +import com.magmaguy.elitemobs.utils.ConfigurationLocation; +import com.magmaguy.elitemobs.utils.NonSolidBlockTypes; +import com.magmaguy.elitemobs.utils.WarningMessage; +import lombok.Getter; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.entity.Villager; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Consumer; +import org.bukkit.util.Vector; + +import java.util.List; +import java.util.UUID; +import java.util.concurrent.ThreadLocalRandom; + +public class NPCEntity implements SimplePersistentEntityInterface { + + public final NPCsConfigFields npCsConfigFields; + @Getter + private final UUID uuid = UUID.randomUUID(); + public SimplePersistentEntity simplePersistentEntity; + private Villager villager = null; + private Location spawnLocation; + private boolean isTalking = false; + private ArmorStand roleDisplay; + private boolean isDisguised = false; + + /** + * Spawns NPC based off of the values in the NPCsConfig config file. Runs at startup and on reload. + */ + public NPCEntity(NPCsConfigFields npCsConfigFields) { + this.npCsConfigFields = npCsConfigFields; + if (!npCsConfigFields.isEnabled()) return; + //this is how the wandering trader works + if (npCsConfigFields.getLocation() == null || npCsConfigFields.getLocation().equalsIgnoreCase("null")) + return; + setSpawnLocation(); + queueSpawn(); + } + + /** + * For the travelling merchant + * + * @param location + */ + public NPCEntity(Location location) { + this.npCsConfigFields = NPCsConfig.getNpcEntities().get("travelling_merchant.yml"); + if (!npCsConfigFields.isEnabled()) return; + Location potentialLocation = location.clone(); + potentialLocation.add(potentialLocation.getDirection().normalize()).setY(location.getY()); + if (NonSolidBlockTypes.isPassthrough(potentialLocation.getBlock().getType())) + this.spawnLocation = potentialLocation; + else this.spawnLocation = location.clone(); + this.spawnLocation.setDirection(this.spawnLocation.getDirection().multiply(-1)); + spawn(); + } + + public void queueSpawn() { + if (spawnLocation != null && ChunkLocationChecker.locationIsLoaded(spawnLocation)) { + spawn(); + return; + } + simplePersistentEntity = new SimplePersistentEntity(this); + } + + private void spawn() { + if (villager != null && villager.isValid()) return; + WorldGuardSpawnEventBypasser.forceSpawn(); + villager = spawnLocation.getWorld().spawn(spawnLocation, Villager.class, villagerInstance -> { + villagerInstance.setAI(false); + villagerInstance.setPersistent(false); + villagerInstance.setRemoveWhenFarAway(false); + villagerInstance.setCustomName(ChatColorConverter.convert(npCsConfigFields.getName())); + villagerInstance.setCustomNameVisible(true); + villagerInstance.setProfession(npCsConfigFields.getProfession()); + if (getNPCsConfigFields().getCustomModel() != null && !getNPCsConfigFields().getCustomModel().isEmpty()) + setCustomModel(villagerInstance); + else + setDisguise(villagerInstance); + }); + EntityTracker.registerNPCEntity(this); + initializeRole(); + setTimeout(); + simplePersistentEntity = null; + } + + private void setDisguise(LivingEntity livingEntity) { + if (npCsConfigFields.getDisguise() == null) return; + if (!Bukkit.getPluginManager().isPluginEnabled("LibsDisguises")) return; + try { + DisguiseEntity.disguise(npCsConfigFields.getDisguise(), livingEntity, npCsConfigFields.getCustomDisguiseData(), npCsConfigFields.getFilename()); + DisguiseEntity.setDisguiseNameVisibility(true, livingEntity); + livingEntity.setCustomNameVisible(true); + isDisguised = true; + } catch (Exception ex) { + new WarningMessage("Failed to load LibsDisguises disguise correctly!"); + ex.printStackTrace(); + } + } + + private void setCustomModel(LivingEntity livingEntity) { + CustomModel.generateCustomModel(livingEntity, getNPCsConfigFields().getCustomModel(), getNPCsConfigFields().getName()); + } + + public Villager getVillager() { + return villager; + } + + public boolean isValid() { + if (villager == null) return false; + return villager.isValid(); + } + + public NPCsConfigFields getNPCsConfigFields() { + return npCsConfigFields; + } + + public Location getSpawnLocation() { + return spawnLocation; + } + + public boolean setSpawnLocation() { + Location location = ConfigurationLocation.serialize(npCsConfigFields.getLocation()); + if (location == null) return false; + this.spawnLocation = location; + return true; + } + + public boolean getIsTalking() { + return this.isTalking; + } + + @Override + public void chunkLoad() { + spawn(); + } + + @Override + public void chunkUnload() { + if (villager != null) + villager.remove(); + if (getNPCsConfigFields().getTimeout() > 0) return; + + if (villager != null) + villager.remove(); + } + + @Override + public void worldLoad() { + setSpawnLocation(); + queueSpawn(); + } + + @Override + public void worldUnload() { + spawnLocation = null; + simplePersistentEntity = new SimplePersistentEntity(this); + remove(RemovalReason.WORLD_UNLOAD); + } + + //Can't be used after the NPCEntity is done initialising + private void initializeRole() { + Vector offSet; + if (!isDisguised) + offSet = new Vector(0, 1.72, 0); + else + offSet = new Vector(0, 1.70, 0); + roleDisplay = this.villager.getWorld().spawn(villager.getLocation().add(offSet), ArmorStand.class, new Consumer() { + @Override + public void accept(ArmorStand armorStand) { + armorStand.setCustomName(npCsConfigFields.getRole()); + armorStand.setCustomNameVisible(true); + armorStand.setMarker(true); + armorStand.setVisible(false); + armorStand.setGravity(false); + armorStand.setPersistent(false); + } + }); + EntityTracker.registerVisualEffects(roleDisplay); + } + + /** + * Starts a cooldown for the talking state. Useful to avoid overlapping speech. + */ + public void startTalkingCooldown() { + this.isTalking = true; + new BukkitRunnable() { + @Override + public void run() { + isTalking = false; + } + }.runTaskLater(MetadataHandler.PLUGIN, 20 * 3); + } + + public void setTimeout() { + if (npCsConfigFields.getTimeout() <= 0) return; + new BukkitRunnable() { + @Override + public void run() { + remove(RemovalReason.NPC_TIMEOUT); + } + }.runTaskLater(MetadataHandler.PLUGIN, (long) (npCsConfigFields.getTimeout() * 20 * 60)); + } + + public void remove(RemovalReason removalReason) { + if (roleDisplay != null) + roleDisplay.remove(); + if (villager != null) { + villager.remove(); + EntityTracker.getNpcEntities().remove(villager.getUniqueId()); + this.villager = null; + } + + if (removalReason.equals(RemovalReason.CHUNK_UNLOAD)) { + simplePersistentEntity = new SimplePersistentEntity(this); + } + + boolean permanentRemoval = false; + + if (removalReason.equals(RemovalReason.REMOVE_COMMAND)) + npCsConfigFields.setEnabled(false); + + if (removalReason.equals(RemovalReason.WORLD_UNLOAD) || + removalReason.equals(RemovalReason.REMOVE_COMMAND)) + permanentRemoval = true; + + if (permanentRemoval) + spawnLocation = null; + } + + /** + * Sends a greeting to a player from the list of greetings the NPCEntity has + * + * @param player Player to send the greeting to + */ + public void sayGreeting(Player player) { + new NPCChatBubble(selectString(npCsConfigFields.getDialog()), this, player); + } + + /** + * Sends a dialog message to a player from the list of dialog messages the NPCEntity has + * + * @param player Player to send the dialog to + */ + public void sayDialog(Player player) { + new NPCChatBubble(selectString(npCsConfigFields.getDialog()), this, player); + } + + /** + * Sends a farewell message to a player from the list of farewell messages the NPCEntity has + * + * @param player + */ + public void sayFarewell(Player player) { + new NPCChatBubble(selectString(npCsConfigFields.getFarewell()), this, player); + } + + /** + * Selects a string from a list of strings + * + * @param strings List of string to select from + * @return Selected String + */ + private String selectString(List strings) { + if (strings != null && !strings.isEmpty()) + return strings.get(ThreadLocalRandom.current().nextInt(strings.size())); + return null; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/npcs/NPCInteractions.java b/src/main/java/com/magmaguy/elitemobs/npcs/NPCInteractions.java new file mode 100644 index 000000000..a6a42a551 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/npcs/NPCInteractions.java @@ -0,0 +1,236 @@ +package com.magmaguy.elitemobs.npcs; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.adventurersguild.GuildRankMenuHandler; +import com.magmaguy.elitemobs.api.PlayerPreTeleportEvent; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.menus.*; +import com.magmaguy.elitemobs.playerdata.database.PlayerData; +import com.magmaguy.elitemobs.quests.QuestInteractionHandler; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryOpenEvent; +import org.bukkit.event.inventory.InventoryType; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.HashSet; + +public class NPCInteractions implements Listener { + + private static HashSet cooldowns = new HashSet<>(); + + @EventHandler(priority = EventPriority.HIGHEST) + public void playerNPCInteract(PlayerInteractAtEntityEvent event) { + + if (cooldowns.contains(event.getPlayer())) return; + cooldowns.add(event.getPlayer()); + Bukkit.getScheduler().runTaskLater(MetadataHandler.PLUGIN, () -> cooldowns.remove(event.getPlayer()), 1); + if (event.isCancelled()) return; + + NPCEntity npcEntity = EntityTracker.getNPCEntity(event.getRightClicked()); + if (npcEntity == null) return; + if (event.getPlayer().getInventory().getItemInMainHand().getType().equals(Material.NAME_TAG)) { + event.setCancelled(true); + event.getPlayer().sendMessage("[EliteMobs] You can't rename NPCs using name tags!"); + return; + } + + event.setCancelled(true); + + switch (npcEntity.getNPCsConfigFields().getInteractionType()) { + case GUILD_GREETER: + if (event.getPlayer().hasPermission("elitemobs.rank.npc")) { + new BukkitRunnable() { + @Override + public void run() { + GuildRankMenuHandler.initializeGuildRankMenu(event.getPlayer()); + } + }.runTaskLater(MetadataHandler.PLUGIN, 1); + } + break; + case CHAT: + npcEntity.sayDialog(event.getPlayer()); + break; + case CUSTOM_SHOP: + if (event.getPlayer().hasPermission("elitemobs.customshop.npc")) + new BukkitRunnable() { + @Override + public void run() { + CustomShopMenu.customShopInitializer(event.getPlayer()); + } + }.runTaskLater(MetadataHandler.PLUGIN, 1); + + break; + case PROCEDURALLY_GENERATED_SHOP: + if (event.getPlayer().hasPermission("elitemobs.shop.npc")) + new BukkitRunnable() { + @Override + public void run() { + ProceduralShopMenu.shopInitializer(event.getPlayer()); + } + }.runTaskLater(MetadataHandler.PLUGIN, 1); + break; + case QUEST_GIVER: + if (event.getPlayer().hasPermission("elitemobs.quest.npc")) + new BukkitRunnable() { + @Override + public void run() { + QuestInteractionHandler.processDynamicQuests(event.getPlayer(), npcEntity); + } + }.runTaskLater(MetadataHandler.PLUGIN, 1); + break; + case CUSTOM_QUEST_GIVER: + QuestInteractionHandler.processNPCQuests(event.getPlayer(), npcEntity); + break; + case BAR: + event.getPlayer().sendMessage("[EliteMobs] This feature is coming soon!"); + break; + case ARENA: + event.getPlayer().sendMessage("[EliteMobs] This feature is coming soon!"); + break; + case SELL: + if (event.getPlayer().hasPermission("elitemobs.shop.npc")) + new BukkitRunnable() { + @Override + public void run() { + SellMenu sellMenu = new SellMenu(); + sellMenu.constructSellMenu(event.getPlayer()); + } + }.runTaskLater(MetadataHandler.PLUGIN, 1); + break; + case TELEPORT_BACK: + if (event.getPlayer().hasPermission("elitemobs.back.npc")) { + Location previousLocation = PlayerData.getBackTeleportLocation(event.getPlayer()); + if (previousLocation == null) { + if (npcEntity.npCsConfigFields.noPreviousLocationMessage != null) + event.getPlayer().sendMessage(ChatColorConverter.convert(npcEntity.npCsConfigFields.noPreviousLocationMessage)); + } else + PlayerPreTeleportEvent.teleportPlayer(event.getPlayer(), previousLocation); + } + break; + case SCRAPPER: + if (event.getPlayer().hasPermission("elitemobs.scrap.npc")) { + new BukkitRunnable() { + @Override + public void run() { + ScrapperMenu scrapperMenu = new ScrapperMenu(); + scrapperMenu.constructScrapMenu(event.getPlayer()); + } + }.runTaskLater(MetadataHandler.PLUGIN, 1); + } + break; + case SMELTER: + if (event.getPlayer().hasPermission("elitemobs.smelt.npc")) { + new BukkitRunnable() { + @Override + public void run() { + SmeltMenu smeltMenu = new SmeltMenu(); + smeltMenu.constructSmeltMenu(event.getPlayer()); + } + }.runTaskLater(MetadataHandler.PLUGIN, 1); + } + break; + case REPAIRMAN: + if (event.getPlayer().hasPermission("elitemobs.repair.npc")) { + new BukkitRunnable() { + @Override + public void run() { + RepairMenu repairMenu = new RepairMenu(); + repairMenu.constructRepairMenu(event.getPlayer()); + } + }.runTaskLater(MetadataHandler.PLUGIN, 1); + } + break; + case ENHANCER: + if (event.getPlayer().hasPermission("elitemobs.enhancer.npc")) { + new BukkitRunnable() { + @Override + public void run() { + EnhancementMenu enhancementMenu = new EnhancementMenu(); + enhancementMenu.constructEnhancementMenu(event.getPlayer()); + } + }.runTaskLater(MetadataHandler.PLUGIN, 1); + } + break; + case REFINER: + if (event.getPlayer().hasPermission("elitemobs.refiner.npc")) { + new BukkitRunnable() { + @Override + public void run() { + RefinerMenu refinerMenu = new RefinerMenu(); + refinerMenu.constructRefinerMenu(event.getPlayer()); + } + }.runTaskLater(MetadataHandler.PLUGIN, 1); + } + break; + case UNBINDER: + if (event.getPlayer().hasPermission("elitemobs.unbind.npc")) { + new BukkitRunnable() { + @Override + public void run() { + UnbindMenu unbindMenu = new UnbindMenu(); + unbindMenu.constructUnbinderMenu(event.getPlayer()); + } + }.runTaskLater(MetadataHandler.PLUGIN, 1); + } + break; + case ARENA_MASTER: + new BukkitRunnable() { + @Override + public void run() { + ArenaMenu arenaMenu = new ArenaMenu(); + arenaMenu.constructArenaMenu(event.getPlayer(), npcEntity.getNPCsConfigFields().getArenaFilename()); + } + }.runTaskLater(MetadataHandler.PLUGIN, 1); + break; + case NONE: + default: + break; + + } + + } + + @EventHandler + public void onInventoryOpen(InventoryOpenEvent event) { + + if (!event.getInventory().getType().equals(InventoryType.MERCHANT)) return; + + for (NPCEntity npcEntity : EntityTracker.getNpcEntities().values()) + if (event.getView().getTitle().equals(npcEntity.getNPCsConfigFields().getName())) { + event.setCancelled(true); + return; + } + + } + + public enum NPCInteractionType { + GUILD_GREETER, + CHAT, + CUSTOM_SHOP, + PROCEDURALLY_GENERATED_SHOP, + BAR, + ARENA, + QUEST_GIVER, + CUSTOM_QUEST_GIVER, + NONE, + SELL, + TELEPORT_BACK, + SCRAPPER, + SMELTER, + REPAIRMAN, + ENHANCER, + REFINER, + UNBINDER, + ARENA_MASTER + } + + +} diff --git a/src/main/java/com/magmaguy/elitemobs/npcs/chatter/NPCChatBubble.java b/src/main/java/com/magmaguy/elitemobs/npcs/chatter/NPCChatBubble.java new file mode 100644 index 000000000..2d5fa2bd0 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/npcs/chatter/NPCChatBubble.java @@ -0,0 +1,67 @@ +package com.magmaguy.elitemobs.npcs.chatter; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.npcs.NPCEntity; +import com.magmaguy.elitemobs.utils.VisualArmorStand; +import org.bukkit.Location; +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +public class NPCChatBubble { + + public NPCChatBubble(String message, NPCEntity npcEntity, Player player) { + + if (!npcEntity.getNPCsConfigFields().isCanTalk()) return; + + if (message == null) return; + if (npcEntity.getVillager().hasPotionEffect(PotionEffectType.INVISIBILITY)) return; + if (npcEntity.getIsTalking()) return; + npcEntity.startTalkingCooldown(); + + int lineCounter = 0; + + for (String substring : message.split("\\\\n")) { + + Location newLocation = npcEntity.getVillager().getEyeLocation().clone() + .add(player.getLocation().clone().subtract(npcEntity.getVillager().getLocation()).toVector().normalize().multiply(0.5)) + .add(new Vector(0, -0.8 - (0.2 * lineCounter), 0)); + + ArmorStand visualArmorStand = VisualArmorStand.VisualArmorStand(newLocation, substring); + + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + if (counter > 20 * 5 || npcEntity.getVillager() == null || !npcEntity.getVillager().isValid() || !visualArmorStand.isValid()) { + visualArmorStand.remove(); + cancel(); + return; + } + visualArmorStand.teleport(visualArmorStand.getLocation().clone().add(new Vector(0, 0.005, 0))); + counter++; + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + + lineCounter++; + + } + + } + + public NPCChatBubble(List message, NPCEntity npcEntity, Player player) { + + String selectedMessage = message.get(ThreadLocalRandom.current().nextInt(message.size())); + + new NPCChatBubble(selectedMessage, npcEntity, player); + + } + + +} diff --git a/src/main/java/com/magmaguy/elitemobs/npcs/chatter/NPCProximitySensor.java b/src/main/java/com/magmaguy/elitemobs/npcs/chatter/NPCProximitySensor.java new file mode 100644 index 000000000..200822871 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/npcs/chatter/NPCProximitySensor.java @@ -0,0 +1,185 @@ +package com.magmaguy.elitemobs.npcs.chatter; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.internal.RemovalReason; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.npcs.NPCEntity; +import com.magmaguy.elitemobs.npcs.NPCInteractions; +import com.magmaguy.elitemobs.playerdata.database.PlayerData; +import com.magmaguy.elitemobs.quests.CustomQuest; +import com.magmaguy.elitemobs.quests.DynamicQuest; +import com.magmaguy.elitemobs.quests.Quest; +import com.magmaguy.elitemobs.utils.VisualArmorStand; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import java.util.HashSet; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +public class NPCProximitySensor implements Listener { + + private final HashSet nearbyPlayers = new HashSet<>(); + + public NPCProximitySensor() { + + new BukkitRunnable() { + + @Override + public void run() { + + HashSet seenPlayerList = (HashSet) nearbyPlayers.clone(); + + for (NPCEntity npcEntity : EntityTracker.getNpcEntities().values()) + if (npcEntity.isValid()) { + boolean alreadySpoke = false; + for (Entity entity : npcEntity.getVillager().getNearbyEntities(npcEntity.getNPCsConfigFields().getActivationRadius(), + npcEntity.getNPCsConfigFields().getActivationRadius(), npcEntity.getNPCsConfigFields().getActivationRadius())) + if (entity.getType().equals(EntityType.PLAYER)) { + Player player = (Player) entity; + Location rotatedLocation = npcEntity.getVillager().getLocation().setDirection(entity.getLocation().subtract(npcEntity.getVillager().getLocation()).toVector()); + npcEntity.getVillager().teleport(rotatedLocation); + if (nearbyPlayers.contains(player)) { + if (!alreadySpoke) + if (!npcEntity.getNPCsConfigFields().getInteractionType().equals(NPCInteractions.NPCInteractionType.CHAT)) + npcEntity.sayDialog(player); + seenPlayerList.remove(player); + alreadySpoke = true; + } else { + if (!alreadySpoke) + npcEntity.sayGreeting(player); + nearbyPlayers.add(player); + startQuestIndicator(npcEntity, player); + alreadySpoke = true; + } + } + } + + for (Player player : seenPlayerList) + nearbyPlayers.remove(player); + + } + + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 20L * 5L); + + } + + private void startQuestIndicator(NPCEntity npcEntity, Player player) { + if (!npcEntity.getNPCsConfigFields().getInteractionType().equals(NPCInteractions.NPCInteractionType.QUEST_GIVER) && + !npcEntity.getNPCsConfigFields().getInteractionType().equals(NPCInteractions.NPCInteractionType.CUSTOM_QUEST_GIVER)) + return; + findQuestState(npcEntity, player); + + } + + private void findQuestState(NPCEntity npcEntity, Player player) { + if (npcEntity.getNPCsConfigFields().getInteractionType().equals(NPCInteractions.NPCInteractionType.CUSTOM_QUEST_GIVER)) { + if (!PlayerData.getQuests(player.getUniqueId()).isEmpty()) { + for (String questString : npcEntity.getNPCsConfigFields().getQuestFilenames()) + for (Quest quest : PlayerData.getQuests(player.getUniqueId())) + if (quest instanceof CustomQuest && + questString.equals(((CustomQuest) quest).getCustomQuestsConfigFields().getFilename())) + if (!quest.isAccepted()) { + if (!((CustomQuest) quest).hasPermissionForQuest(player)) + return; + //Quest yet to be accepted + unacceptedQuestIndicator(npcEntity, player); + return; + } else if (!quest.getQuestObjectives().isOver()) { + //Quest has been accepted but not completed + acceptedQuestIndicator(npcEntity, player); + return; + } else { + //Quest has been completed + completedQuestIndicator(npcEntity, player); + return; + } + } + } else if (npcEntity.getNPCsConfigFields().getInteractionType().equals(NPCInteractions.NPCInteractionType.QUEST_GIVER)) { + for (Quest quest : PlayerData.getQuests(player.getUniqueId())) + if (quest instanceof DynamicQuest) + //Dynamic quest + if (!quest.isAccepted()) { + //Quest yet to be accepted + unacceptedQuestIndicator(npcEntity, player); + return; + } else if (!quest.getQuestObjectives().isOver()) { + //Quest has been accepted but not completed + acceptedQuestIndicator(npcEntity, player); + return; + } else { + //Quest has been completed + completedQuestIndicator(npcEntity, player); + return; + } + } + unacceptedQuestIndicator(npcEntity, player); + } + + private void unacceptedQuestIndicator(NPCEntity npcEntity, Player player) { + generateIndicator(npcEntity, player, ChatColor.YELLOW + "" + ChatColor.BOLD + "!", + ChatColor.GOLD + "" + ChatColor.BOLD + "!"); + } + + private void acceptedQuestIndicator(NPCEntity npcEntity, Player player) { + generateIndicator(npcEntity, player, ChatColor.GRAY + "" + ChatColor.BOLD + "?", + ChatColor.DARK_GRAY + "" + ChatColor.BOLD + "?"); + } + + private void completedQuestIndicator(NPCEntity npcEntity, Player player) { + generateIndicator(npcEntity, player, ChatColor.YELLOW + "" + ChatColor.BOLD + "?", + ChatColor.GOLD + "" + ChatColor.BOLD + "?"); + } + + private void generateIndicator(NPCEntity npcEntity, Player player, String messageUp, String messageDown) { + Location newLocation = npcEntity.getVillager().getEyeLocation().clone() + .add(player.getLocation().clone().subtract(npcEntity.getVillager().getLocation()).toVector().normalize().multiply(0.5)) + .add(new Vector(0, -0.1, 0)); + ArmorStand visualArmorStand = VisualArmorStand.VisualArmorStand(newLocation, messageUp); + AtomicInteger counter = new AtomicInteger(); + AtomicBoolean up = new AtomicBoolean(true); + Bukkit.getScheduler().runTaskTimer(MetadataHandler.PLUGIN, task -> { + if (!player.isValid() || + npcEntity.getVillager() == null || + !npcEntity.getVillager().isValid() || + !npcEntity.getVillager().getWorld().equals(player.getWorld()) || + npcEntity.getVillager().getLocation().distance(player.getLocation()) > npcEntity.getNPCsConfigFields().getActivationRadius()) { + task.cancel(); + EntityTracker.unregister(visualArmorStand, RemovalReason.EFFECT_TIMEOUT); + return; + } + + counter.getAndIncrement(); + + if (counter.get() % 20 == 0) { + up.getAndSet(!up.get()); + if (up.get()) + visualArmorStand.setCustomName(messageUp); + else + visualArmorStand.setCustomName(messageDown); + } + + visualArmorStand.teleport(visualArmorStand.getLocation().clone().add(new Vector(0, up.get() ? 0.01 : -0.01, 0))); + + }, 0L, 1L); + } + + @EventHandler + public void onInventoryClose(InventoryCloseEvent event) { + if (event.getView().getTitle().length() > 0) + for (Entity entity : event.getPlayer().getNearbyEntities(5, 5, 5)) + if (EntityTracker.isNPCEntity(entity)) + EntityTracker.getNPCEntity(entity).sayFarewell((Player) event.getPlayer()); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/ondeathcommands/OnDeathCommands.java b/src/main/java/com/magmaguy/elitemobs/ondeathcommands/OnDeathCommands.java new file mode 100644 index 000000000..6c77245cd --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/ondeathcommands/OnDeathCommands.java @@ -0,0 +1,144 @@ +package com.magmaguy.elitemobs.ondeathcommands; + +import com.magmaguy.elitemobs.api.EliteMobDeathEvent; +import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.utils.WarningMessage; +import lombok.Getter; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; + +import java.util.*; +import java.util.concurrent.ThreadLocalRandom; + +public class OnDeathCommands implements Listener { + + public static void parseConsoleCommand(List configStrings, EliteMobDeathEvent event) { + Player topDamager = null; + Player secondDamager = null; + Player thirdDamager = null; + HashMap sortedMap = sortByComparator(event.getEliteEntity().getDamagers(), false); + Iterator sortedMapIterator = sortedMap.keySet().iterator(); + for (int i = 1; i < 4; i++) { + if (i > sortedMap.size()) + break; + Player nextPlayer = sortedMapIterator.next(); + switch (i) { + case 1: + topDamager = nextPlayer; + break; + case 2: + secondDamager = nextPlayer; + break; + case 3: + thirdDamager = nextPlayer; + break; + } + } + for (String string : configStrings) { + double chance = 1; + string = parseCommonCommandStrings(string, event.getEliteEntity()); + if (string.contains("$damager1name")) { + if (topDamager != null) + string = string.replace("$damager1name", topDamager.getName()); + else + string = ""; + } + if (string.contains("$damager2name")) { + if (secondDamager != null) + string = string.replace("$damager2name", secondDamager.getName()); + else + string = ""; + } + if (string.contains("$damager3name")) { + if (thirdDamager != null) + string = string.replace("$damager3name", thirdDamager.getName()); + else + string = ""; + } + RunChance runChance = new RunChance(string); + string = runChance.getString(); + chance = runChance.getChance(); + if (string.contains("$players")) { + if (event.getEliteEntity().hasDamagers()) + for (Player player : event.getEliteEntity().getDamagers().keySet()) + if (chance == 1 || ThreadLocalRandom.current().nextDouble() < chance) + runConsoleCommand(string.replace("$players", player.getName())); + else return; + } else if (chance == 1 || ThreadLocalRandom.current().nextDouble() < chance) runConsoleCommand(string); + } + } + + public static String parseCommonCommandStrings(String string, EliteEntity eliteEntity) { + if (string.contains("$level")) + string = string.replace("$level", eliteEntity.getLevel() + ""); + if (string.contains("$name")) + string = string.replace("$name", eliteEntity.getName()); + if (eliteEntity.getLocation() != null) { + if (string.contains("$locationWorldName") && eliteEntity.getLocation() != null) + string = string.replace("$locationWorldName", Objects.requireNonNull(eliteEntity.getLocation().getWorld()).getName()); + if (string.contains("$locationX")) + string = string.replace("$locationX", eliteEntity.getLocation().getX() + ""); + if (string.contains("$locationY")) + string = string.replace("$locationY", eliteEntity.getLocation().getY() + ""); + if (string.contains("$locationZ")) + string = string.replace("$locationZ", eliteEntity.getLocation().getZ() + ""); + } + return string; + } + + private static HashMap sortByComparator(Map unsortMap, final boolean order) { + + List> list = new LinkedList<>(unsortMap.entrySet()); + + // Sorting the list based on values + list.sort((o1, o2) -> { + if (order) + return o1.getValue().compareTo(o2.getValue()); + else + return o2.getValue().compareTo(o1.getValue()); + }); + + // Maintaining insertion order with the help of LinkedList + HashMap sortedMap = new LinkedHashMap<>(); + for (Map.Entry entry : list) + sortedMap.put(entry.getKey(), entry.getValue()); + + return sortedMap; + } + + private static void runConsoleCommand(String command) { + Bukkit.dispatchCommand(Bukkit.getServer().getConsoleSender(), command); + } + + @EventHandler + public void onEliteMobDeath(EliteMobDeathEvent event) { + if (MobCombatSettingsConfig.getCommandsOnDeath().isEmpty()) return; + parseConsoleCommand(MobCombatSettingsConfig.getCommandsOnDeath(), event); + } + + public static class RunChance { + @Getter + private double chance = 1; + @Getter + private String string; + + public RunChance(String commandString) { + this.string = commandString; + if (string.contains("$chance=")) { + try { + String chanceString = string.split("\\$chance=")[1]; + chanceString = chanceString.split("\\$")[0]; + chance = Double.parseDouble(chanceString); + String fullString = "$chance=" + chanceString + "$"; + string = string.replace(fullString, ""); + } catch (Exception ex) { + new WarningMessage("Failed to get the chance value of the command " + string + " . The correct format should be $chance=X.Y$", true); + } + } + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/playerdata/ElitePlayerInventory.java b/src/main/java/com/magmaguy/elitemobs/playerdata/ElitePlayerInventory.java new file mode 100644 index 000000000..4db784d0d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/playerdata/ElitePlayerInventory.java @@ -0,0 +1,210 @@ +package com.magmaguy.elitemobs.playerdata; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.items.MobTierCalculator; +import com.magmaguy.elitemobs.items.potioneffects.ElitePotionEffect; +import org.bukkit.Bukkit; +import org.bukkit.GameMode; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerLoginEvent; +import org.bukkit.event.player.PlayerQuitEvent; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.UUID; + +public class ElitePlayerInventory { + + public static HashMap playerInventories = new HashMap<>(); + public final PlayerItem helmet, chestplate, leggings, boots, mainhand, offhand; + private final Player player; + private boolean getArmorCooldown = false; + private boolean getWeaponCooldown = false; + + /** + * Object of the player's inventory for EliteMobs. + * For performance reasons, values are cached and updated only when strictly necessary. + * Stores already parsed logic for weapon and armor tiers, as well as potion effects associated to weapons. + * + * @param player Inventory th + */ + public ElitePlayerInventory(Player player) { + this.player = player; + this.helmet = new PlayerItem(player.getInventory().getHelmet(), PlayerItem.EquipmentSlot.HELMET, player); + this.chestplate = new PlayerItem(player.getInventory().getChestplate(), PlayerItem.EquipmentSlot.CHESTPLATE, player); + this.leggings = new PlayerItem(player.getInventory().getLeggings(), PlayerItem.EquipmentSlot.LEGGINGS, player); + this.boots = new PlayerItem(player.getInventory().getBoots(), PlayerItem.EquipmentSlot.BOOTS, player); + this.mainhand = new PlayerItem(player.getInventory().getItemInMainHand(), PlayerItem.EquipmentSlot.MAINHAND, player); + this.offhand = new PlayerItem(player.getInventory().getItemInOffHand(), PlayerItem.EquipmentSlot.OFFHAND, player); + playerInventories.put(player.getUniqueId(), this); + } + + public static void initialize() { + for (Player player : Bukkit.getOnlinePlayers()) + playerInventories.put(player.getUniqueId(), new ElitePlayerInventory(player)); + } + + /** + * An average of all equipped armor tiers! + * + * @return Average of all armor tiers + */ + public double getArmorTier(boolean update) { + if (!armorCheck()) update = false; + return (helmet.getTier(player.getInventory().getHelmet(), update) + + chestplate.getTier(player.getInventory().getChestplate(), update) + + leggings.getTier(player.getInventory().getLeggings(), update) + + boots.getTier(player.getInventory().getBoots(), update)) + / 4D; + } + + private boolean armorCheck() { + if (getArmorCooldown) return false; + getArmorCooldown = true; + Bukkit.getScheduler().runTaskLater(MetadataHandler.PLUGIN, () -> getArmorCooldown = false, 1); + return true; + } + + /** + * Tier of the weapon in the main hand. + * + * @return Tier of the weapon in the main hand. + */ + public int getWeaponTier(boolean update) { + if (!weaponCheck()) update = false; + return mainhand.getTier(player.getInventory().getItemInMainHand(), update); + } + + private boolean weaponCheck() { + if (getWeaponCooldown) return false; + getWeaponCooldown = true; + Bukkit.getScheduler().runTaskLater(MetadataHandler.PLUGIN, () -> getWeaponCooldown = false, 1); + return true; + } + + public int getFullPlayerTier(boolean update) { + return (int) ((helmet.getTier(player.getInventory().getHelmet(), update) + + chestplate.getTier(player.getInventory().getChestplate(), update) + + leggings.getTier(player.getInventory().getLeggings(), update) + + boots.getTier(player.getInventory().getBoots(), update) + + mainhand.getTier(player.getInventory().getItemInMainHand(), update)) + / 5D); + } + + public int getNaturalMobSpawnLevel(boolean update) { + if (player.getGameMode().equals(GameMode.SPECTATOR)) return 0; + return (int) ((helmet.getTier(player.getInventory().getHelmet(), update) + + chestplate.getTier(player.getInventory().getChestplate(), update) + + leggings.getTier(player.getInventory().getLeggings(), update) + + boots.getTier(player.getInventory().getBoots(), update) + + mainhand.getTier(player.getInventory().getItemInMainHand(), update)) + / 5D * MobTierCalculator.PER_TIER_LEVEL_INCREASE); + } + + /** + * Returns a list of all continuous potion effects in armor/weapons, may contain duplicate effects. + * + * @return ArrayList of all continuous potion effects. + */ + public ArrayList getContinuousPotionEffects(boolean update) { + ArrayList elitePotionEffects = new ArrayList<>(); + if (player.getInventory().getHelmet() != null) + elitePotionEffects.addAll(helmet.getContinuousPotionEffects(player.getInventory().getHelmet(), update)); + if (player.getInventory().getChestplate() != null) + elitePotionEffects.addAll(chestplate.getContinuousPotionEffects(player.getInventory().getChestplate(), update)); + if (player.getInventory().getLeggings() != null) + elitePotionEffects.addAll(leggings.getContinuousPotionEffects(player.getInventory().getLeggings(), update)); + if (player.getInventory().getBoots() != null) + elitePotionEffects.addAll(boots.getContinuousPotionEffects(player.getInventory().getBoots(), update)); + elitePotionEffects.addAll(mainhand.getContinuousPotionEffects(player.getInventory().getItemInMainHand(), update)); + elitePotionEffects.addAll(offhand.getContinuousPotionEffects(player.getInventory().getItemInOffHand(), update)); + return elitePotionEffects; + } + + /** + * Returns a list of all on hit potion effects in armor/weapons, may contain duplicates. + * + * @return ArrayList of all onHit potion effects. + */ + public ArrayList getOnHitPotionEffects(boolean update) { + ArrayList elitePotionEffects = new ArrayList<>(); + elitePotionEffects.addAll(helmet.getOnHitPotionEffects(player.getInventory().getHelmet(), update)); + elitePotionEffects.addAll(chestplate.getOnHitPotionEffects(player.getInventory().getChestplate(), update)); + elitePotionEffects.addAll(leggings.getOnHitPotionEffects(player.getInventory().getLeggings(), update)); + elitePotionEffects.addAll(boots.getOnHitPotionEffects(player.getInventory().getBoots(), update)); + elitePotionEffects.addAll(mainhand.getOnHitPotionEffects(player.getInventory().getItemInMainHand(), update)); + elitePotionEffects.addAll(offhand.getOnHitPotionEffects(player.getInventory().getItemInOffHand(), update)); + return elitePotionEffects; + } + + public double getCritChance(boolean update) { + return mainhand.getCritChance(player.getInventory().getItemInMainHand(), update); + } + + public double getLightningChance(boolean update) { + return mainhand.getLightningChance(player.getInventory().getItemInMainHand(), update); + } + + public double getHunterChance(boolean update) { + return helmet.getHunterChance(player.getInventory().getHelmet(), update) + + chestplate.getHunterChance(player.getInventory().getChestplate(), update) + + leggings.getHunterChance(player.getInventory().getLeggings(), update) + + boots.getHunterChance(player.getInventory().getBoots(), update); + } + + public double getPlasmaBootsLevel(boolean update) { + return boots.getPlasmaBootsLevel(player.getInventory().getBoots(), update); + } + + public double getEarthquakeLevel(boolean update) { + return helmet.getEarthquakeLevel(player.getInventory().getHelmet(), update) + + chestplate.getEarthquakeLevel(player.getInventory().getChestplate(), update) + + leggings.getEarthquakeLevel(player.getInventory().getLeggings(), update) + + boots.getEarthquakeLevel(player.getInventory().getBoots(), update); + } + + /** + * Outputs the base damage of the player given the current gear. Does not take secondary enchantments into account, + * such as Smite + * + * @return Base damage value + */ + public double baseDamage() { + if (getWeaponTier(true) == 0) + return 1; + return getWeaponTier(false); + } + + /** + * Outputs the base damage reduction given the current gear. Does not take secondary enchantments into accounts, + * such as Blast Protection + * + * @return Base damage reduction value + */ + public double baseDamageReduction() { + return getArmorTier(true); + } + + /** + * Outputs the total level of the thorns enchantment across all armor + * + * @return Total thorns enchantment level + */ + public int getThornsLevel() { + return helmet.thornsLevel + chestplate.thornsLevel + leggings.thornsLevel + boots.thornsLevel; + } + + public static class ElitePlayerInventoryEvents implements Listener { + @EventHandler + public void onPlayerLogin(PlayerLoginEvent event) { + playerInventories.put(event.getPlayer().getUniqueId(), new ElitePlayerInventory(event.getPlayer())); + } + + @EventHandler + public void onPlayerLogout(PlayerQuitEvent event) { + playerInventories.remove(event.getPlayer().getUniqueId()); + } + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/playerdata/PlayerData.java b/src/main/java/com/magmaguy/elitemobs/playerdata/PlayerData.java deleted file mode 100644 index aa966dc26..000000000 --- a/src/main/java/com/magmaguy/elitemobs/playerdata/PlayerData.java +++ /dev/null @@ -1,181 +0,0 @@ -package com.magmaguy.elitemobs.playerdata; - -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.config.*; -import org.bukkit.scheduler.BukkitRunnable; - -import java.util.HashMap; -import java.util.UUID; - -public class PlayerData { - - public static HashMap playerDisplayName = new HashMap<>(); - public static HashMap playerCurrency = new HashMap<>(); - public static HashMap playerMaxGuildRank = new HashMap<>(); - public static HashMap playerSelectedGuildRank = new HashMap<>(); - - public static void initializePlayerData() { - - initializeDisplayName(); - initializeCurrency(); - initializeSelectedGuildRank(); - initializeMaxGuildRank(); - - } - - public static void clearPlayerData() { - - playerDisplayName.clear(); - playerCurrency.clear(); - playerMaxGuildRank.clear(); - playerSelectedGuildRank.clear(); - - } - - public static int databaseSyncTaskID = 0; - public static boolean playerCacheChanged = false; - public static boolean playerCurrencyChanged = false; - public static boolean playerSelectedGuildRankChanged = false; - public static boolean playerMaxGuildRankChanged = false; - - public static void synchronizeDatabases() { - - databaseSyncTaskID = new BukkitRunnable() { - - @Override - public void run() { - - saveDatabases(); - - } - - }.runTaskTimerAsynchronously(MetadataHandler.PLUGIN, 20 * 60, 20 * 60).getTaskId(); - - } - - public static void saveDatabases() { - - if (playerCacheChanged) - saveDisplayName(); - if (playerCurrencyChanged) - saveCurrency(); - if (playerSelectedGuildRankChanged) - saveSelectedGuildRank(); - if (playerMaxGuildRankChanged) - saveMaxGuildRank(); - - } - - private static void initializeDisplayName() { - - PlayerCacheData playerCacheData = new PlayerCacheData(); - - for (String string : playerCacheData.configuration.getKeys(true)) { - - playerDisplayName.put(UUID.fromString(string), ConfigValues.playerCacheConfig.getString(string)); - - } - - } - - private static void saveDisplayName() { - - PlayerCacheData playerCacheData = new PlayerCacheData(); - - for (UUID uuid : playerDisplayName.keySet()) { - - playerCacheData.configuration.set(uuid.toString(), playerDisplayName.get(uuid)); - - } - - playerCacheData.customConfigLoader.saveCustomConfig(PlayerCacheData.CONFIG_NAME, true); - - playerCacheChanged = false; - - } - - private static void initializeCurrency() { - - PlayerMoneyData playerMoneyData = new PlayerMoneyData(); - - for (String string : playerMoneyData.configuration.getKeys(true)) { - - playerCurrency.put(UUID.fromString(string), ConfigValues.playerMoneyData.getDouble(string)); - - } - - } - - private static void saveCurrency() { - - PlayerMoneyData playerMoneyData = new PlayerMoneyData(); - - for (UUID uuid : playerCurrency.keySet()) { - - playerMoneyData.configuration.set(uuid.toString(), playerCurrency.get(uuid)); - - } - - playerMoneyData.customConfigLoader.saveCustomConfig(PlayerMoneyData.CONFIG_NAME, true); - - playerCurrencyChanged = false; - - } - - private static void initializeMaxGuildRank() { - - PlayerMaxGuildRank playerMaxGuildRankClass = new PlayerMaxGuildRank(); - - for (String string : playerMaxGuildRankClass.configuration.getKeys(true)){ - - playerMaxGuildRank.put(UUID.fromString(string), playerMaxGuildRankClass.configuration.getInt(string)); - - } - - } - - private static void saveMaxGuildRank() { - - PlayerMaxGuildRank playerMaxGuildRankClass = new PlayerMaxGuildRank(); - - for (UUID uuid : playerMaxGuildRank.keySet()) { - - playerMaxGuildRankClass.configuration.set(uuid.toString(), playerMaxGuildRank.get(uuid)); - - } - - playerMaxGuildRankClass.customConfigLoader.saveCustomConfig(PlayerMaxGuildRank.CONFIG_NAME, true); - - playerMaxGuildRankChanged = false; - - } - - private static void initializeSelectedGuildRank() { - - PlayerGuildRank playerGuildRankClass = new PlayerGuildRank(); - - for (String string : playerGuildRankClass.configuration.getKeys(true)){ - - playerSelectedGuildRank.put(UUID.fromString(string), playerGuildRankClass.configuration.getInt(string)); - - } - - } - - private static void saveSelectedGuildRank() { - - PlayerGuildRank playerGuildRankClass = new PlayerGuildRank(); - - for (UUID uuid : playerSelectedGuildRank.keySet()) { - - playerGuildRankClass.configuration.set(uuid.toString(), playerSelectedGuildRank.get(uuid)); - - } - - playerGuildRankClass.customConfigLoader.saveCustomConfig(PlayerGuildRank.CONFIG_NAME, true); - - playerSelectedGuildRankChanged = false; - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/playerdata/PlayerItem.java b/src/main/java/com/magmaguy/elitemobs/playerdata/PlayerItem.java new file mode 100644 index 000000000..5173ec5bf --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/playerdata/PlayerItem.java @@ -0,0 +1,193 @@ +package com.magmaguy.elitemobs.playerdata; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.config.enchantments.EnchantmentsConfig; +import com.magmaguy.elitemobs.items.ItemTagger; +import com.magmaguy.elitemobs.items.ItemTierFinder; +import com.magmaguy.elitemobs.items.customenchantments.*; +import com.magmaguy.elitemobs.items.potioneffects.ElitePotionEffect; +import org.bukkit.Material; +import org.bukkit.NamespacedKey; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.util.ArrayList; + +public class PlayerItem { + + public EquipmentSlot equipmentSlot; + public Player player; + public ItemStack itemStack = null; + public int itemTier = 0; + public ArrayList continuousPotionEffects = new ArrayList<>(); + public ArrayList onHitPotionEffects = new ArrayList<>(); + public int damageArthropodsLevel = 0; + public int damageUndeadLevel = 0; + public int thornsLevel = 0; + private double plasmaBootsLevel = 0; + private double critChance = 0; + private double hunterChance = 0; + private double lightningChance = 0; + private double earthquakeLevel = 0; + + /** + * Stores an instance of the custom EliteMobs values of what a player is wearing. This is used to reduce the amount + * of checks done by EliteMobs during combat and for passive potion effect applications. It should (largely) only update + * when necessary. + * + * @param itemStack ItemStack in the equipment slot. Does not update. + * @param equipmentSlot Player's equipment slot. This is used to quickly access weapons and armor for the combat system. Updates when the ItemStack changes. + * @param player Player associated to the gear. Does not update. + */ + public PlayerItem(ItemStack itemStack, EquipmentSlot equipmentSlot, Player player) { + this.equipmentSlot = equipmentSlot; //equipment slot never updates + this.player = player; + fullUpdate(itemStack); + } + + private boolean fullUpdate(ItemStack itemStack) { + + //case when both are null + if (itemStack == null && this.itemStack == null) + return false; + + //case when it became null + if (itemStack == null) + return fillNullItem(); + + //case when it's the same item as before - best performance + if (itemStack.isSimilar(this.itemStack)) + return false; + + if (EnchantmentsConfig.getEnchantment(SoulbindEnchantment.key + ".yml").isEnabled()) + if (!SoulbindEnchantment.isValidSoulbindUser(itemStack.getItemMeta(), player)) { + player.getWorld().dropItem(player.getLocation(), itemStack); + itemStack.setAmount(0); + itemStack = new ItemStack(Material.AIR); + } + + //case when the item changed during runtime to another valid ItemStack + this.itemStack = itemStack; + if (equipmentSlot.equals(EquipmentSlot.MAINHAND)) + this.itemTier = ItemTierFinder.mainHandCombatParser(itemStack); + else + this.itemTier = ItemTierFinder.findBattleTier(itemStack); + + this.continuousPotionEffects = ItemTagger.getPotionEffects(itemStack.getItemMeta(), ItemTagger.continuousPotionEffectKey); + this.onHitPotionEffects = ItemTagger.getPotionEffects(itemStack.getItemMeta(), ItemTagger.onHitPotionEffectKey); + + if (equipmentSlot.equals(EquipmentSlot.MAINHAND)) { + this.damageArthropodsLevel = ItemTagger.getEnchantment(itemStack.getItemMeta(), Enchantment.DAMAGE_ARTHROPODS.getKey()); + this.damageUndeadLevel = ItemTagger.getEnchantment(itemStack.getItemMeta(), Enchantment.DAMAGE_UNDEAD.getKey()); + this.critChance = ItemTagger.getEnchantment(itemStack.getItemMeta(), new NamespacedKey(MetadataHandler.PLUGIN, CriticalStrikesEnchantment.key)) / 10D; + this.lightningChance = Math.pow(ItemTagger.getEnchantment(itemStack.getItemMeta(), new NamespacedKey(MetadataHandler.PLUGIN, LightningEnchantment.key)), 2) / 1000D; + } + + if (equipmentSlot.equals(EquipmentSlot.BOOTS)) { + this.plasmaBootsLevel = ItemTagger.getEnchantment(itemStack.getItemMeta(), new NamespacedKey(MetadataHandler.PLUGIN, PlasmaBootsEnchantment.key)); + } + + this.hunterChance = ItemTagger.getEnchantment(itemStack.getItemMeta(), new NamespacedKey(MetadataHandler.PLUGIN, HunterEnchantment.key)) * EnchantmentsConfig.getEnchantment("hunter.yml").getFileConfiguration().getDouble("hunterSpawnBonus"); + + this.earthquakeLevel = ItemTagger.getEnchantment(itemStack.getItemMeta(), new NamespacedKey(MetadataHandler.PLUGIN, EarthquakeEnchantment.key)); + + checkArmorSpecificFeatures(); + + return true; + + } + + private boolean fillNullItem() { + itemTier = 0; + continuousPotionEffects = new ArrayList<>(); + onHitPotionEffects = new ArrayList<>(); + damageArthropodsLevel = 0; + damageUndeadLevel = 0; + thornsLevel = 0; + plasmaBootsLevel = 0; + critChance = 0; + hunterChance = 0; + lightningChance = 0; + return true; + } + + private void checkArmorSpecificFeatures() { + if (!(equipmentSlot.equals(EquipmentSlot.HELMET) || + equipmentSlot.equals(EquipmentSlot.CHESTPLATE) || + equipmentSlot.equals(EquipmentSlot.LEGGINGS) || + equipmentSlot.equals(EquipmentSlot.BOOTS))) return; + this.thornsLevel = ItemTagger.getEnchantment(itemStack.getItemMeta(), Enchantment.THORNS.getKey()); + } + + public int getTier(ItemStack itemStack, boolean update) { + if (update) + fullUpdate(itemStack); + return this.itemTier; + } + + public ArrayList getContinuousPotionEffects(ItemStack itemStack, boolean update) { + if (update) + fullUpdate(itemStack); + return this.continuousPotionEffects; + } + + public ArrayList getOnHitPotionEffects(ItemStack itemStack, boolean update) { + if (update) + fullUpdate(itemStack); + return this.onHitPotionEffects; + } + + public int getDamageArthropodsLevel(ItemStack itemStack, boolean update) { + if (update) + fullUpdate(itemStack); + return this.damageArthropodsLevel; + } + + public int getDamageUndeadLevel(ItemStack itemStack, boolean update) { + if (update) + fullUpdate(itemStack); + return this.damageUndeadLevel; + } + + public double getCritChance(ItemStack itemStack, boolean update) { + if (update) + fullUpdate(itemStack); + return this.critChance; + } + + public double getHunterChance(ItemStack itemStack, boolean update) { + if (update) + fullUpdate(itemStack); + return this.hunterChance; + } + + public double getLightningChance(ItemStack itemStack, boolean update) { + if (update) + fullUpdate(itemStack); + return this.lightningChance; + } + + public double getPlasmaBootsLevel(ItemStack itemStack, boolean update) { + if (update) + fullUpdate(itemStack); + return this.plasmaBootsLevel; + } + + public double getEarthquakeLevel(ItemStack itemStack, boolean update) { + if (update) + fullUpdate(itemStack); + return this.earthquakeLevel; + } + + + public enum EquipmentSlot { + HELMET, + CHESTPLATE, + LEGGINGS, + BOOTS, + MAINHAND, + OFFHAND + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/playerdata/PlayerStatsTracker.java b/src/main/java/com/magmaguy/elitemobs/playerdata/PlayerStatsTracker.java new file mode 100644 index 000000000..58db5a158 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/playerdata/PlayerStatsTracker.java @@ -0,0 +1,29 @@ +package com.magmaguy.elitemobs.playerdata; + +import com.magmaguy.elitemobs.api.EliteMobDeathEvent; +import com.magmaguy.elitemobs.playerdata.database.PlayerData; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; + +public class PlayerStatsTracker implements Listener { + + public static void registerPlayerDeath(Player player) { + PlayerData.incrementDeaths(player.getUniqueId()); + PlayerData.decrementScore(player.getUniqueId()); + } + + @EventHandler + public void onEliteDeath(EliteMobDeathEvent event) { + if (event.getEliteEntity().isTriggeredAntiExploit()) return; + if (event.getEliteEntity().getDamagers().isEmpty()) return; + //todo : optimize + for (Player player : event.getEliteEntity().getDamagers().keySet()) { + if (player.hasMetadata("NPC")) continue; + if (!PlayerData.isInMemory(player.getUniqueId())) continue; + PlayerData.incrementKills(player.getUniqueId()); + PlayerData.setHighestLevelKilled(player.getUniqueId(), event.getEliteEntity().getLevel()); + PlayerData.incrementScore(player.getUniqueId(), event.getEliteEntity().getLevel()); + } + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/playerdata/database/GenerateDatabase.java b/src/main/java/com/magmaguy/elitemobs/playerdata/database/GenerateDatabase.java new file mode 100644 index 000000000..902c4464f --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/playerdata/database/GenerateDatabase.java @@ -0,0 +1,74 @@ +package com.magmaguy.elitemobs.playerdata.database; + +import com.magmaguy.elitemobs.utils.InfoMessage; +import com.magmaguy.elitemobs.utils.WarningMessage; + +import java.sql.DatabaseMetaData; +import java.sql.ResultSet; +import java.sql.Statement; + +public class GenerateDatabase { + private GenerateDatabase() { + } + + public static void generate() throws Exception { + Statement statement = PlayerData.getConnection().createStatement(); + String sql = "CREATE TABLE IF NOT EXISTS " + PlayerData.getPLAYER_DATA_TABLE_NAME() + + "(PlayerUUID TEXT PRIMARY KEY NOT NULL);"; + statement.executeUpdate(sql); + statement.close(); + addEntryIfEmpty("DisplayName", ColumnValues.TEXT); + addEntryIfEmpty("Currency", ColumnValues.REAL); + addEntryIfEmpty("GuildPrestigeLevel", ColumnValues.INT); + addEntryIfEmpty("GuildMaxLevel", ColumnValues.INT); + addEntryIfEmpty("GuildActiveLevel", ColumnValues.INT); + addEntryIfEmpty("QuestStatus", ColumnValues.BLOB); + addEntryIfEmpty("Score", ColumnValues.INT); + addEntryIfEmpty("Kills", ColumnValues.INT); + addEntryIfEmpty("HighestLevelKilled", ColumnValues.INT); + addEntryIfEmpty("Deaths", ColumnValues.INT); + addEntryIfEmpty("QuestsCompleted", ColumnValues.INT); + addEntryIfEmpty("PlayerQuestCooldowns", ColumnValues.BLOB); + addEntryIfEmpty("BackTeleportLocation", ColumnValues.TEXT); + addEntryIfEmpty("UseBookMenus", ColumnValues.BOOLEAN); + addEntryIfEmpty("DismissEMStatusScreenMessage", ColumnValues.BOOLEAN); + } + + private static void addEntryIfEmpty(String columnName, ColumnValues columnValues) { + try { + DatabaseMetaData metaData = PlayerData.getConnection().getMetaData(); + ResultSet resultSet = metaData.getColumns(null, null, PlayerData.getPLAYER_DATA_TABLE_NAME(), columnName); + if (resultSet.next()) { + //Developer.message("Database already had " + columnName); + } else { + new InfoMessage("Adding new database column " + columnName); + addColumn(columnName, columnValues); + } + resultSet.close(); + } catch (Exception ex) { + new WarningMessage("Could not process column " + columnName); + ex.printStackTrace(); + } + } + + private static void addColumn(String columnName, ColumnValues type) { + try { + Statement statement = PlayerData.getConnection().createStatement(); + String sql = "ALTER TABLE " + PlayerData.getPLAYER_DATA_TABLE_NAME() + " ADD " + columnName + " " + type.toString(); + statement.executeUpdate(sql); + statement.close(); + } catch (Exception ex) { + new WarningMessage("Failed to insert new column " + columnName); + ex.printStackTrace(); + } + } + + private enum ColumnValues { + BLOB, + INT, + TEXT, + REAL, + BOOLEAN + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/playerdata/database/PlayerData.java b/src/main/java/com/magmaguy/elitemobs/playerdata/database/PlayerData.java new file mode 100644 index 000000000..a719862d8 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/playerdata/database/PlayerData.java @@ -0,0 +1,708 @@ +package com.magmaguy.elitemobs.playerdata.database; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.instanced.MatchInstance; +import com.magmaguy.elitemobs.quests.CustomQuest; +import com.magmaguy.elitemobs.quests.Quest; +import com.magmaguy.elitemobs.quests.playercooldowns.PlayerQuestCooldowns; +import com.magmaguy.elitemobs.utils.ConfigurationLocation; +import com.magmaguy.elitemobs.utils.InfoMessage; +import com.magmaguy.elitemobs.utils.ObjectSerializer; +import com.magmaguy.elitemobs.utils.WarningMessage; +import lombok.Getter; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.permissions.PermissionAttachment; +import org.bukkit.scheduler.BukkitRunnable; + +import javax.annotation.Nullable; +import java.io.File; +import java.sql.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.UUID; + +public class PlayerData { + + @Getter + private static final String DATABASE_NAME = "player_data.db"; + @Getter + private static final String PLAYER_DATA_TABLE_NAME = "PlayerData"; + private static final HashMap playerDataHashMap = new HashMap<>(); + private static Connection connection = null; + private double currency; + private int guildPrestigeLevel; + private int maxGuildLevel; + private int activeGuildLevel; + private int score; + private int kills; + private int highestLevelKilled; + private int deaths; + private int questsCompleted; + private List quests = new ArrayList<>(); + private PlayerQuestCooldowns playerQuestCooldowns = null; + private Location backTeleportLocation; + private boolean useBookMenus; + private boolean dismissEMStatusScreenMessage; + //This is currently not stored in the database, time will tell if it is necessary to do so + private MatchInstance matchInstance = null; + + /** + * Called when a player logs in, storing their data in memory + * + * @param uuid + */ + public PlayerData(UUID uuid) { + Player player = Bukkit.getPlayer(uuid); + if (player == null) { + new WarningMessage("EliteMobs did not initialize player data for uuid " + uuid + " because Minecraft does not recognize this as a valid player!"); + return; + } + PermissionAttachment permissionAttachment = player.addAttachment(MetadataHandler.PLUGIN); + permissionAttachment.setPermission("elitequest.*", false); + new BukkitRunnable() { + @Override + public void run() { + Statement statement = null; + try { + statement = getConnection().createStatement(); + ResultSet resultSet = statement.executeQuery("SELECT * FROM " + PLAYER_DATA_TABLE_NAME + " WHERE PlayerUUID = '" + uuid.toString() + "';"); + //case for there being data to read + if (resultSet.next()) { + readExistingData(statement, uuid, resultSet); + } else { + //case for new data to be written + writeNewData(statement, uuid); + } + resultSet.close(); + statement.close(); + + } catch (Exception e) { + if (statement != null) { + try { + statement.close(); + } catch (SQLException throwables) { + new WarningMessage("Failed to close statement after failing player data creation!"); + throwables.printStackTrace(); + } + } + new WarningMessage("Something went wrong while generating a new player entry. This is bad! Tell the dev."); + new WarningMessage(e.getClass().getName() + ": " + e.getMessage()); + } + } + }.runTaskAsynchronously(MetadataHandler.PLUGIN); + } + + public static PlayerData getPlayerData(UUID player) { + return playerDataHashMap.get(player); + } + + public static void updateQuestStatus(UUID uuid) { + List playerQuests = getQuests(uuid); + try { + setDatabaseValue(uuid, "QuestStatus", ObjectSerializer.toString((ArrayList) playerQuests)); + if (playerDataHashMap.containsKey(uuid)) + playerDataHashMap.get(uuid).quests = playerQuests; + } catch (Exception ex) { + new WarningMessage("Failed to serialize player quest data!"); + ex.printStackTrace(); + } + } + + public static void clearPlayerData(UUID uuid) { + playerDataHashMap.remove(uuid); + } + + public static boolean isInMemory(Player player) { + return playerDataHashMap.containsKey(player.getUniqueId()); + } + + public static boolean isInMemory(UUID uuid) { + return playerDataHashMap.containsKey(uuid); + } + + public static String getDisplayName(UUID uuid) { + if (!isInMemory(uuid)) + return getDatabaseString(uuid, "DisplayName"); + + return Bukkit.getPlayer(uuid).getCustomName(); + } + + public static void setDisplayName(UUID uuid, String displayName) { + setDatabaseValue(uuid, "DisplayName", displayName); + } + + public static double getCurrency(UUID uuid) { + if (!isInMemory(uuid)) + return getDatabaseDouble(uuid, "Currency"); + return playerDataHashMap.get(uuid).currency; + } + + public static double getCurrency(UUID uuid, boolean databaseAccess) { + if (!isInMemory(uuid)) + if (databaseAccess) + return getDatabaseDouble(uuid, "Currency"); + else + //default fallback value for when PAPI suddenly decides to start querying the database thousands of times per second + return 0; + return playerDataHashMap.get(uuid).currency; + } + + public static void setCurrency(UUID uuid, double currency) { + setDatabaseValue(uuid, "Currency", currency); + if (playerDataHashMap.containsKey(uuid)) + playerDataHashMap.get(uuid).currency = currency; + } + + public static int getGuildPrestigeLevel(UUID uuid) { + if (!isInMemory(uuid)) + return getDatabaseInteger(uuid, "GuildPrestigeLevel"); + return playerDataHashMap.get(uuid).guildPrestigeLevel; + } + + public static int getGuildPrestigeLevel(UUID uuid, boolean databaseAccess) { + if (!isInMemory(uuid)) + if (databaseAccess) + return getDatabaseInteger(uuid, "GuildPrestigeLevel"); + else + //default fallback value for when PAPI suddenly decides to start querying the database thousands of times per second + return 0; + return playerDataHashMap.get(uuid).guildPrestigeLevel; + } + + public static void setGuildPrestigeLevel(UUID uuid, int newPrestigeLevel) { + setDatabaseValue(uuid, "GuildPrestigeLevel", newPrestigeLevel); + if (playerDataHashMap.containsKey(uuid)) + playerDataHashMap.get(uuid).guildPrestigeLevel = newPrestigeLevel; + } + + public static int getMaxGuildLevel(UUID uuid) { + if (!isInMemory(uuid)) + return getDatabaseInteger(uuid, "GuildMaxLevel"); + + return playerDataHashMap.get(uuid).maxGuildLevel; + } + + public static int getMaxGuildLevel(UUID uuid, boolean databaseAccess) { + if (!isInMemory(uuid)) + if (databaseAccess) + return getDatabaseInteger(uuid, "GuildMaxLevel"); + else + //default fallback value for when PAPI suddenly decides to start querying the database thousands of times per second + return 0; + + return playerDataHashMap.get(uuid).maxGuildLevel; + } + + public static void setMaxGuildLevel(UUID uuid, int maxGuildLevel) { + setDatabaseValue(uuid, "GuildMaxLevel", maxGuildLevel); + + if (playerDataHashMap.containsKey(uuid)) + playerDataHashMap.get(uuid).maxGuildLevel = maxGuildLevel; + } + + public static int getActiveGuildLevel(UUID uuid) { + if (!isInMemory(uuid)) + return getDatabaseInteger(uuid, "GuildActiveLevel"); + + return playerDataHashMap.get(uuid).activeGuildLevel; + } + + public static int getActiveGuildLevel(UUID uuid, boolean databaseAccess) { + if (!isInMemory(uuid)) + if (databaseAccess) + return getDatabaseInteger(uuid, "GuildActiveLevel"); + else + //default fallback value for when PAPI suddenly decides to start querying the database thousands of times per second + return 0; + + return playerDataHashMap.get(uuid).activeGuildLevel; + } + + public static void setActiveGuildLevel(UUID uuid, int activeGuildLevel) { + setDatabaseValue(uuid, "GuildActiveLevel", activeGuildLevel); + + if (playerDataHashMap.containsKey(uuid)) + playerDataHashMap.get(uuid).activeGuildLevel = activeGuildLevel; + } + + public static List getQuests(UUID uuid) { + try { + if (!isInMemory(uuid)) + return (List) ObjectSerializer.fromString((String) getDatabaseBlob(uuid, "QuestStatus")); + if (playerDataHashMap.get(uuid) == null) return new ArrayList<>(); + return playerDataHashMap.get(uuid).quests == null ? new ArrayList<>() : playerDataHashMap.get(uuid).quests; + } catch (Exception ex) { + return new ArrayList<>(); + } + } + + public static Quest getQuest(UUID uuid, String questID) { + try { + UUID questUUID = UUID.fromString(questID); + return getQuest(uuid, questUUID); + } catch (Exception ex) { + new WarningMessage("Failed to convert quest ID from command into a valid UUID format!"); + return null; + } + } + + public static Quest getQuest(UUID uuid, UUID questUUID) { + List questList = null; + try { + if (!isInMemory(uuid)) + questList = (List) ObjectSerializer.fromString((String) getDatabaseBlob(uuid, "QuestStatus")); + else + questList = playerDataHashMap.get(uuid).quests; + } catch (Exception ex) { + return null; + } + for (Quest iteratedQuest : questList) + if (iteratedQuest.getQuestID().equals(questUUID)) + return iteratedQuest; + return null; + } + + public static void resetQuests(UUID uuid) { + getQuests(uuid).clear(); + updateQuestStatus(uuid); + } + + public static void removeQuest(UUID uuid, Quest quest) { + if (quest == null) return; + playerDataHashMap.get(uuid).quests.removeIf(iteratedQuest -> iteratedQuest.getQuestID().equals(quest.getQuestID())); + updateQuestStatus(uuid); + } + + public static void addQuest(UUID uuid, Quest quest) { + playerDataHashMap.get(uuid).quests.add(quest); + updateQuestStatus(uuid); + } + + public static void updateQuestStatus(UUID uuid, Quest quest) { + //this might be removed in the future + updateQuestStatus(uuid); + } + + @Nullable + public static PlayerQuestCooldowns getPlayerQuestCooldowns(UUID uuid) { + try { + if (!isInMemory(uuid)) + return (PlayerQuestCooldowns) ObjectSerializer.fromString((String) getDatabaseBlob(uuid, "PlayerQuestCooldowns")); + if (playerDataHashMap.get(uuid) == null) return PlayerQuestCooldowns.initializePlayer(); + return playerDataHashMap.get(uuid).playerQuestCooldowns == null ? PlayerQuestCooldowns.initializePlayer() : playerDataHashMap.get(uuid).playerQuestCooldowns; + } catch (Exception ex) { + return null; + } + } + + public static void resetPlayerQuestCooldowns(UUID uuid) { + updatePlayerQuestCooldowns(uuid, PlayerQuestCooldowns.initializePlayer()); + } + + public static void updatePlayerQuestCooldowns(UUID uuid, PlayerQuestCooldowns playerQuestCooldowns) { + try { + setDatabaseValue(uuid, "PlayerQuestCooldowns", ObjectSerializer.toString(playerQuestCooldowns)); + } catch (Exception ex) { + new WarningMessage("Failed to register player quest cooldowns!"); + ex.printStackTrace(); + } + } + + public static void setDatabaseValue(UUID uuid, String key, Object value) { + + new BukkitRunnable() { + @Override + public void run() { + Statement statement = null; + try { + statement = getConnection().createStatement(); + String sql; + if (value instanceof String) + sql = "UPDATE " + PLAYER_DATA_TABLE_NAME + " SET " + key + " = '" + value + "' WHERE PlayerUUID = '" + uuid.toString() + "';"; + else + sql = "UPDATE " + PLAYER_DATA_TABLE_NAME + " SET " + key + " = " + value + " WHERE PlayerUUID = '" + uuid.toString() + "';"; + statement.executeUpdate(sql); + statement.close(); + + } catch (Exception e) { + new WarningMessage("Failed to update database value."); + e.printStackTrace(); + } + } + }.runTaskAsynchronously(MetadataHandler.PLUGIN); + + } + + private static Object getDatabaseBlob(UUID uuid, String value) { + try { + Statement statement = getConnection().createStatement(); + ResultSet resultSet = statement.executeQuery("SELECT * FROM " + PLAYER_DATA_TABLE_NAME + " WHERE PlayerUUID = '" + uuid.toString() + "';"); + byte[] bytes = resultSet.getBytes(value); + resultSet.close(); + statement.close(); + if (bytes == null) return null; + return new String(bytes); + } catch (Exception e) { + new WarningMessage("Failed to get blob value from database!"); + new WarningMessage("UUID: " + uuid + " | Value: " + value); + e.printStackTrace(); + return null; + } + } + + public static int getScore(UUID uuid) { + if (!isInMemory(uuid)) + return getDatabaseInteger(uuid, "Score"); + return playerDataHashMap.get(uuid).score; + } + + public static void incrementScore(UUID uuid, int levelToIncrement) { + setDatabaseValue(uuid, "Score", getScore(uuid) + levelToIncrement * 2); + + if (playerDataHashMap.containsKey(uuid)) + playerDataHashMap.get(uuid).score += (levelToIncrement * 2); + } + + public static void decrementScore(UUID uuid) { + setDatabaseValue(uuid, "Score", getScore(uuid) - 100); + if (playerDataHashMap.containsKey(uuid)) + playerDataHashMap.get(uuid).score -= 100; + } + + public static int getKills(UUID uuid) { + if (!isInMemory(uuid)) + return getDatabaseInteger(uuid, "Kills"); + return playerDataHashMap.get(uuid).kills; + } + + public static void incrementKills(UUID uuid) { + setDatabaseValue(uuid, "Kills", getKills(uuid) + 1); + if (playerDataHashMap.containsKey(uuid)) + playerDataHashMap.get(uuid).kills += 1; + } + + public static int getHighestLevelKilled(UUID uuid) { + if (!isInMemory(uuid)) + return getDatabaseInteger(uuid, "HighestLevelKilled"); + return playerDataHashMap.get(uuid).highestLevelKilled; + } + + public static void setHighestLevelKilled(UUID uuid, int tentativeNewLevel) { + if (tentativeNewLevel < getHighestLevelKilled(uuid)) return; + setDatabaseValue(uuid, "HighestLevelKilled", tentativeNewLevel); + + if (playerDataHashMap.containsKey(uuid)) + playerDataHashMap.get(uuid).highestLevelKilled = tentativeNewLevel; + } + + public static int getDeaths(UUID uuid) { + if (!isInMemory(uuid)) + return getDatabaseInteger(uuid, "Deaths"); + + return playerDataHashMap.get(uuid).deaths; + } + + public static void incrementDeaths(UUID uuid) { + setDatabaseValue(uuid, "Deaths", getDeaths(uuid) + 1); + + if (playerDataHashMap.containsKey(uuid)) + playerDataHashMap.get(uuid).deaths += 1; + } + + public static int getQuestsCompleted(UUID uuid) { + if (!isInMemory(uuid)) + return getDatabaseInteger(uuid, "QuestsCompleted"); + + return playerDataHashMap.get(uuid).questsCompleted; + } + + public static void incrementQuestsCompleted(UUID uuid) { + setDatabaseValue(uuid, "QuestsCompleted", getQuestsCompleted(uuid) + 1); + + if (playerDataHashMap.containsKey(uuid)) + playerDataHashMap.get(uuid).questsCompleted += 1; + } + + public static Location getBackTeleportLocation(Player player) { + if (!isInMemory(player.getUniqueId())) + return ConfigurationLocation.serialize(getDatabaseString(player.getUniqueId(), "BackTeleportLocation")); + + return playerDataHashMap.get(player.getUniqueId()).backTeleportLocation; + } + + public static void setBackTeleportLocation(Player player, Location location) { + setDatabaseValue(player.getUniqueId(), "BackTeleportLocation", ConfigurationLocation.deserialize(location)); + playerDataHashMap.get(player.getUniqueId()).backTeleportLocation = location; + } + + public static boolean getUseBookMenus(UUID uuid) { + if (!isInMemory(uuid)) + return getDatabaseBoolean(uuid, "UseBookMenus"); + return playerDataHashMap.get(uuid).useBookMenus; + } + + public static void setUseBookMenus(Player player, boolean use) { + setDatabaseValue(player.getUniqueId(), "UseBookMenus", use); + playerDataHashMap.get(player.getUniqueId()).useBookMenus = use; + } + + public static boolean getDismissEMStatusScreenMessage(UUID uuid) { + if (!isInMemory(uuid)) + return getDatabaseBoolean(uuid, "DismissEMStatusScreenMessage"); + return playerDataHashMap.get(uuid).dismissEMStatusScreenMessage; + } + + public static void setDismissEMStatusScreenMessage(Player player, boolean use) { + setDatabaseValue(player.getUniqueId(), "DismissEMStatusScreenMessage", use); + playerDataHashMap.get(player.getUniqueId()).dismissEMStatusScreenMessage = use; + } + + public static MatchInstance getMatchInstance(Player player) { + return playerDataHashMap.get(player.getUniqueId()).matchInstance; + } + + public static void setMatchInstance(Player player, MatchInstance newMatchInstance) { + playerDataHashMap.get(player.getUniqueId()).matchInstance = newMatchInstance; + } + + private static Boolean getDatabaseBoolean(UUID uuid, String value) { + try { + Statement statement = getConnection().createStatement(); + ResultSet resultSet = statement.executeQuery("SELECT * FROM " + PLAYER_DATA_TABLE_NAME + " WHERE PlayerUUID = '" + uuid.toString() + "';"); + boolean reply = resultSet.getBoolean(value); + resultSet.close(); + statement.close(); + return reply; + } catch (Exception e) { + new WarningMessage("Failed to get double value from database!"); + e.printStackTrace(); + return null; + } + } + + + private static String getDatabaseString(UUID uuid, String value) { + try { + Statement statement = getConnection().createStatement(); + ResultSet resultSet = statement.executeQuery("SELECT * FROM " + PLAYER_DATA_TABLE_NAME + " WHERE PlayerUUID = '" + uuid.toString() + "';"); + String reply = resultSet.getString(value); + resultSet.close(); + statement.close(); + return reply; + } catch (Exception e) { + new WarningMessage("Failed to get string value from database!"); + e.printStackTrace(); + return null; + } + } + + private static Double getDatabaseDouble(UUID uuid, String value) { + try { + Statement statement = getConnection().createStatement(); + ResultSet resultSet = statement.executeQuery("SELECT * FROM " + PLAYER_DATA_TABLE_NAME + " WHERE PlayerUUID = '" + uuid.toString() + "';"); + double reply = resultSet.getDouble(value); + resultSet.close(); + statement.close(); + return reply; + } catch (Exception e) { + new WarningMessage("Failed to get double value from database!"); + e.printStackTrace(); + return null; + } + } + + private static Integer getDatabaseInteger(UUID uuid, String value) { + try { + Statement statement = getConnection().createStatement(); + ResultSet resultSet = statement.executeQuery("SELECT * FROM " + PLAYER_DATA_TABLE_NAME + " WHERE PlayerUUID = '" + uuid.toString() + "';"); + int reply = resultSet.getInt(value); + resultSet.close(); + statement.close(); + return reply; + } catch (Exception e) { + new WarningMessage("Failed to get integer value from database!"); + e.printStackTrace(); + return null; + } + } + + public static Connection getConnection() throws Exception { + File dataFolder = new File(MetadataHandler.PLUGIN.getDataFolder(), "data/" + DATABASE_NAME); + if (connection == null || connection.isClosed()) { + Class.forName("org.sqlite.JDBC"); + connection = DriverManager.getConnection("jdbc:sqlite:" + dataFolder); + connection.setAutoCommit(true); + } + return connection; + } + + public static void initializeDatabaseConnection() { + new File(MetadataHandler.PLUGIN.getDataFolder().getPath() + "/data").mkdirs(); + try { + new InfoMessage("Opened database successfully"); + GenerateDatabase.generate(); + for (Player player : Bukkit.getOnlinePlayers()) + new PlayerData(player.getUniqueId()); + } catch (Exception e) { + new WarningMessage(e.getClass().getName() + ": " + e.getMessage()); + new WarningMessage("Failed to establish a connection to the SQLite database. This is not good."); + } + + new PortOldData(); + } + + public static void closeConnection() { + try { + if (connection == null) return; + connection.close(); + } catch (Exception ex) { + new WarningMessage("Could not correctly close database connection."); + } + } + + private void readExistingData(Statement statement, UUID uuid, ResultSet resultSet) throws Exception { + playerDataHashMap.put(uuid, this); + currency = resultSet.getDouble("Currency"); + guildPrestigeLevel = resultSet.getInt("GuildPrestigeLevel"); + maxGuildLevel = resultSet.getInt("GuildMaxLevel"); + activeGuildLevel = resultSet.getInt("GuildActiveLevel"); + score = resultSet.getInt("Score"); + kills = resultSet.getInt("Kills"); + highestLevelKilled = resultSet.getInt("HighestLevelKilled"); + deaths = resultSet.getInt("Deaths"); + questsCompleted = resultSet.getInt("QuestsCompleted"); + backTeleportLocation = ConfigurationLocation.serialize(resultSet.getString("BackTeleportLocation")); + + if (resultSet.getBytes("QuestStatus") != null) { + try { + quests = (List) ObjectSerializer.fromString(new String(resultSet.getBytes("QuestStatus"), "UTF-8")); + //Serializes ItemStack which require specific handling, necessary recovering the rewards + for (Quest quest : quests) + if (quest instanceof CustomQuest) + ((CustomQuest) quest).applyTemporaryPermissions(Bukkit.getPlayer(uuid)); + } catch (Exception ex) { + new WarningMessage("Failed to serialize quest data for player " + Bukkit.getPlayer(uuid) + " ! This player's quest data will be wiped to prevent future errors."); + try { + resetQuests(uuid); + } catch (Exception ex2) { + new WarningMessage("Failed to reset quest data! Ironic."); + ex2.printStackTrace(); + } + } + } + + if (resultSet.getBytes("PlayerQuestCooldowns") != null) { + try { + playerQuestCooldowns = (PlayerQuestCooldowns) ObjectSerializer.fromString(new String(resultSet.getBytes("PlayerQuestCooldowns"), "UTF-8")); + playerQuestCooldowns.startCooldowns(uuid); + } catch (Exception exception) { + new WarningMessage("Failed to get player quest cooldowns! ! This player's quest cooldowns will be wiped to prevent future errors."); + try { + resetPlayerQuestCooldowns(uuid); + } catch (Exception ex2) { + new WarningMessage("Failed to reset quest cooldowns! Ironic."); + ex2.printStackTrace(); + } + } + } + + if (resultSet.getObject("UseBookMenus") != null) { + useBookMenus = resultSet.getBoolean("UseBookMenus"); + + } else { + setUseBookMenus(Bukkit.getPlayer(uuid), true); + } + + if (resultSet.getObject("DismissEMStatusScreenMessage") != null) { + dismissEMStatusScreenMessage = resultSet.getBoolean("UseBookMenus"); + } else { + setDismissEMStatusScreenMessage(Bukkit.getPlayer(uuid), false); + } + + new InfoMessage("User " + uuid + " data successfully read!"); + } + + private void writeNewData(Statement statement, UUID uuid) throws Exception { + playerDataHashMap.put(uuid, this); + currency = 0; + guildPrestigeLevel = 0; + maxGuildLevel = 1; + activeGuildLevel = 1; + score = 0; + kills = 0; + highestLevelKilled = 0; + deaths = 0; + questsCompleted = 0; + statement = getConnection().createStatement(); + String sql = "INSERT INTO " + PLAYER_DATA_TABLE_NAME + + " (PlayerUUID," + + " DisplayName," + + " Currency," + + " GuildPrestigeLevel," + + " GuildMaxLevel," + + " GuildActiveLevel," + + " Score," + + " Kills," + + " HighestLevelKilled," + + " Deaths," + + " QuestsCompleted) " + + //identifier + "VALUES ('" + uuid + "'," + + //display name + " '" + Bukkit.getPlayer(uuid).getName() + "'," + + //currency + " 0," + + //guild_prestige_level + " 0," + + //guild_max_level + " 1," + + //guild_active_level + " 1," + + //score + "0," + + //kills + "0," + + //highestLevelKilled + "0," + + //deaths + "0," + + //questsCompleted + "0);"; + statement.executeUpdate(sql); + + new InfoMessage("No player entry detected, generating new entry!"); + } + + public static class PlayerDataEvents implements Listener { + @EventHandler(priority = EventPriority.LOWEST) + public void onPlayerLogin(PlayerJoinEvent event) { + new BukkitRunnable() { + @Override + public void run() { + if (Bukkit.getPlayer(event.getPlayer().getUniqueId()) == null) return; + new PlayerData(event.getPlayer().getUniqueId()); + } + }.runTaskLaterAsynchronously(MetadataHandler.PLUGIN, 20); + } + + @EventHandler + public void onPlayerLogout(PlayerQuitEvent event) { + new BukkitRunnable() { + @Override + public void run() { + clearPlayerData(event.getPlayer().getUniqueId()); + setDisplayName(event.getPlayer().getUniqueId(), event.getPlayer().getName()); + } + }.runTaskLaterAsynchronously(MetadataHandler.PLUGIN, 20); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/playerdata/database/PortOldData.java b/src/main/java/com/magmaguy/elitemobs/playerdata/database/PortOldData.java new file mode 100644 index 000000000..8dab6971f --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/playerdata/database/PortOldData.java @@ -0,0 +1,161 @@ +package com.magmaguy.elitemobs.playerdata.database; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.utils.WarningMessage; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.configuration.file.YamlConfiguration; + +import java.io.File; +import java.sql.Statement; +import java.util.HashSet; +import java.util.UUID; + +public class PortOldData { + + public PortOldData() { + File playerCache = new File(MetadataHandler.PLUGIN.getDataFolder().getPath() + "/data/playerCache.yml"); + File playerGuildRank = new File(MetadataHandler.PLUGIN.getDataFolder().getPath() + "/data/playerGuildRank.yml"); + File playerMaxGuildRank = new File(MetadataHandler.PLUGIN.getDataFolder().getPath() + "/data/playerMaxGuildRank.yml"); + File playerMoneyData = new File(MetadataHandler.PLUGIN.getDataFolder().getPath() + "/data/playerMoneyData.yml"); + + if (!playerCache.isFile() && !playerGuildRank.isFile() && !playerMaxGuildRank.isFile() && !playerMoneyData.isFile()) + return; + + FileConfiguration playerCacheConfig = null, + playerGuildRankConfig = null, + playerMaxGuildRankConfig = null, + playerMoneyDataConfig = null; + + HashSet uuids = new HashSet<>(); + + if (playerCache.exists()) { + playerCacheConfig = YamlConfiguration.loadConfiguration(playerCache); + for (String string : playerCacheConfig.getKeys(false)) + uuids.add(UUID.fromString(string)); + } + + if (playerGuildRank.exists()) { + playerGuildRankConfig = YamlConfiguration.loadConfiguration(playerGuildRank); + for (String string : playerGuildRankConfig.getKeys(false)) + uuids.add(UUID.fromString(string)); + } + + if (playerMaxGuildRank.exists()) { + playerMaxGuildRankConfig = YamlConfiguration.loadConfiguration(playerMaxGuildRank); + for (String string : playerMaxGuildRankConfig.getKeys(false)) + uuids.add(UUID.fromString(string)); + } + + if (playerMoneyData.exists()) { + playerMoneyDataConfig = YamlConfiguration.loadConfiguration(playerMoneyData); + for (String string : playerMoneyDataConfig.getKeys(false)) + uuids.add(UUID.fromString(string)); + } + + if (uuids.isEmpty()) { + deleteConfigs(playerCache, playerGuildRank, playerMaxGuildRank, playerMoneyData); + return; + } + + boolean errored = false; + + for (UUID uuid : uuids) { + + boolean wasOldMaxRank = false; + + String displayName = null; + if (playerCacheConfig != null) { + if (playerCacheConfig.contains(uuid.toString())) + displayName = playerCacheConfig.getString(uuid.toString()); + } + if (displayName == null) { + displayName = "PlaceholderName"; + } + + Integer playerActiveGuildRank = null; + if (playerGuildRankConfig != null) { + if (playerGuildRankConfig.contains(uuid.toString())) + playerActiveGuildRank = playerGuildRankConfig.getInt(uuid.toString()); + } + if (playerActiveGuildRank == null) { + playerActiveGuildRank = 1; + } + + Integer playerMaxGuildRankValue = null; + if (playerMaxGuildRankConfig != null) { + if (playerMaxGuildRankConfig.contains(uuid.toString())) + playerMaxGuildRankValue = playerMaxGuildRankConfig.getInt(uuid.toString()); + } + if (playerMaxGuildRankValue == null) { + playerMaxGuildRankValue = 1; + } + if (playerMaxGuildRankValue == 11) { + playerActiveGuildRank = 10; + playerMaxGuildRankValue = 10; + wasOldMaxRank = true; + } + + Double currency = null; + if (playerMoneyDataConfig != null) { + if (playerMoneyDataConfig.contains(uuid.toString())) + currency = playerMoneyDataConfig.getDouble(uuid.toString()); + } + if (currency == null) { + currency = 0.0; + } + if (wasOldMaxRank) + currency += 30000; + + try { + Statement statement = null; + statement = PlayerData.getConnection().createStatement(); + String sql = "INSERT INTO " + PlayerData.getPLAYER_DATA_TABLE_NAME() + + " (PlayerUUID, DisplayName, Currency, GuildPrestigeLevel, GuildMaxLevel, GuildActiveLevel) " + + //identifier + "VALUES ('" + uuid.toString() + "'," + + //display name + " '" + displayName + "'," + + //currency + " " + currency + "," + + //guild_prestige_level + " 0," + + //guild_max_level + " " + playerMaxGuildRankValue + "," + + //guild_active_level + " " + playerActiveGuildRank + ");"; + statement.executeUpdate(sql); + statement.close(); + PlayerData.getConnection().commit(); + PlayerData.getConnection().close(); + } catch (Exception e) { + new WarningMessage("Warning: Failed to write values from old config files to new database system. Tell the dev!"); + System.err.println(e.getClass().getName() + ": " + e.getMessage()); + errored = true; + } + + } + + if (!errored) + deleteConfigs(playerCache, playerGuildRank, playerMaxGuildRank, playerMoneyData); + + } + + private void deleteConfigs(File playerCache, File playerGuildRank, File playerMaxGuildRank, File playerMoneyData) { + deleteConfig(playerCache); + deleteConfig(playerGuildRank); + deleteConfig(playerMaxGuildRank); + deleteConfig(playerMoneyData); + } + + private void deleteConfig(File file) { + try { + if (file.exists() && file.isFile()) { + file.delete(); + new WarningMessage("Deleted data file " + file.getName() + " - was no longer in use, moved to SQLite"); + } + } catch (Exception ex) { + + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/playerdata/statusscreen/BossTrackingPage.java b/src/main/java/com/magmaguy/elitemobs/playerdata/statusscreen/BossTrackingPage.java new file mode 100644 index 000000000..952b77cf3 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/playerdata/statusscreen/BossTrackingPage.java @@ -0,0 +1,120 @@ +package com.magmaguy.elitemobs.playerdata.statusscreen; + +import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; +import com.magmaguy.elitemobs.config.menus.premade.PlayerStatusMenuConfig; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import com.magmaguy.elitemobs.utils.SpigotMessage; +import com.magmaguy.elitemobs.utils.WarningMessage; +import net.md_5.bungee.api.chat.ClickEvent; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.inventory.Inventory; + +import java.util.*; + +public class BossTrackingPage { + private BossTrackingPage() { + } + + protected static TextComponent[] bossTrackingPage(Player player) { + + TextComponent configTextComponent = new TextComponent(); + + for (int i = 0; i < 3; i++) { + + TextComponent line = new TextComponent(PlayerStatusMenuConfig.getBossTrackerTextLines()[i] + "\n"); + + if (!PlayerStatusMenuConfig.getBossTrackerHoverLines()[i].isEmpty()) + PlayerStatusScreen.setHoverText(line, PlayerStatusMenuConfig.getBossTrackerHoverLines()[i]); + + if (!PlayerStatusMenuConfig.getBossTrackerCommandLines()[i].isEmpty()) + line.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, PlayerStatusMenuConfig.getBossTrackerCommandLines()[i])); + + configTextComponent.addExtra(line); + } + + ArrayList textComponents = new ArrayList<>(); + int counter = 0; + + for (CustomBossEntity customBossEntity : CustomBossEntity.getTrackableCustomBosses()) { + try { + textComponents.add(SpigotMessage.commandHoverMessage( + customBossEntity.getCustomBossBossBar().bossBarMessage(player, customBossEntity.getCustomBossesConfigFields().getLocationMessage()) + "\n", + PlayerStatusMenuConfig.getOnBossTrackHover(), + "/elitemobs trackcustomboss " + customBossEntity.getEliteUUID())); + + counter++; + } catch (Exception ex) { + new WarningMessage("Failed to correctly get elements for boss tracking page!"); + ex.printStackTrace(); + } + } + + TextComponent[] textComponent; + if (counter == 0) { + textComponent = new TextComponent[1]; + textComponent[0] = configTextComponent; + } else { + textComponent = new TextComponent[(int) Math.floor(counter / 6D) + 1]; + int internalCounter = 0; + textComponent[0] = configTextComponent; + for (TextComponent text : textComponents) { + int currentPage = (int) Math.floor(internalCounter / 6D); + if (textComponent[currentPage] == null) + textComponent[currentPage] = new TextComponent(); + textComponent[currentPage].addExtra(text); + internalCounter++; + } + } + return textComponent; + } + + protected static void bossTrackingPage(Player targetPlayer, Player requestingPlayer) { + Inventory inventory = Bukkit.createInventory(requestingPlayer, 54, PlayerStatusMenuConfig.getBossTrackerChestMenuName()); + int counter = 0; + BossTrackingPageEvents.bosses.clear(); + for (CustomBossEntity customBossEntity : CustomBossEntity.getTrackableCustomBosses()) { + BossTrackingPageEvents.bosses.add(customBossEntity); + inventory.setItem(counter, ItemStackGenerator.generateItemStack(Material.ZOMBIE_HEAD, + customBossEntity.getCustomBossBossBar().bossBarMessage(targetPlayer, customBossEntity.getCustomBossesConfigFields().getLocationMessage()), + Collections.singletonList(MobCombatSettingsConfig.getBossLocationMessage()))); + counter++; + } + inventory.setItem(53, PlayerStatusMenuConfig.getBackItem()); + requestingPlayer.openInventory(inventory); + BossTrackingPageEvents.pageInventories.put(requestingPlayer, inventory); + } + + public static class BossTrackingPageEvents implements Listener { + private static final Map pageInventories = new HashMap<>(); + private static final List bosses = new ArrayList<>(); + + @EventHandler (ignoreCancelled = true) + public void onInventoryInteract(InventoryClickEvent event) { + Player player = ((Player) event.getWhoClicked()).getPlayer(); + if (!pageInventories.containsKey(player)) return; + event.setCancelled(true); + if (bosses.size() - 1 >= event.getSlot()) { + player.closeInventory(); + bosses.get(event.getSlot()).getCustomBossBossBar().addTrackingPlayer(player); + return; + } + if (event.getSlot() == 53) { + player.closeInventory(); + CoverPage.coverPage(player); + } + } + + @EventHandler + public void onInventoryClose(InventoryCloseEvent event) { + pageInventories.remove(event.getPlayer()); + } + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/playerdata/statusscreen/CommandsPage.java b/src/main/java/com/magmaguy/elitemobs/playerdata/statusscreen/CommandsPage.java new file mode 100644 index 000000000..10b0c7c21 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/playerdata/statusscreen/CommandsPage.java @@ -0,0 +1,69 @@ +package com.magmaguy.elitemobs.playerdata.statusscreen; + +import com.magmaguy.elitemobs.config.menus.premade.PlayerStatusMenuConfig; +import net.md_5.bungee.api.chat.ClickEvent; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.inventory.Inventory; + +import java.util.HashMap; +import java.util.Map; + +public class CommandsPage { + + private CommandsPage() { + } + + protected static TextComponent commandsPage() { + + TextComponent textComponent = new TextComponent(); + + for (int i = 0; i < 13; i++) { + + TextComponent line = new TextComponent(PlayerStatusMenuConfig.getCommandsTextLines()[i] + "\n"); + + if (!PlayerStatusMenuConfig.getCommandsHoverLines()[i].isEmpty()) + PlayerStatusScreen.setHoverText(line, PlayerStatusMenuConfig.getCommandsHoverLines()[i]); + + if (!PlayerStatusMenuConfig.getCommandsCommandLines()[i].isEmpty()) + line.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, PlayerStatusMenuConfig.getCommandsCommandLines()[i])); + + textComponent.addExtra(line); + } + return textComponent; + } + + protected static void commandsPage(Player targetPlayer, Player requestingPlayer) { + Inventory inventory = Bukkit.createInventory(requestingPlayer, 27, PlayerStatusMenuConfig.getCommandsChestMenuName()); + inventory.setItem(PlayerStatusMenuConfig.getCommandsAGSlot(), PlayerStatusMenuConfig.getCommandsAGItem()); + inventory.setItem(PlayerStatusMenuConfig.getCommandsShareItemSlot(), PlayerStatusMenuConfig.getCommandsShareItemItem()); + inventory.setItem(26, PlayerStatusMenuConfig.getBackItem()); + requestingPlayer.openInventory(inventory); + CommandsPageEvents.pageInventories.put(requestingPlayer, inventory); + } + + public static class CommandsPageEvents implements Listener { + private static final Map pageInventories = new HashMap<>(); + + @EventHandler (ignoreCancelled = true) + public void onInventoryInteract(InventoryClickEvent event) { + Player player = ((Player) event.getWhoClicked()).getPlayer(); + if (!pageInventories.containsKey(player)) return; + event.setCancelled(true); + if (event.getSlot() == 26) { + player.closeInventory(); + CoverPage.coverPage(player); + } + } + + @EventHandler + public void onInventoryClose(InventoryCloseEvent event) { + pageInventories.remove(event.getPlayer()); + } + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/playerdata/statusscreen/CoverPage.java b/src/main/java/com/magmaguy/elitemobs/playerdata/statusscreen/CoverPage.java new file mode 100644 index 000000000..e55defc69 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/playerdata/statusscreen/CoverPage.java @@ -0,0 +1,137 @@ +package com.magmaguy.elitemobs.playerdata.statusscreen; + +import com.magmaguy.elitemobs.commands.guild.AdventurersGuildCommand; +import com.magmaguy.elitemobs.config.menus.premade.PlayerStatusMenuConfig; +import net.md_5.bungee.api.chat.ClickEvent; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.inventory.Inventory; + +import java.util.HashMap; +import java.util.Map; + +public class CoverPage { + protected static TextComponent coverPage(int statsPage, int gearPage, int teleportsPage, int commandsPage, int questsPage, int bossTrackingPage) { + + TextComponent textComponent = new TextComponent(); + + for (int i = 0; i < 13; i++) { + TextComponent line = new TextComponent( + PlayerStatusMenuConfig.getIndexTextLines()[i] + .replace("$statsPage", statsPage + "") + .replace("$gearPage", gearPage + "") + .replace("$teleportsPage", teleportsPage + "") + .replace("$commandsPage", commandsPage + "") + .replace("$questsPage", questsPage + "") + .replace("$bossTrackingPage", bossTrackingPage + "") + + "\n"); + + if (!PlayerStatusMenuConfig.getIndexHoverLines()[i].isEmpty()) + PlayerStatusScreen.setHoverText(line, PlayerStatusMenuConfig.getIndexHoverLines()[i]); + + if (PlayerStatusMenuConfig.getIndexCommandLines()[i].contains("$statsPage")) + line.setClickEvent(new ClickEvent(ClickEvent.Action.CHANGE_PAGE, PlayerStatusMenuConfig.getIndexCommandLines()[i].replace("$statsPage", statsPage + ""))); + else if (PlayerStatusMenuConfig.getIndexCommandLines()[i].contains("$gearPage")) + line.setClickEvent(new ClickEvent(ClickEvent.Action.CHANGE_PAGE, PlayerStatusMenuConfig.getIndexCommandLines()[i].replace("$gearPage", gearPage + ""))); + else if (PlayerStatusMenuConfig.getIndexCommandLines()[i].contains("$teleportsPage")) + line.setClickEvent(new ClickEvent(ClickEvent.Action.CHANGE_PAGE, PlayerStatusMenuConfig.getIndexCommandLines()[i].replace("$teleportsPage", teleportsPage + ""))); + else if (PlayerStatusMenuConfig.getIndexCommandLines()[i].contains("$commandsPage")) + line.setClickEvent(new ClickEvent(ClickEvent.Action.CHANGE_PAGE, PlayerStatusMenuConfig.getIndexCommandLines()[i].replace("$commandsPage", commandsPage + ""))); + else if (PlayerStatusMenuConfig.getIndexCommandLines()[i].contains("$questsPage")) + line.setClickEvent(new ClickEvent(ClickEvent.Action.CHANGE_PAGE, PlayerStatusMenuConfig.getIndexCommandLines()[i].replace("$questsPage", questsPage + ""))); + else if (PlayerStatusMenuConfig.getIndexCommandLines()[i].contains("$bossTrackingPage")) + line.setClickEvent(new ClickEvent(ClickEvent.Action.CHANGE_PAGE, PlayerStatusMenuConfig.getIndexCommandLines()[i].replace("$bossTrackingPage", bossTrackingPage + ""))); + + else + line.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, PlayerStatusMenuConfig.getIndexCommandLines()[i])); + + textComponent.addExtra(line); + } + + return textComponent; + + } + + protected static void coverPage(Player requestingPlayer) { + Inventory inventory = Bukkit.createInventory(requestingPlayer, 27, PlayerStatusMenuConfig.getIndexChestMenuName()); + inventory.setItem(PlayerStatusMenuConfig.getIndexHeaderSlot(), PlayerStatusMenuConfig.getIndexHeaderItem()); + + if (PlayerStatusMenuConfig.isDoStatsPage()) + inventory.setItem(PlayerStatusMenuConfig.getIndexStatsSlot(), PlayerStatusMenuConfig.getIndexStatsItem()); + if (PlayerStatusMenuConfig.isDoGearPage()) + inventory.setItem(PlayerStatusMenuConfig.getIndexGearSlot(), PlayerStatusMenuConfig.getIndexGearItem()); + if (PlayerStatusMenuConfig.isDoTeleportsPage()) + inventory.setItem(PlayerStatusMenuConfig.getIndexTeleportsSlot(), PlayerStatusMenuConfig.getIndexTeleportsItem()); + if (PlayerStatusMenuConfig.isDoCommandsPage()) + inventory.setItem(PlayerStatusMenuConfig.getIndexCommandsSlot(), PlayerStatusMenuConfig.getIndexCommandsItem()); + if (PlayerStatusMenuConfig.isDoQuestTrackingPage()) + inventory.setItem(PlayerStatusMenuConfig.getIndexQuestTrackingSlot(), PlayerStatusMenuConfig.getIndexQuestTrackingItem()); + if (PlayerStatusMenuConfig.isDoBossTrackingPage()) + inventory.setItem(PlayerStatusMenuConfig.getIndexBossTrackingSlot(), PlayerStatusMenuConfig.getIndexBossTrackingItem()); + CoverPageEvents.pageInventories.put(requestingPlayer, inventory); + requestingPlayer.openInventory(inventory); + } + + public static class CoverPageEvents implements Listener { + private static final Map pageInventories = new HashMap<>(); + + @EventHandler + public void onInventoryInteract(InventoryClickEvent event) { + Player player = ((Player) event.getWhoClicked()).getPlayer(); + if (!pageInventories.containsKey(player)) return; + event.setCancelled(true); + + if (event.getSlot() == PlayerStatusMenuConfig.getIndexHeaderSlot()) { + player.closeInventory(); + AdventurersGuildCommand.adventurersGuildCommand(player); + return; + } + + if (event.getSlot() == PlayerStatusMenuConfig.getIndexGearSlot() && PlayerStatusMenuConfig.isDoGearPage()) { + player.closeInventory(); + GearPage.gearPage(player, player); + return; + } + + if (event.getSlot() == PlayerStatusMenuConfig.getIndexStatsSlot() && PlayerStatusMenuConfig.isDoStatsPage()) { + player.closeInventory(); + StatsPage.statsPage(player, player); + return; + } + + if (event.getSlot() == PlayerStatusMenuConfig.getIndexCommandsSlot() && PlayerStatusMenuConfig.isDoCommandsPage()) { + player.closeInventory(); + CommandsPage.commandsPage(player, player); + return; + } + + if (event.getSlot() == PlayerStatusMenuConfig.getIndexTeleportsSlot() && PlayerStatusMenuConfig.isDoTeleportsPage()) { + player.closeInventory(); + TeleportsPage.teleportsPage(player, player); + return; + } + + if (event.getSlot() == PlayerStatusMenuConfig.getIndexQuestTrackingSlot() && PlayerStatusMenuConfig.isDoQuestTrackingPage()) { + player.closeInventory(); + QuestsPage.questsPage(player, player); + return; + } + + if (event.getSlot() == PlayerStatusMenuConfig.getIndexBossTrackingSlot() && PlayerStatusMenuConfig.isDoBossTrackingPage()) { + player.closeInventory(); + BossTrackingPage.bossTrackingPage(player, player); + return; + } + } + + @EventHandler + public void onInventoryClose(InventoryCloseEvent event) { + pageInventories.remove(event.getPlayer()); + } + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/playerdata/statusscreen/GearPage.java b/src/main/java/com/magmaguy/elitemobs/playerdata/statusscreen/GearPage.java new file mode 100644 index 000000000..9036b5da8 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/playerdata/statusscreen/GearPage.java @@ -0,0 +1,271 @@ +package com.magmaguy.elitemobs.playerdata.statusscreen; + +import com.magmaguy.elitemobs.api.EliteMobsItemDetector; +import com.magmaguy.elitemobs.config.menus.premade.PlayerStatusMenuConfig; +import com.magmaguy.elitemobs.items.ShareItem; +import com.magmaguy.elitemobs.playerdata.ElitePlayerInventory; +import com.magmaguy.elitemobs.utils.VersionChecker; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.HashMap; +import java.util.Map; + +public class GearPage { + protected static TextComponent gearPage(Player targetPlayer) { + + TextComponent textComponent = new TextComponent(); + + for (int i = 0; i < 13; i++) { + + TextComponent line; + + if (!PlayerStatusMenuConfig.getGearTextLines()[i].contains("{")) { + line = new TextComponent(parseGearPlaceholders(PlayerStatusMenuConfig.getGearTextLines()[i], targetPlayer) + "\n"); + gearMultiComponentLine(textComponent, line, i, targetPlayer, false, 0); + } else { + TextComponent prePlaceholderElements = new TextComponent(parseGearPlaceholders(PlayerStatusMenuConfig.getGearTextLines()[i].split("\\{")[0], targetPlayer)); + gearMultiComponentLine(textComponent, prePlaceholderElements, i, targetPlayer, false, 0); + for (int j = 0; j < PlayerStatusMenuConfig.getGearTextLines()[i].split("\\{").length; j++) { + TextComponent placeholderString = new TextComponent(parseGearPlaceholders(PlayerStatusMenuConfig.getGearTextLines()[i].split("\\{")[j].split("}")[0], targetPlayer)); + gearMultiComponentLine(textComponent, placeholderString, i, targetPlayer, true, j); + if (PlayerStatusMenuConfig.getGearTextLines()[i].split("}").length > j + && PlayerStatusMenuConfig.getGearTextLines()[i].split("}")[j].contains("{")) { + TextComponent spaceBetweenPlaceholders = new TextComponent(parseGearPlaceholders(PlayerStatusMenuConfig.getGearTextLines()[i].split("}")[j].split("\\{")[0], targetPlayer)); + gearMultiComponentLine(textComponent, spaceBetweenPlaceholders, i, targetPlayer, false, 0); + } + } + TextComponent spaceAfterPlaceholders = new TextComponent("\n"); + gearMultiComponentLine(textComponent, spaceAfterPlaceholders, i, targetPlayer, false, 0); + } + + + } + + return textComponent; + } + + private static String parseGearPlaceholders(String string, Player targetPlayer) { + + if (string.contains("$helmettier")) + if (targetPlayer.getEquipment().getHelmet() != null) + return unicodeColorizer(targetPlayer.getEquipment().getHelmet().getType()) + + string.replace("$helmettier", + ElitePlayerInventory.playerInventories.get(targetPlayer.getUniqueId()).helmet.getTier(targetPlayer.getInventory().getHelmet(), true) + ""); + else + return string.replace("$helmettier", + ElitePlayerInventory.playerInventories.get(targetPlayer.getUniqueId()).helmet.getTier(targetPlayer.getInventory().getHelmet(), true) + ""); + if (string.contains("$chestplatetier")) + if (targetPlayer.getEquipment().getChestplate() != null) + return unicodeColorizer(targetPlayer.getEquipment().getChestplate().getType()) + + string.replace("$chestplatetier", + ElitePlayerInventory.playerInventories.get(targetPlayer.getUniqueId()).chestplate.getTier(targetPlayer.getInventory().getChestplate(), true) + ""); + else + return string.replace("$chestplatetier", + ElitePlayerInventory.playerInventories.get(targetPlayer.getUniqueId()).chestplate.getTier(targetPlayer.getInventory().getChestplate(), true) + ""); + if (string.contains("$leggingstier")) + if (targetPlayer.getEquipment().getLeggings() != null) + return unicodeColorizer(targetPlayer.getEquipment().getLeggings().getType()) + + string.replace("$leggingstier", + ElitePlayerInventory.playerInventories.get(targetPlayer.getUniqueId()).leggings.getTier(targetPlayer.getInventory().getLeggings(), true) + ""); + else + return string.replace("$leggingstier", + ElitePlayerInventory.playerInventories.get(targetPlayer.getUniqueId()).leggings.getTier(targetPlayer.getInventory().getLeggings(), true) + ""); + if (string.contains("$bootstier")) + if (targetPlayer.getEquipment().getBoots() != null) + return unicodeColorizer(targetPlayer.getEquipment().getBoots().getType()) + + string.replace("$bootstier", + ElitePlayerInventory.playerInventories.get(targetPlayer.getUniqueId()).boots.getTier(targetPlayer.getInventory().getBoots(), true) + ""); + else + return string.replace("$bootstier", + ElitePlayerInventory.playerInventories.get(targetPlayer.getUniqueId()).boots.getTier(targetPlayer.getInventory().getBoots(), true) + ""); + if (string.contains("$mainhandtier")) + return unicodeColorizer(targetPlayer.getEquipment().getItemInMainHand().getType()) + + string.replace("$mainhandtier", + ElitePlayerInventory.playerInventories.get(targetPlayer.getUniqueId()).mainhand.getTier(targetPlayer.getInventory().getItemInMainHand(), true) + ""); + if (string.contains("$offhandtier")) + return unicodeColorizer(targetPlayer.getEquipment().getItemInOffHand().getType()) + + string.replace("$offhandtier", + ElitePlayerInventory.playerInventories.get(targetPlayer.getUniqueId()).offhand.getTier(targetPlayer.getInventory().getItemInOffHand(), true) + ""); + if (string.contains("$damage")) + return string.replace("$damage", ElitePlayerInventory.playerInventories.get(targetPlayer.getUniqueId()).baseDamage() + ""); + if (string.contains("$armor")) + return string.replace("$armor", ElitePlayerInventory.playerInventories.get(targetPlayer.getUniqueId()).baseDamageReduction() + ""); + if (string.contains("$threat")) + return string.replace("$threat", ElitePlayerInventory.playerInventories.get(targetPlayer.getUniqueId()).getNaturalMobSpawnLevel(true) + ""); + + return string; + + } + + private static void gearMultiComponentLine(TextComponent textComponent, TextComponent line, int i, Player targetPlayer, boolean brackets, int bracketCount) { + + if (!PlayerStatusMenuConfig.getGearHoverLines()[i].isEmpty()) { + String hoverLines = PlayerStatusMenuConfig.getGearHoverLines()[i]; + if (hoverLines.contains("$helmet")) + ShareItem.setItemHoverEvent(line, targetPlayer.getInventory().getHelmet()); + else if (hoverLines.contains("$chestplate")) + ShareItem.setItemHoverEvent(line, targetPlayer.getInventory().getChestplate()); + else if (hoverLines.contains("$leggings")) + ShareItem.setItemHoverEvent(line, targetPlayer.getEquipment().getLeggings()); + else if (hoverLines.contains("$boots")) + ShareItem.setItemHoverEvent(line, targetPlayer.getInventory().getBoots()); + else if (brackets) { + if (hoverLines.contains("{") && hoverLines.contains("}")) + for (int j = 0; j < hoverLines.split("\\{").length; j++) + if (bracketCount == j) { + String parsedLine = hoverLines.split("\\{")[j].split("}")[0]; + if (parsedLine.contains("$mainhand")) { + ShareItem.setItemHoverEvent(line, targetPlayer.getInventory().getItemInMainHand()); + } else if (parsedLine.contains("$offhand")) { + ShareItem.setItemHoverEvent(line, targetPlayer.getInventory().getItemInOffHand()); + } else + PlayerStatusScreen.setHoverText(line, parsedLine); + } + } else if (!(hoverLines.contains("{") && hoverLines.contains("}"))) + PlayerStatusScreen.setHoverText(line, PlayerStatusMenuConfig.getGearHoverLines()[i]); + + } + + textComponent.addExtra(line); + } + + private static ChatColor unicodeColorizer(Material material) { + switch (material) { + case DIAMOND_AXE: + case DIAMOND_SWORD: + case DIAMOND_HOE: + case DIAMOND_HELMET: + case DIAMOND_CHESTPLATE: + case DIAMOND_LEGGINGS: + case DIAMOND_BOOTS: + case DIAMOND_SHOVEL: + case DIAMOND_PICKAXE: + return ChatColor.AQUA; + case IRON_AXE: + case IRON_SWORD: + case IRON_HOE: + case IRON_HELMET: + case IRON_CHESTPLATE: + case IRON_LEGGINGS: + case IRON_BOOTS: + case IRON_SHOVEL: + case IRON_PICKAXE: + case CHAINMAIL_HELMET: + case CHAINMAIL_CHESTPLATE: + case CHAINMAIL_LEGGINGS: + case CHAINMAIL_BOOTS: + case STONE_AXE: + case STONE_SWORD: + case STONE_HOE: + case STONE_SHOVEL: + case STONE_PICKAXE: + return ChatColor.GRAY; + case GOLDEN_AXE: + case GOLDEN_SWORD: + case GOLDEN_HOE: + case GOLDEN_HELMET: + case GOLDEN_CHESTPLATE: + case GOLDEN_LEGGINGS: + case GOLDEN_BOOTS: + case GOLDEN_SHOVEL: + case GOLDEN_PICKAXE: + return ChatColor.YELLOW; + case LEATHER_HELMET: + case LEATHER_CHESTPLATE: + case LEATHER_LEGGINGS: + case LEATHER_BOOTS: + case WOODEN_AXE: + case WOODEN_SWORD: + case WOODEN_HOE: + case WOODEN_SHOVEL: + case WOODEN_PICKAXE: + return ChatColor.GOLD; + case TURTLE_HELMET: + return ChatColor.GREEN; + default: + if (!VersionChecker.serverVersionOlderThan(16, 0)) { + if (material.equals(Material.NETHERITE_HELMET) || + material.equals(Material.NETHERITE_CHESTPLATE) || + material.equals(Material.NETHERITE_LEGGINGS) || + material.equals(Material.NETHERITE_BOOTS) || + material.equals(Material.NETHERITE_SWORD) || + material.equals(Material.NETHERITE_AXE) || + material.equals(Material.NETHERITE_HOE) || + material.equals(Material.NETHERITE_PICKAXE)) + return ChatColor.BLACK; + } + return ChatColor.DARK_GRAY; + } + } + + protected static void gearPage(Player requestingPlayer, Player targetPlayer) { + Inventory inventory = Bukkit.createInventory(requestingPlayer, 54, PlayerStatusMenuConfig.getGearChestMenuName()); + //head + if (EliteMobsItemDetector.isEliteMobsItem(targetPlayer.getInventory().getArmorContents()[3])) + inventory.setItem(11, targetPlayer.getInventory().getArmorContents()[3]); + //main hand + if (EliteMobsItemDetector.isEliteMobsItem(targetPlayer.getInventory().getItemInMainHand())) + inventory.setItem(19, targetPlayer.getInventory().getItemInMainHand()); + //chestplate + if (EliteMobsItemDetector.isEliteMobsItem(targetPlayer.getInventory().getArmorContents()[2])) + inventory.setItem(20, targetPlayer.getInventory().getArmorContents()[2]); + //shield + if (EliteMobsItemDetector.isEliteMobsItem(targetPlayer.getInventory().getItemInOffHand())) + inventory.setItem(21, targetPlayer.getInventory().getItemInOffHand()); + //leggings + if (EliteMobsItemDetector.isEliteMobsItem(targetPlayer.getInventory().getArmorContents()[1])) + inventory.setItem(29, targetPlayer.getInventory().getArmorContents()[1]); + //boots + inventory.setItem(38, targetPlayer.getInventory().getArmorContents()[0]); + inventory.setItem(PlayerStatusMenuConfig.getGearDamageSlot(), + replaceItemNamePlaceholder(PlayerStatusMenuConfig.getGearDamageItem().clone(), "$damage", + ElitePlayerInventory.playerInventories.get(targetPlayer.getUniqueId()).baseDamage() + "")); + inventory.setItem(PlayerStatusMenuConfig.getGearArmorSlot(), + replaceItemNamePlaceholder(PlayerStatusMenuConfig.getGearArmorItem().clone(), "$defense", + ElitePlayerInventory.playerInventories.get(targetPlayer.getUniqueId()).baseDamageReduction() + "")); + inventory.setItem(PlayerStatusMenuConfig.getGearThreatSlot(), + replaceItemNamePlaceholder(PlayerStatusMenuConfig.getGearThreatItem().clone(), "$threat", + ElitePlayerInventory.playerInventories.get(targetPlayer.getUniqueId()).getNaturalMobSpawnLevel(true) + "")); + inventory.setItem(53, PlayerStatusMenuConfig.getBackItem()); + GearPageEvents.pageInventories.put(requestingPlayer, inventory); + requestingPlayer.openInventory(inventory); + } + + private static ItemStack replaceItemNamePlaceholder(ItemStack itemStack, String placeholder, String replacement) { + ItemMeta itemMeta = itemStack.getItemMeta(); + itemMeta.setDisplayName(itemMeta.getDisplayName().replace(placeholder, replacement)); + itemStack.setItemMeta(itemMeta); + return itemStack; + } + + public static class GearPageEvents implements Listener { + private static final Map pageInventories = new HashMap<>(); + + @EventHandler (ignoreCancelled = true) + public void onInventoryInteract(InventoryClickEvent event) { + Player player = ((Player) event.getWhoClicked()).getPlayer(); + if (!pageInventories.containsKey(player)) return; + event.setCancelled(true); + if (event.getSlot() == 53) { + player.closeInventory(); + CoverPage.coverPage(player); + } + } + + @EventHandler + public void onInventoryClose(InventoryCloseEvent event) { + pageInventories.remove(event.getPlayer()); + } + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/playerdata/statusscreen/PlayerStatusScreen.java b/src/main/java/com/magmaguy/elitemobs/playerdata/statusscreen/PlayerStatusScreen.java new file mode 100644 index 000000000..b3335b1ac --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/playerdata/statusscreen/PlayerStatusScreen.java @@ -0,0 +1,130 @@ +package com.magmaguy.elitemobs.playerdata.statusscreen; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.config.DefaultConfig; +import com.magmaguy.elitemobs.config.TranslationConfig; +import com.magmaguy.elitemobs.config.menus.premade.PlayerStatusMenuConfig; +import com.magmaguy.elitemobs.playerdata.database.PlayerData; +import com.magmaguy.elitemobs.thirdparty.geyser.GeyserDetector; +import com.magmaguy.elitemobs.utils.BookMaker; +import net.md_5.bungee.api.chat.ComponentBuilder; +import net.md_5.bungee.api.chat.HoverEvent; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.entity.Player; +import org.bukkit.event.Listener; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.BookMeta; + +import java.util.ArrayList; +import java.util.List; + +public class PlayerStatusScreen implements Listener { + + public PlayerStatusScreen(Player requestingPlayer, Player targetPlayer) { + ItemStack writtenBook = generateBook(requestingPlayer, targetPlayer); + BookMeta bookMeta = (BookMeta) writtenBook.getItemMeta(); + List pages = bookMeta.getPages(); + String debugPage = ""; + debugPage += "Is in memory: " + PlayerData.isInMemory(targetPlayer); + ArrayList newPages = new ArrayList<>(pages); + newPages.add(debugPage); + BookMaker.generateBook(requestingPlayer, newPages); + } + + public PlayerStatusScreen(Player player) { + if (!PlayerData.getUseBookMenus(player.getUniqueId()) || GeyserDetector.bedrockPlayer(player) || DefaultConfig.isOnlyUseBedrockMenus()) { + generateChestMenu(player, player); + } else { + generateBook(player, player); + } + if (!PlayerData.getDismissEMStatusScreenMessage(player.getUniqueId()) && !DefaultConfig.isOnlyUseBedrockMenus()) { + player.sendMessage(TranslationConfig.getDismissEMMessage()); + } + } + + protected static void setHoverText(TextComponent textComponent, String text) { + textComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(text).create())); + } + + public static String convertLightColorsToBlack(String string) { + string = ChatColorConverter.convert(string); + string = string.replace("§f", "§0").replace("§e", "§0"); + if (!string.startsWith("§")) + string = "§0" + string; + return string; + } + + private void generateChestMenu(Player requestingPlayer, Player targetPlayer) { + CoverPage.coverPage(requestingPlayer); + } + + private ItemStack generateBook(Player requestingPlayer, Player targetPlayer) { + TextComponent[] pages = new TextComponent[50]; + int pageCounter = 1; + pageCounter++; + int statsPage = -1; + int gearPage = -1; + int teleportsPage = -1; + int commandsPage = -1; + int questsPage = -1; + int bossTrackingPage = -1; + if (PlayerStatusMenuConfig.isDoStatsPage()) { + statsPage = pageCounter; + pages[pageCounter] = StatsPage.statsPage(targetPlayer); + pageCounter++; + } + if (PlayerStatusMenuConfig.isDoGearPage()) { + gearPage = pageCounter; + pages[pageCounter] = GearPage.gearPage(targetPlayer); + pageCounter++; + } + if (PlayerStatusMenuConfig.isDoTeleportsPage()) { + teleportsPage = pageCounter; + for (TextComponent textComponent : TeleportsPage.teleportsPage()) { + pages[pageCounter] = textComponent; + pageCounter++; + } + } + if (PlayerStatusMenuConfig.isDoCommandsPage()) { + commandsPage = pageCounter; + pages[pageCounter] = CommandsPage.commandsPage(); + pageCounter++; + } + if (PlayerStatusMenuConfig.isDoQuestTrackingPage()) { + questsPage = pageCounter; + for (TextComponent textComponent : QuestsPage.questsPage(targetPlayer)) { + pages[pageCounter] = textComponent; + pageCounter++; + } + } + + if (PlayerStatusMenuConfig.isDoBossTrackingPage()) { + bossTrackingPage = pageCounter; + for (TextComponent textComponent : BossTrackingPage.bossTrackingPage(targetPlayer)) { + pages[pageCounter] = textComponent; + pageCounter++; + } + } + + pages[0] = CoverPage.coverPage(statsPage, gearPage, teleportsPage, commandsPage, questsPage, bossTrackingPage); + + int counter = 0; + for (TextComponent textComponent : pages) { + if (textComponent != null) + counter++; + } + + TextComponent[] finalPages = new TextComponent[counter]; + int secondCounter = 0; + for (TextComponent textComponent : pages) { + if (textComponent != null) { + finalPages[secondCounter] = textComponent; + secondCounter++; + } + } + + return BookMaker.generateBook(requestingPlayer, finalPages); + } + + +} diff --git a/src/main/java/com/magmaguy/elitemobs/playerdata/statusscreen/QuestsPage.java b/src/main/java/com/magmaguy/elitemobs/playerdata/statusscreen/QuestsPage.java new file mode 100644 index 000000000..aa1977106 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/playerdata/statusscreen/QuestsPage.java @@ -0,0 +1,16 @@ +package com.magmaguy.elitemobs.playerdata.statusscreen; + +import com.magmaguy.elitemobs.playerdata.database.PlayerData; +import com.magmaguy.elitemobs.quests.menus.QuestMenu; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.entity.Player; + +public class QuestsPage { + protected static TextComponent[] questsPage(Player targetPlayer) { + return QuestMenu.generateQuestEntry(targetPlayer, null); + } + + protected static void questsPage(Player targetPlayer, Player requestingPlayer) { + QuestMenu.generateQuestMenu(PlayerData.getQuests(targetPlayer.getUniqueId()), targetPlayer, null); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/playerdata/statusscreen/StatsPage.java b/src/main/java/com/magmaguy/elitemobs/playerdata/statusscreen/StatsPage.java new file mode 100644 index 000000000..543084ae4 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/playerdata/statusscreen/StatsPage.java @@ -0,0 +1,108 @@ +package com.magmaguy.elitemobs.playerdata.statusscreen; + +import com.magmaguy.elitemobs.adventurersguild.GuildRank; +import com.magmaguy.elitemobs.config.AdventurersGuildConfig; +import com.magmaguy.elitemobs.config.menus.premade.PlayerStatusMenuConfig; +import com.magmaguy.elitemobs.economy.EconomyHandler; +import com.magmaguy.elitemobs.playerdata.database.PlayerData; +import net.md_5.bungee.api.chat.ClickEvent; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import java.util.HashMap; +import java.util.Map; + +public class StatsPage { + private StatsPage() { + } + + protected static TextComponent statsPage(Player targetPlayer) { + + TextComponent textComponent = new TextComponent(); + + for (int i = 0; i < 13; i++) { + TextComponent line = new TextComponent(PlayerStatusMenuConfig.getStatsTextLines()[i] + .replace("$money", EconomyHandler.checkCurrency(targetPlayer.getUniqueId()) + "") + .replace("$guildtier", PlayerStatusScreen.convertLightColorsToBlack(AdventurersGuildConfig.getShortenedRankName(GuildRank.getGuildPrestigeRank(targetPlayer), GuildRank.getActiveGuildRank(targetPlayer)))) + .replace("$kills", PlayerData.getKills(targetPlayer.getUniqueId()) + "") + .replace("$highestkill", PlayerData.getHighestLevelKilled(targetPlayer.getUniqueId()) + "") + .replace("$deaths", PlayerData.getDeaths(targetPlayer.getUniqueId()) + "") + .replace("$quests", PlayerData.getQuestsCompleted(targetPlayer.getUniqueId()) + "") + .replace("$score", PlayerData.getScore(targetPlayer.getUniqueId()) + "") + "\n"); + + if (!PlayerStatusMenuConfig.getStatsHoverLines()[i].isEmpty()) + PlayerStatusScreen.setHoverText(line, PlayerStatusMenuConfig.getStatsHoverLines()[i]); + + if (!PlayerStatusMenuConfig.getStatsCommandLines()[i].isEmpty()) + line.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, PlayerStatusMenuConfig.getStatsCommandLines()[i])); + + textComponent.addExtra(line); + } + + return textComponent; + + } + + protected static void statsPage(Player targetPlayer, Player requestingPlayer) { + Inventory inventory = Bukkit.createInventory(requestingPlayer, 27, PlayerStatusMenuConfig.getStatsChestMenuName()); + inventory.setItem(PlayerStatusMenuConfig.getStatsMoneySlot(), + replaceItemNamePlaceholder(PlayerStatusMenuConfig.getStatsMoneyItem().clone(), "$money", + EconomyHandler.checkCurrency(targetPlayer.getUniqueId()) + "")); + inventory.setItem(PlayerStatusMenuConfig.getStatsGuildTierSlot(), + replaceItemNamePlaceholder(PlayerStatusMenuConfig.getStatsGuildTierItem().clone(), "$tier", + AdventurersGuildConfig.getShortenedRankName(GuildRank.getGuildPrestigeRank(targetPlayer), GuildRank.getActiveGuildRank(targetPlayer)) + "")); + inventory.setItem(PlayerStatusMenuConfig.getStatsEliteKillsSlot(), + replaceItemNamePlaceholder(PlayerStatusMenuConfig.getStatsEliteKillsItem().clone(), "$kills", + PlayerData.getKills(targetPlayer.getUniqueId()) + "")); + inventory.setItem(PlayerStatusMenuConfig.getStatsMaxEliteLevelKilledSlot(), + replaceItemNamePlaceholder(PlayerStatusMenuConfig.getStatsMaxEliteLevelKilledItem().clone(), "$maxKill", + PlayerData.getKills(targetPlayer.getUniqueId()) + "")); + inventory.setItem(PlayerStatusMenuConfig.getStatsEliteDeathsSlot(), + replaceItemNamePlaceholder(PlayerStatusMenuConfig.getStatsEliteDeathsItem().clone(), "$deaths", + PlayerData.getDeaths(targetPlayer.getUniqueId()) + "")); + inventory.setItem(PlayerStatusMenuConfig.getStatsQuestsCompletedSlot(), + replaceItemNamePlaceholder(PlayerStatusMenuConfig.getStatsQuestsCompletedItem().clone(), "$questsCompleted", + PlayerData.getQuestsCompleted(targetPlayer.getUniqueId()) + "")); + inventory.setItem(PlayerStatusMenuConfig.getStatsScoreSlot(), + replaceItemNamePlaceholder(PlayerStatusMenuConfig.getStatsScoreItem().clone(), "$score", + PlayerData.getScore(targetPlayer.getUniqueId()) + "")); + inventory.setItem(26, PlayerStatusMenuConfig.getBackItem()); + requestingPlayer.openInventory(inventory); + StatsPageEvents.pageInventories.put(requestingPlayer, inventory); + } + + private static ItemStack replaceItemNamePlaceholder(ItemStack itemStack, String placeholder, String replacement) { + ItemMeta itemMeta = itemStack.getItemMeta(); + itemMeta.setDisplayName(itemMeta.getDisplayName().replace(placeholder, replacement)); + itemStack.setItemMeta(itemMeta); + return itemStack; + } + + public static class StatsPageEvents implements Listener { + private static final Map pageInventories = new HashMap<>(); + + @EventHandler + public void onInventoryInteract(InventoryClickEvent event) { + Player player = ((Player) event.getWhoClicked()).getPlayer(); + if (!pageInventories.containsKey(player)) return; + event.setCancelled(true); + if (event.getSlot() == 26) { + player.closeInventory(); + CoverPage.coverPage(player); + } + } + + @EventHandler + public void onInventoryClose(InventoryCloseEvent event) { + pageInventories.remove(event.getPlayer()); + } + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/playerdata/statusscreen/TeleportsPage.java b/src/main/java/com/magmaguy/elitemobs/playerdata/statusscreen/TeleportsPage.java new file mode 100644 index 000000000..d32421b12 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/playerdata/statusscreen/TeleportsPage.java @@ -0,0 +1,129 @@ +package com.magmaguy.elitemobs.playerdata.statusscreen; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.commands.DungeonCommands; +import com.magmaguy.elitemobs.config.menus.premade.PlayerStatusMenuConfig; +import com.magmaguy.elitemobs.dungeons.Minidungeon; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import net.md_5.bungee.api.chat.ClickEvent; +import net.md_5.bungee.api.chat.ComponentBuilder; +import net.md_5.bungee.api.chat.HoverEvent; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.Bukkit; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.inventory.Inventory; + +import java.util.*; + + +public class TeleportsPage { + + protected static TextComponent[] teleportsPage() { + TextComponent configTextComponent = new TextComponent(); + //Fills the non-dungeon lines + int textLineCounter = 0; + for (String string : PlayerStatusMenuConfig.getTeleportTextLines()) { + if (string == null || string.equals("null")) + continue; + TextComponent line = new TextComponent(string + "\n"); + if (PlayerStatusMenuConfig.getTeleportHoverLines()[textLineCounter] != null && !PlayerStatusMenuConfig.getTeleportHoverLines()[textLineCounter].isEmpty()) + PlayerStatusScreen.setHoverText(line, PlayerStatusMenuConfig.getTeleportHoverLines()[textLineCounter]); + + if (PlayerStatusMenuConfig.getTeleportCommandLines()[textLineCounter] != null && !PlayerStatusMenuConfig.getTeleportCommandLines()[textLineCounter].isEmpty()) + line.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, PlayerStatusMenuConfig.getTeleportCommandLines()[textLineCounter])); + + configTextComponent.addExtra(line); + textLineCounter++; + } + + //Fills the minidungeon components + int counter = 0; + ArrayList textComponents = new ArrayList<>(); + + for (Minidungeon minidungeon : Minidungeon.getMinidungeons().values()) { + if (!minidungeon.isInstalled()) continue; + + TextComponent message = new TextComponent(PlayerStatusScreen.convertLightColorsToBlack(minidungeon.getDungeonPackagerConfigFields().getName() + "\n")); + String hoverMessage = ChatColorConverter.convert(PlayerStatusMenuConfig.getOnTeleportHover() + "\n" + + minidungeon.getDungeonPackagerConfigFields().getPlayerInfo() + .replace("$bossCount", minidungeon.getRegionalBossCount() + "") + .replace("$lowestTier", minidungeon.getLowestTier() + "") + .replace("$highestTier", minidungeon.getHighestTier() + "")); + message.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new ComponentBuilder(hoverMessage).create())); + message.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, "/elitemobs dungeontp " + minidungeon.getDungeonPackagerConfigFields().getFilename())); + textComponents.add(message); + + counter++; + } + + if (counter == 0) { + TextComponent[] textComponent = new TextComponent[1]; + textComponent[0] = configTextComponent; + return textComponent; + } else { + TextComponent[] textComponent = new TextComponent[(int) Math.floor(counter / 9D) + 1]; + int internalCounter = 0; + textComponent[0] = configTextComponent; + for (TextComponent text : textComponents) { + int currentPage = (int) Math.floor(internalCounter / 9D); + if (textComponent[currentPage] == null) + textComponent[currentPage] = new TextComponent(); + textComponent[currentPage].addExtra(text); + internalCounter++; + } + return textComponent; + } + } + + protected static void teleportsPage(Player targetPlayer, Player requestingPlayer) { + Inventory inventory = Bukkit.createInventory(requestingPlayer, 54, PlayerStatusMenuConfig.getTeleportChestMenuName()); + int counter = 0; + TeleportsPageEvents.orderedDungeons.clear(); + for (Minidungeon minidungeon : Minidungeon.getMinidungeons().values()) { + if (!minidungeon.isInstalled()) continue; + TeleportsPageEvents.orderedDungeons.add(minidungeon); + inventory.setItem(counter, ItemStackGenerator.generateItemStack(Material.PAPER, minidungeon.getDungeonPackagerConfigFields().getName() + , Collections.singletonList(minidungeon.getDungeonPackagerConfigFields().getPlayerInfo() + .replace("$bossCount", minidungeon.getRegionalBossCount() + "") + .replace("$lowestTier", minidungeon.getLowestTier() + "") + .replace("$highestTier", minidungeon.getHighestTier() + "")))); + counter++; + } + inventory.setItem(53, PlayerStatusMenuConfig.getBackItem()); + requestingPlayer.openInventory(inventory); + TeleportsPageEvents.pageInventories.put(requestingPlayer, inventory); + } + + public static class TeleportsPageEvents implements Listener { + private static final Map pageInventories = new HashMap<>(); + private static List orderedDungeons = new ArrayList<>(); + + @EventHandler (ignoreCancelled = true) + public void onInventoryInteract(InventoryClickEvent event) { + Player player = ((Player) event.getWhoClicked()).getPlayer(); + if (!pageInventories.containsKey(player)) return; + event.setCancelled(true); + if (event.getSlot() < 0) return; + if (orderedDungeons.size() - 1 >= event.getSlot()) { + player.closeInventory(); + DungeonCommands.teleport(player, orderedDungeons.get(event.getSlot()).getDungeonPackagerConfigFields().getFilename()); + return; + } + if (event.getSlot() == 53) { + player.closeInventory(); + CoverPage.coverPage(player); + } + } + + @EventHandler + public void onInventoryClose(InventoryCloseEvent event) { + pageInventories.remove(event.getPlayer()); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/BonusCoins.java b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/BonusCoins.java new file mode 100644 index 000000000..6338367eb --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/BonusCoins.java @@ -0,0 +1,39 @@ +package com.magmaguy.elitemobs.powers.bosspowers; + +import com.magmaguy.elitemobs.api.EliteMobDeathEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.items.ItemLootShower; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.playerdata.database.PlayerData; +import com.magmaguy.elitemobs.powers.meta.BossPower; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; + +public class BonusCoins extends BossPower { + private double coinMultiplier = 2D; + + public BonusCoins() { + super(PowersConfig.getPower("bonus_coins.yml")); + } + + public void setCoinMultiplier(double coinMultiplier) { + this.coinMultiplier = coinMultiplier; + } + + public void doCoinDrop(EliteEntity eliteEntity, Player player) { + new ItemLootShower(eliteEntity.getLevel() * coinMultiplier, eliteEntity.getUnsyncedLivingEntity().getLocation(), player); + } + + public static class BonusCoinsEvents implements Listener { + @EventHandler + public void onEliteDeath(EliteMobDeathEvent event) { + BonusCoins bonusCoins = (BonusCoins) event.getEliteEntity().getPower("bonus_coins.yml"); + if (bonusCoins == null) return; + for (Player player : event.getEliteEntity().getDamagers().keySet()) + if (!player.hasMetadata("NPC") && PlayerData.isInMemory(player.getUniqueId())) + if (event.getEliteEntity().getDamagers().get(player) / event.getEliteEntity().getMaxHealth() > 0.1) + bonusCoins.doCoinDrop(event.getEliteEntity(), player); + } + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/BulletHell.java b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/BulletHell.java new file mode 100644 index 000000000..e09b79abf --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/BulletHell.java @@ -0,0 +1,111 @@ +package com.magmaguy.elitemobs.powers.bosspowers; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerEvent; +import com.magmaguy.elitemobs.api.internal.RemovalReason; +import com.magmaguy.elitemobs.combatsystem.EliteProjectile; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.meta.BossPower; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Particle; +import org.bukkit.entity.Arrow; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import java.util.concurrent.ThreadLocalRandom; + +public class BulletHell extends BossPower implements Listener { + public BulletHell() { + super(PowersConfig.getPower("bullet_hell.yml")); + } + + private static void trackingArrowLoop(Player player, Arrow arrow) { + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + if (player.isValid() && !player.isDead() && arrow.isValid() && arrow.getWorld().equals(player.getWorld()) + && player.getLocation().distanceSquared(arrow.getLocation()) < 900 && !arrow.isOnGround()) { + if (counter % 10 == 0) + arrow.setVelocity(arrow.getVelocity().add(arrowAdjustmentVector(arrow, player))); + arrow.getWorld().spawnParticle(Particle.FLAME, arrow.getLocation(), 10, 0.01, 0.01, 0.01, 0.01); + } else { + arrow.setGravity(true); + EntityTracker.unregister(arrow, RemovalReason.EFFECT_TIMEOUT); + cancel(); + } + if (counter > 20 * 10) { + EntityTracker.unregister(arrow, RemovalReason.EFFECT_TIMEOUT); + arrow.setGravity(true); + cancel(); + } + counter++; + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + } + + private static Vector arrowAdjustmentVector(Arrow arrow, Player player) { + return player.getEyeLocation().clone().subtract(new Vector(0, 0.5, 0)).subtract(arrow.getLocation()).toVector().normalize().multiply(0.1); + } + + @EventHandler + public void onDamage(EliteMobDamagedByPlayerEvent event) { + BulletHell bulletHell = (BulletHell) event.getEliteMobEntity().getPower(this); + if (bulletHell == null) return; + if (!eventIsValid(event, bulletHell)) return; + if (ThreadLocalRandom.current().nextDouble() > 0.25) return; + + bulletHell.doGlobalCooldown(20 * 20, event.getEliteMobEntity()); + doBulletHell(event.getEliteMobEntity()); + + } + + public void doBulletHell(EliteEntity eliteEntity) { + eliteEntity.getLivingEntity().setAI(false); + if (eliteEntity.getLivingEntity().getLocation().clone().add(new Vector(0, 10, 0)).getBlock().getType().equals(Material.AIR)) + eliteEntity.getLivingEntity().teleport(eliteEntity.getLivingEntity().getLocation().clone().add(new Vector(0, 10, 0))); + new BukkitRunnable() { + final Location initialLocation = eliteEntity.getLivingEntity().getLocation().clone(); + int counter = 0; + + @Override + public void run() { + + if (!eliteEntity.isValid()) { + cancel(); + return; + } + + eliteEntity.getLivingEntity().getWorld().spawnParticle(Particle.DRIP_WATER, eliteEntity.getLivingEntity().getLocation(), 10, 1, 1, 1); + + for (Entity nearbyEntity : eliteEntity.getLivingEntity().getNearbyEntities(20, 20, 20)) + if (nearbyEntity instanceof Player && + (((Player) nearbyEntity).getGameMode().equals(GameMode.ADVENTURE) || + ((Player) nearbyEntity).getGameMode().equals(GameMode.SURVIVAL))) { + Arrow arrow = (Arrow) EliteProjectile.create(EntityType.ARROW, eliteEntity.getLivingEntity(), (Player) nearbyEntity, false); + arrow.setVelocity(arrow.getVelocity().multiply(0.1)); + trackingArrowLoop((Player) nearbyEntity, arrow); + } + + counter++; + if (counter > 20) { + cancel(); + eliteEntity.getLivingEntity().setAI(true); + eliteEntity.getLivingEntity().teleport(initialLocation); + } + + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 10); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/ChannelHealing.java b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/ChannelHealing.java new file mode 100644 index 000000000..6d4abe01f --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/ChannelHealing.java @@ -0,0 +1,98 @@ +package com.magmaguy.elitemobs.powers.bosspowers; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.meta.CombatEnterScanPower; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.entity.Entity; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + + +public class ChannelHealing extends CombatEnterScanPower { + public ChannelHealing() { + super(PowersConfig.getPower("channel_healing.yml")); + } + + @Override + protected void finishActivation(EliteEntity eliteEntity) { + super.bukkitTask = new BukkitRunnable() { + + @Override + public void run() { + if (doExit(eliteEntity) || isInCooldown(eliteEntity)) { + return; + } + doPower(eliteEntity); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 20 * 2); + } + + private void doPower(EliteEntity eliteEntity) { + for (Entity entity : eliteEntity.getLivingEntity().getNearbyEntities(20, 20, 20)) { + EliteEntity parsedEntity = EntityTracker.getEliteMobEntity(entity); + if (parsedEntity == null) continue; + if (parsedEntity.getHealth() / parsedEntity.getMaxHealth() > .8) continue; + if (parsedEntity.isHealing()) continue; + channelHealing(eliteEntity, parsedEntity); + return; + } + + } + + private void channelHealing(EliteEntity healer, EliteEntity damagedEntity) { + super.setInCooldown(healer, true); + healer.getLivingEntity().setAI(false); + damagedEntity.setHealing(true); + new BukkitRunnable() { + int timer = 0; + + @Override + public void run() { + if (!healer.isValid() || + !damagedEntity.isValid() || + damagedEntity.getHealth() / damagedEntity.getMaxHealth() > .8 || + healer.getLocation().distance(damagedEntity.getLocation()) > 25) { + cancel(); + setInCooldown(healer, false); + doCooldown(healer); + damagedEntity.setHealing(false); + if (healer.isValid()) + healer.getLivingEntity().setAI(true); + return; + } + + if (timer % 10 == 0 && timer > 0) { + double healAmount = healer.getLevel() / 2d; + damagedEntity.heal(healAmount); + damagedEntity.getLocation().getWorld().spawnParticle(Particle.TOTEM, damagedEntity.getLocation().add(new Vector(0, 1, 0)), 20, 0.1, 0.1, 0.1); + } + + Vector toDamaged = damagedEntity.getLocation().add(new Vector(0, 1, 0)) + .subtract(healer.getLocation().add(new Vector(0, 1, 0))) + .toVector().normalize().multiply(.5); + + Location rayLocation = healer.getLocation().add(new Vector(0, 1, 0)).add(toDamaged); + + for (int i = 0; i < 55; i++) { + rayLocation.getWorld().spawnParticle(Particle.TOTEM, rayLocation, 1, toDamaged.getX(), toDamaged.getY(), toDamaged.getZ(), .2D); + rayLocation.add(toDamaged); + if (rayLocation.distance(damagedEntity.getLocation()) < 2) + break; + } + + timer++; + + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0L, 2L); + } + + @Override + protected void finishDeactivation(EliteEntity eliteEntity) { + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/DeathSlice.java b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/DeathSlice.java new file mode 100644 index 000000000..03160a422 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/DeathSlice.java @@ -0,0 +1,97 @@ +package com.magmaguy.elitemobs.powers.bosspowers; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.events.BossCustomAttackDamage; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.meta.BossPower; +import com.magmaguy.elitemobs.powerstances.GenericRotationMatrixMath; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.concurrent.ThreadLocalRandom; + +public class DeathSlice extends BossPower implements Listener { + + public DeathSlice() { + super(PowersConfig.getPower("death_slice.yml")); + } + + private static void doDeathSlice(EliteEntity eliteEntity) { + ArrayList locations = raytracedLocationList(eliteEntity.getLivingEntity().getLocation()); + eliteEntity.getLivingEntity().setAI(false); + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + if (counter > 20 * 5 || !eliteEntity.isValid()) { + if (eliteEntity.getLivingEntity() != null) + eliteEntity.getLivingEntity().setAI(true); + cancel(); + return; + } + + if (counter < 20 * 2.5) { + for (Location location : locations) + doWarningParticle(location); + } else { + for (Location location : locations) + doDamagePhase(location, eliteEntity); + } + + counter++; + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 2); + + } + + private static ArrayList raytracedLocationList(Location originalLocation) { + ArrayList locations = new ArrayList<>(); + int safeSide = ThreadLocalRandom.current().nextInt(16); + for (int i = 0; i < 15; i++) + for (int j = 0; j < 16; j++) + for (int k = 0; k < 2; k++) { + if (safeSide == j) + continue; + locations.add(originalLocation.clone().add(GenericRotationMatrixMath.applyRotation(0, 1, 0, 16, i, 0, 0, j)).add(new Vector(0, k, 0))); + } + + return locations; + } + + private static void doWarningParticle(Location location) { + if (ThreadLocalRandom.current().nextDouble() < 0.3) + location.getWorld().spawnParticle(Particle.SMOKE_LARGE, location, 1, 0.05, 0.05, 0.05, 0.05); + } + + private static void doDamagePhase(Location location, EliteEntity eliteEntity) { + if (ThreadLocalRandom.current().nextDouble() < 0.3) + location.getWorld().spawnParticle(Particle.FLAME, location, 1, 0.1, 0.1, 0.1, 0.05); + for (Entity entity : location.getWorld().getNearbyEntities(location, 0.5, 0.5, 0.5)) + if (entity instanceof LivingEntity && !EntityTracker.isEliteMob(entity)) + BossCustomAttackDamage.dealCustomDamage(eliteEntity.getLivingEntity(), (LivingEntity) entity, 1); + } + + @EventHandler + public void onEliteDamaged(EliteMobDamagedByPlayerEvent event) { + DeathSlice deathSlice = (DeathSlice) event.getEliteMobEntity().getPower(this); + if (deathSlice == null) return; + if (deathSlice.isInGlobalCooldown()) return; + + if (ThreadLocalRandom.current().nextDouble() > 0.10) return; + deathSlice.doGlobalCooldown(20 * 20); + + doDeathSlice(event.getEliteMobEntity()); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/Firestorm.java b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/Firestorm.java new file mode 100644 index 000000000..a0ab69447 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/Firestorm.java @@ -0,0 +1,177 @@ +package com.magmaguy.elitemobs.powers.bosspowers; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.events.BossCustomAttackDamage; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.meta.BossPower; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import java.util.concurrent.ThreadLocalRandom; + +public class Firestorm extends BossPower implements Listener { + + public Firestorm() { + super(PowersConfig.getPower("firestorm.yml")); + } + + private static void doFirestorm(EliteEntity eliteEntity) { + if (eliteEntity == null || !eliteEntity.isValid()) return; + eliteEntity.getLivingEntity().setAI(false); + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + counter++; + + if (counter > 20 * 10 || !eliteEntity.isValid()) { + if (eliteEntity.isValid()) + eliteEntity.getLivingEntity().setAI(true); + cancel(); + return; + } + + if (counter % 5 == 0) { + Location randomLocation = eliteEntity.getLivingEntity().getLocation().add(new Vector( + ThreadLocalRandom.current().nextInt(-20, 20), + 0, + ThreadLocalRandom.current().nextInt(-20, 20) + )); + doFlamePyrePhase1(randomLocation, eliteEntity); + } + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + } + + /** + * Warning phase + */ + private static void doFlamePyrePhase1(Location location, EliteEntity eliteEntity) { + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + counter++; + spawnPhase1Particle(location, Particle.SMOKE_NORMAL); + if (counter < 20 * 2) return; + cancel(); + doFlamePyrePhase2(location, eliteEntity); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + } + + private static void spawnPhase1Particle(Location location, Particle particle) { + for (int i = 0; i < 10; i++) { + location.getWorld().spawnParticle(particle, new Location( + location.getWorld(), + (ThreadLocalRandom.current().nextDouble() - 0.5) * 0.5 + location.getX(), + location.getY(), + (ThreadLocalRandom.current().nextDouble() - 0.5) * 0.5 + location.getZ() + ), 0, 0, 1, 0, ThreadLocalRandom.current().nextDouble() * 2); + } + } + + /** + * First damage phase + */ + private static void doFlamePyrePhase2(Location location, EliteEntity eliteEntity) { + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + counter++; + spawnPhase1Particle(location, Particle.FLAME); + doDamage(location, eliteEntity, 0.5, 50, 0.5); + spawnPhase2Particle(location, Particle.SMOKE_NORMAL); + if (counter < 20 * 2) return; + cancel(); + doFlamePyrePhase3(location, eliteEntity); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + } + + private static void spawnPhase2Particle(Location location, Particle particle) { + for (int i = 0; i < 10; i++) { + location.getWorld().spawnParticle(particle, new Location( + location.getWorld(), + (ThreadLocalRandom.current().nextDouble() - 0.5) * 3 + location.getX(), + location.getY(), + (ThreadLocalRandom.current().nextDouble() - 0.5) * 3 + location.getZ() + ), 0, 0, 1, 0, ThreadLocalRandom.current().nextDouble() * 2); + } + } + + private static void doDamage(Location location, EliteEntity eliteEntity, double range1, double range2, double range3) { + for (Entity entity : location.getWorld().getNearbyEntities(location, range1, range2, range3)) + if (entity instanceof LivingEntity) + BossCustomAttackDamage.dealCustomDamage(eliteEntity.getLivingEntity(), (LivingEntity) entity, 1); + } + + /** + * Second damage phase / last warning phase + */ + private static void doFlamePyrePhase3(Location location, EliteEntity eliteEntity) { + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + counter++; + spawnPhase2Particle(location, Particle.FLAME); + doDamage(location, eliteEntity, 3, 50, 3); + spawnPhase3Particle(location, Particle.SMOKE_NORMAL); + if (counter < 20 * 2) return; + cancel(); + doFlamePyrePhase4(location, eliteEntity); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + } + + private static void spawnPhase3Particle(Location location, Particle particle) { + location.getWorld().spawnParticle(particle, location, 50, 0.01, 0.01, 0.01, 0.1); + } + + /** + * Final/full damage phase + * + * @param eliteEntity + */ + private static void doFlamePyrePhase4(Location location, EliteEntity eliteEntity) { + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + counter++; + spawnPhase3Particle(location, Particle.FLAME); + doDamage(location, eliteEntity, 5, 50, 5); + if (counter < 20 * 2) return; + cancel(); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + } + + @EventHandler + public void onDamage(EliteMobDamagedByPlayerEvent event) { + Firestorm firestorm = (Firestorm) event.getEliteMobEntity().getPower(this); + if (firestorm == null) return; + if (!eventIsValid(event, firestorm)) return; + if (ThreadLocalRandom.current().nextDouble() > 0.25) return; + + firestorm.doGlobalCooldown(20 * 20, event.getEliteMobEntity()); + doFirestorm(event.getEliteMobEntity()); + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/FireworksBarrage.java b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/FireworksBarrage.java new file mode 100644 index 000000000..c3746a464 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/FireworksBarrage.java @@ -0,0 +1,126 @@ +package com.magmaguy.elitemobs.powers.bosspowers; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.explosionregen.Explosion; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.meta.BossPower; +import org.bukkit.*; +import org.bukkit.block.Block; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Firework; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.inventory.meta.FireworkMeta; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +public class FireworksBarrage extends BossPower { + public FireworksBarrage() { + super(PowersConfig.getPower("fireworks_barrage.yml")); + } + + public void doFireworksBarrage(EliteEntity eliteEntity) { + eliteEntity.getLivingEntity().setAI(false); + if (eliteEntity.getLivingEntity().getLocation().clone().add(new Vector(0, 10, 0)).getBlock().getType().equals(Material.AIR)) + if (!eliteEntity.getLivingEntity().getType().equals(EntityType.GHAST)) + eliteEntity.getLivingEntity().teleport(eliteEntity.getLivingEntity().getLocation().clone().add(new Vector(0, 10, 0))); + FireworksBarrage fireworksBarrage = this; + new BukkitRunnable() { + final Location initialLocation = eliteEntity.getLivingEntity().getLocation().clone(); + int counter = 0; + + @Override + public void run() { + + if (!eliteEntity.isValid()) { + cancel(); + return; + } + + for (int i = 0; i < 2; i++) { + Firework firework = (Firework) eliteEntity.getLivingEntity().getWorld().spawnEntity(eliteEntity.getLivingEntity().getLocation(), EntityType.FIREWORK); + FireworkMeta fireworkMeta = firework.getFireworkMeta(); + fireworkMeta.setPower(10); + fireworkMeta.addEffect(FireworkEffect.builder().withColor(Color.RED, Color.WHITE, Color.BLUE).flicker(true).build()); + firework.setFireworkMeta(fireworkMeta); + firework.setVelocity(new Vector(ThreadLocalRandom.current().nextDouble(-0.5, 0.5), + ThreadLocalRandom.current().nextDouble(), ThreadLocalRandom.current().nextDouble(-0.5, 0.5))); + } + + for (Entity nearbyEntity : eliteEntity.getLivingEntity().getNearbyEntities(20, 20, 20)) + if (nearbyEntity instanceof Player) + if (((Player) nearbyEntity).getGameMode().equals(GameMode.ADVENTURE) || + ((Player) nearbyEntity).getGameMode().equals(GameMode.SURVIVAL)) { + Firework firework = (Firework) eliteEntity.getLivingEntity().getWorld().spawnEntity(eliteEntity.getLivingEntity().getLocation(), EntityType.FIREWORK); + FireworkMeta fireworkMeta = firework.getFireworkMeta(); + fireworkMeta.setPower(10); + fireworkMeta.addEffect(FireworkEffect.builder().withColor(Color.RED, Color.WHITE, Color.BLUE).flicker(true).build()); + firework.setFireworkMeta(fireworkMeta); + firework.setVelocity( + ((Player) nearbyEntity).getEyeLocation().clone() + .subtract(firework.getLocation()) + .toVector().normalize().multiply(0.5)); + firework.setShotAtAngle(true); + new FireworkTask(firework, nearbyEntity.getLocation().clone(), eliteEntity, fireworksBarrage); + } + + counter++; + if (counter > 10) { + cancel(); + eliteEntity.getLivingEntity().setAI(true); + eliteEntity.getLivingEntity().teleport(initialLocation); + } + + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 10); + } + + public static class FireworksBarrageEvents implements Listener { + @EventHandler + public void onDamage(EliteMobDamagedByPlayerEvent event) { + FireworksBarrage fireworksBarrage = (FireworksBarrage) event.getEliteMobEntity().getPower(new FireworksBarrage()); + if (fireworksBarrage == null) return; + if (!eventIsValid(event, fireworksBarrage)) return; + if (ThreadLocalRandom.current().nextDouble() > 0.25) return; + + fireworksBarrage.doCooldown(event.getEliteMobEntity()); + fireworksBarrage.doFireworksBarrage(event.getEliteMobEntity()); + } + } + + private class FireworkTask { + public FireworkTask(Firework firework, Location targetLocation, EliteEntity eliteEntity, FireworksBarrage fireworksBarrage) { + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + counter++; + if (firework == null || counter > 20 * 5) { + cancel(); + return; + } + if (firework.getLocation().distanceSquared(targetLocation) < Math.pow(0.01, 2)) { + firework.detonate(); + List blockList = new ArrayList<>(); + for (int x = -1; x < 2; x++) + for (int y = -1; y < 2; y++) + for (int z = -1; z < 2; z++) + blockList.add(firework.getLocation().clone().add(new Vector(x, y, z)).getBlock()); + Explosion.generateFakeExplosion(blockList, eliteEntity.getLivingEntity(), fireworksBarrage, firework.getLocation()); + } + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/FlamePyre.java b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/FlamePyre.java new file mode 100644 index 000000000..cd4d769e0 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/FlamePyre.java @@ -0,0 +1,166 @@ +package com.magmaguy.elitemobs.powers.bosspowers; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.events.BossCustomAttackDamage; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.meta.BossPower; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.concurrent.ThreadLocalRandom; + +public class FlamePyre extends BossPower implements Listener { + + public FlamePyre() { + super(PowersConfig.getPower("flame_pyre.yml")); + } + + @EventHandler + public void onHit(EliteMobDamagedByPlayerEvent event) { + + FlamePyre flamePyre = (FlamePyre) event.getEliteMobEntity().getPower(this); + if (flamePyre == null) return; + if (!eventIsValid(event, flamePyre)) return; + if (ThreadLocalRandom.current().nextDouble() > 0.25) return; + + flamePyre.doGlobalCooldown(20 * 20, event.getEliteMobEntity()); + doFlamePyrePhase1(event.getEliteMobEntity()); + + } + + /** + * Warning phase + */ + private void doFlamePyrePhase1(EliteEntity eliteEntity) { + eliteEntity.getLivingEntity().setAI(false); + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + counter++; + if (!eliteEntity.isValid()) { + cancel(); + return; + } + spawnPhase1Particle(eliteEntity.getLivingEntity().getLocation().clone(), Particle.SMOKE_NORMAL); + if (counter < 20 * 2) return; + cancel(); + doFlamePyrePhase2(eliteEntity); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + } + + private void spawnPhase1Particle(Location location, Particle particle) { + for (int i = 0; i < 10; i++) { + location.getWorld().spawnParticle(particle, new Location( + location.getWorld(), + (ThreadLocalRandom.current().nextDouble() - 0.5) * 0.5 + location.getX(), + location.getY(), + (ThreadLocalRandom.current().nextDouble() - 0.5) * 0.5 + location.getZ() + ), 0, 0, 1, 0, ThreadLocalRandom.current().nextDouble() * 2); + } + } + + /** + * First damage phase + */ + private void doFlamePyrePhase2(EliteEntity eliteEntity) { + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + if (!eliteEntity.isValid()) { + cancel(); + return; + } + counter++; + spawnPhase1Particle(eliteEntity.getLivingEntity().getLocation().clone(), Particle.FLAME); + doDamage(eliteEntity, 0.5, 50, 0.5); + spawnPhase2Particle(eliteEntity.getLivingEntity().getLocation().clone(), Particle.SMOKE_NORMAL); + if (counter < 20 * 2) return; + cancel(); + doFlamePyrePhase3(eliteEntity); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + } + + private void spawnPhase2Particle(Location location, Particle particle) { + for (int i = 0; i < 10; i++) { + location.getWorld().spawnParticle(particle, new Location( + location.getWorld(), + (ThreadLocalRandom.current().nextDouble() - 0.5) * 3 + location.getX(), + location.getY(), + (ThreadLocalRandom.current().nextDouble() - 0.5) * 3 + location.getZ() + ), 0, 0, 1, 0, ThreadLocalRandom.current().nextDouble() * 2); + } + } + + private void doDamage(EliteEntity eliteEntity, double range1, double range2, double range3) { + for (Entity entity : eliteEntity.getLivingEntity().getNearbyEntities(range1, range2, range3)) + if (entity instanceof LivingEntity) + BossCustomAttackDamage.dealCustomDamage(eliteEntity.getLivingEntity(), (LivingEntity) entity, 1); + } + + /** + * Second damage phase / last warning phase + * + * @param eliteEntity + */ + private void doFlamePyrePhase3(EliteEntity eliteEntity) { + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + if (!eliteEntity.isValid()) { + cancel(); + return; + } + counter++; + spawnPhase2Particle(eliteEntity.getLivingEntity().getLocation().clone(), Particle.FLAME); + doDamage(eliteEntity, 3, 50, 3); + spawnPhase3Particle(eliteEntity.getLivingEntity().getLocation().clone(), Particle.SMOKE_NORMAL); + if (counter < 20 * 2) return; + cancel(); + doFlamePyrePhase4(eliteEntity); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + } + + private void spawnPhase3Particle(Location location, Particle particle) { + location.getWorld().spawnParticle(particle, location, 50, 0.01, 0.01, 0.01, 0.1); + } + + /** + * Final/full damage phase + */ + private void doFlamePyrePhase4(EliteEntity eliteEntity) { + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + if (!eliteEntity.isValid()) { + cancel(); + return; + } + counter++; + spawnPhase3Particle(eliteEntity.getLivingEntity().getLocation().clone(), Particle.FLAME); + doDamage(eliteEntity, 5, 50, 5); + if (counter < 20 * 2) return; + cancel(); + eliteEntity.getLivingEntity().setAI(true); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/Flamethrower.java b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/Flamethrower.java new file mode 100644 index 000000000..bc60c41e4 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/Flamethrower.java @@ -0,0 +1,158 @@ +package com.magmaguy.elitemobs.powers.bosspowers; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.events.BossCustomAttackDamage; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.meta.BossPower; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +public class Flamethrower extends BossPower implements Listener { + + public Flamethrower() { + super(PowersConfig.getPower("flamethrower.yml")); + } + + private static List generateDamagePoints(EliteEntity eliteEntity, Location fixedPlayerLocation) { + List locations = new ArrayList<>(); + Location eliteMobLocation = eliteEntity.getLivingEntity().getLocation().clone(); + Vector toPlayerVector = fixedPlayerLocation.clone().subtract(eliteMobLocation).toVector().normalize().multiply(0.5); + for (int i = 0; i < 40; i++) + locations.add(eliteMobLocation.add(toPlayerVector).clone()); + return locations; + } + + private static void doDamage(List locations, EliteEntity eliteEntity) { + for (Location location : locations) + for (Entity entity : location.getWorld().getNearbyEntities(location, 0.5, 0.5, 0.5)) + if (entity instanceof LivingEntity) { + if (eliteEntity.getLivingEntity().equals(entity)) continue; + BossCustomAttackDamage.dealCustomDamage(eliteEntity.getLivingEntity(), (LivingEntity) entity, 1); + } + + } + + /** + * Warning phase + * + * @param eliteEntity + */ + private void doFlamethrowerPhase1(EliteEntity eliteEntity, Location fixedPlayerLocation) { + + eliteEntity.getLivingEntity().setAI(false); + + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + + if (!eliteEntity.isValid()) { + cancel(); + return; + } + + doParticleEffect(eliteEntity, fixedPlayerLocation, Particle.SMOKE_NORMAL); + counter++; + + if (counter < 20 * 2) return; + doFlamethrowerPhase2(eliteEntity, fixedPlayerLocation); + cancel(); + + } + + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + + } + + @EventHandler + public void onHit(EliteMobDamagedByPlayerEvent event) { + + Flamethrower flameThrower = (Flamethrower) event.getEliteMobEntity().getPower(this); + if (flameThrower == null) return; + if (!eventIsValid(event, flameThrower)) return; + if (ThreadLocalRandom.current().nextDouble() > 0.25) return; + + flameThrower.doGlobalCooldown(20 * 20, event.getEliteMobEntity()); + doFlamethrowerPhase1(event.getEliteMobEntity(), event.getPlayer().getLocation().clone()); + + } + + private void doParticleEffect(EliteEntity eliteEntity, Location fixedPlayerLocation, Particle particle) { + Vector directionVector = fixedPlayerLocation.clone().subtract(eliteEntity.getLivingEntity().getLocation()).toVector().normalize(); + for (int i = 0; i < 5; i++) { + eliteEntity.getLivingEntity().getWorld().spawnParticle( + particle, + eliteEntity.getLivingEntity().getEyeLocation().clone().add(directionVector.getX(), -0.5, directionVector.getZ()), + 0, + (ThreadLocalRandom.current().nextDouble() - 0.5) * 0.1 + directionVector.getX(), + (ThreadLocalRandom.current().nextDouble() - 0.5) * 0.1 + directionVector.getY(), + (ThreadLocalRandom.current().nextDouble() - 0.5) * 0.1 + directionVector.getZ(), + ThreadLocalRandom.current().nextDouble() + 0.05); + } + } + + /** + * Damage phase + * + * @param eliteEntity + */ + private void doFlamethrowerPhase2(EliteEntity eliteEntity, Location fixedPlayerLocation) { + List damagePoints = generateDamagePoints(eliteEntity, fixedPlayerLocation); + new BukkitRunnable() { + int timer = 0; + + @Override + public void run() { + if (!eliteEntity.isValid()) { + cancel(); + return; + } + + doParticleEffect(eliteEntity, fixedPlayerLocation, Particle.FLAME); + doDamage(damagePoints, eliteEntity); + timer++; + if (timer < 20 * 3) return; + doFlamethrowerPhase3(eliteEntity, fixedPlayerLocation); + cancel(); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + } + + /** + * Cooldown phase + * + * @param eliteEntity + */ + private void doFlamethrowerPhase3(EliteEntity eliteEntity, Location fixedPlayerLocation) { + new BukkitRunnable() { + int timer = 0; + + @Override + public void run() { + if (!eliteEntity.isValid()) { + cancel(); + return; + } + timer++; + doParticleEffect(eliteEntity, fixedPlayerLocation, Particle.SMOKE_NORMAL); + if (timer < 20) return; + cancel(); + eliteEntity.getLivingEntity().setAI(true); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/FrostCone.java b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/FrostCone.java new file mode 100644 index 000000000..c79de0fc9 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/FrostCone.java @@ -0,0 +1,144 @@ +package com.magmaguy.elitemobs.powers.bosspowers; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerEvent; +import com.magmaguy.elitemobs.api.PlayerDamagedByEliteMobEvent; +import com.magmaguy.elitemobs.combatsystem.EliteProjectile; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.meta.BossPower; +import com.magmaguy.elitemobs.powers.meta.ProjectileTagger; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.NamespacedKey; +import org.bukkit.Particle; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.entity.Projectile; +import org.bukkit.entity.Snowball; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.persistence.PersistentDataType; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import java.util.HashMap; +import java.util.concurrent.ThreadLocalRandom; + +public class FrostCone extends BossPower implements Listener { + + private static final NamespacedKey frostConeSnowballKey = new NamespacedKey(MetadataHandler.PLUGIN, "frost_cone_snowball"); + private static final HashMap frostconePlayer = new HashMap<>(); + + public FrostCone() { + super(PowersConfig.getPower("frost_cone.yml")); + } + + public static void startFrostCone(EliteEntity eliteEntity, Location damager) { + if (eliteEntity == null || eliteEntity.getLivingEntity() == null || !eliteEntity.getLivingEntity().isValid()) + return; + eliteEntity.getLivingEntity().setAI(false); + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + counter++; + + //ending phase + if (counter > 20 * 6 || !isPowerStillValid(eliteEntity, damager)) { + cancel(); + if (eliteEntity.getLivingEntity() != null && !eliteEntity.getLivingEntity().isDead()) + eliteEntity.getLivingEntity().setAI(true); + return; + } + + //warning phase + if (counter < 20 * 3) { + doSmokeEffect(eliteEntity, damager); + return; + } + + //firing phase + for (int i = 0; i < 10; i++) + createSnowball(eliteEntity, damager); + + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + } + + private static void doSmokeEffect(EliteEntity eliteEntity, Location location) { + for (int i = 0; i < 100; i++) { + Vector shotVector = getShotVector(eliteEntity, location); + eliteEntity.getLivingEntity().getWorld().spawnParticle( + Particle.SMOKE_NORMAL, + eliteEntity.getLivingEntity().getLocation().clone().add(new Vector(0, 1, 0)), + 0, + shotVector.getX(), + shotVector.getY(), + shotVector.getZ(), + 0.75); + } + } + + private static boolean isPowerStillValid(EliteEntity eliteEntity, Location playerLocation) { + if (!eliteEntity.isValid()) + return false; + return eliteEntity.getLivingEntity().getWorld().equals(playerLocation.getWorld()); + } + + private static Vector getShotVector(EliteEntity eliteEntity, Location location) { + return location.clone().subtract(eliteEntity.getLivingEntity().getLocation().clone()).toVector() + .normalize() + .add(new Vector( + ThreadLocalRandom.current().nextDouble() * 1 - 0.5, + ThreadLocalRandom.current().nextDouble() * 0.5 - 0.25, + ThreadLocalRandom.current().nextDouble() * 1 - 0.5)) + .normalize(); + } + + private static Snowball createSnowball(EliteEntity eliteEntity, Location location) { + Projectile snowball = EliteProjectile.create(EntityType.SNOWBALL, eliteEntity.getLivingEntity(), getShotVector(eliteEntity, location), false); + ProjectileTagger.tagProjectileWithCustomDamage(snowball, 2); + snowball.getPersistentDataContainer().set(frostConeSnowballKey, PersistentDataType.STRING, "true"); + Bukkit.getScheduler().runTaskLater(MetadataHandler.PLUGIN, snowball::remove, 20L * 3); + return (Snowball) snowball; + } + + @EventHandler + public void onDamagedEvent(EliteMobDamagedByPlayerEvent event) { + FrostCone frostCone = (FrostCone) event.getEliteMobEntity().getPower(this); + if (frostCone == null) return; + if (frostCone.isInGlobalCooldown()) return; + + frostCone.doGlobalCooldown(20 * 10, event.getEliteMobEntity()); + + frostCone.setFiring(true); + startFrostCone(event.getEliteMobEntity(), event.getPlayer().getLocation().clone()); + } + + @EventHandler(ignoreCancelled = true) + public void playerHitByFrostConeSnowball(PlayerDamagedByEliteMobEvent event) { + if (event.getProjectile() == null) return; + if (!event.getProjectile().getPersistentDataContainer().has(frostConeSnowballKey, PersistentDataType.STRING)) + return; + if (!frostconePlayer.containsKey(event.getPlayer())) + frostconePlayer.put(event.getPlayer(), 1); + else + frostconePlayer.put(event.getPlayer(), frostconePlayer.get(event.getPlayer()) + 1); + event.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 20 * 7, frostconePlayer.get(event.getPlayer()))); + new BukkitRunnable() { + final int amount = frostconePlayer.get(event.getPlayer()); + + @Override + public void run() { + if (!frostconePlayer.containsKey(event.getPlayer())) return; + if (amount != frostconePlayer.get(event.getPlayer())) return; + frostconePlayer.remove(event.getPlayer()); + } + }.runTaskLater(MetadataHandler.PLUGIN, 20L * 5); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/GoldExplosion.java b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/GoldExplosion.java new file mode 100644 index 000000000..496eb630f --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/GoldExplosion.java @@ -0,0 +1,93 @@ +package com.magmaguy.elitemobs.powers.bosspowers; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerEvent; +import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.meta.BossPower; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import org.bukkit.Material; +import org.bukkit.Particle; +import org.bukkit.entity.Item; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +public class GoldExplosion extends BossPower implements Listener { + + public GoldExplosion() { + super(PowersConfig.getPower("gold_explosion.yml")); + } + + @EventHandler + public void onHit(EliteMobDamagedByPlayerEvent event) { + + GoldExplosion goldExplosion = (GoldExplosion) event.getEliteMobEntity().getPower(this); + if (goldExplosion == null) return; + if (!eventIsValid(event, goldExplosion)) return; + if (ThreadLocalRandom.current().nextDouble() > 0.25) return; + + goldExplosion.doGlobalCooldown(20 * 20, event.getEliteMobEntity()); + doGoldExplosion(event.getEliteMobEntity()); + + } + + private void doGoldExplosion(EliteEntity eliteEntity) { + + eliteEntity.getLivingEntity().setAI(false); + + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + if (!eliteEntity.isValid()) { + cancel(); + return; + } + + counter++; + if (MobCombatSettingsConfig.isEnableWarningVisualEffects()) + eliteEntity.getLivingEntity().getWorld().spawnParticle(Particle.SMOKE_NORMAL, eliteEntity.getLivingEntity().getLocation(), counter, 1, 1, 1, 0); + + if (counter < 20 * 1.5) return; + cancel(); + eliteEntity.getLivingEntity().setAI(true); + List goldNuggets = generateVisualItems(eliteEntity); + ProjectileDamage.doGoldNuggetDamage(goldNuggets, eliteEntity); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + + } + + private List generateVisualItems(EliteEntity eliteEntity) { + List visualItemsList = new ArrayList<>(); + for (int i = 0; i < 200; i++) { + Vector velocityVector = new Vector( + ThreadLocalRandom.current().nextDouble() - 0.5, + ThreadLocalRandom.current().nextDouble() / 1.5, + ThreadLocalRandom.current().nextDouble() - 0.5); + + Item visualProjectile = eliteEntity.getLivingEntity().getWorld().dropItem( + eliteEntity.getLivingEntity().getLocation().clone() + .add(new Vector(velocityVector.getX(), + 0.5, + velocityVector.getZ())), + ItemStackGenerator.generateItemStack( + Material.GOLD_NUGGET, + "visual projectile", + Arrays.asList(ThreadLocalRandom.current().nextDouble() + ""))); + ProjectileDamage.configureVisualProjectile(visualProjectile); + visualProjectile.setVelocity(velocityVector); + visualItemsList.add(visualProjectile); + } + return visualItemsList; + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/GoldShotgun.java b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/GoldShotgun.java new file mode 100644 index 000000000..2cffc40ea --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/GoldShotgun.java @@ -0,0 +1,119 @@ +package com.magmaguy.elitemobs.powers.bosspowers; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.meta.BossPower; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.Particle; +import org.bukkit.entity.Item; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +public class GoldShotgun extends BossPower implements Listener { + + public GoldShotgun() { + super(PowersConfig.getPower("gold_shotgun.yml")); + } + + @EventHandler + public void onHit(EliteMobDamagedByPlayerEvent event) { + + GoldShotgun goldShotgun = (GoldShotgun) event.getEliteMobEntity().getPower(this); + if (goldShotgun == null) return; + if (!eventIsValid(event, goldShotgun)) return; + if (ThreadLocalRandom.current().nextDouble() > 0.25) return; + + goldShotgun.doGlobalCooldown(20 * 20, event.getEliteMobEntity()); + goldShotgun.doGoldShotgun(event.getEliteMobEntity(), event.getPlayer()); + + } + + private void doGoldShotgun(EliteEntity eliteEntity, Player player) { + + eliteEntity.getLivingEntity().setAI(false); + + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + + if (!eliteEntity.isValid()) { + cancel(); + return; + } + + doSmokeEffect(eliteEntity, player); + counter++; + + if (counter < 20 * 3) return; + + cancel(); + eliteEntity.getLivingEntity().setAI(true); + List nuggetList = generateVisualItems(eliteEntity, player); + if (nuggetList == null) return; + ProjectileDamage.doGoldNuggetDamage(nuggetList, eliteEntity); + + } + + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + + } + + private void doSmokeEffect(EliteEntity eliteEntity, Player player) { + for (int i = 0; i < 200; i++) { + Vector shotVector = getShotVector(eliteEntity, player); + if (shotVector == null) return; + eliteEntity.getLivingEntity().getWorld().spawnParticle( + Particle.SMOKE_NORMAL, + eliteEntity.getLivingEntity().getLocation().clone().add(new Vector(0, 0.5, 0)), + 0, + shotVector.getX(), + shotVector.getY(), + shotVector.getZ(), + 0.75); + } + } + + private List generateVisualItems(EliteEntity eliteEntity, Player player) { + List nuggetList = new ArrayList<>(); + if (getShotVector(eliteEntity, player) == null) return null; + for (int i = 0; i < 200; i++) { + Item visualProjectile = eliteEntity.getLivingEntity().getWorld().dropItem( + eliteEntity.getLivingEntity().getLocation(), + ItemStackGenerator.generateItemStack( + Material.GOLD_NUGGET, + "visual projectile", + Arrays.asList(ThreadLocalRandom.current().nextDouble() + ""))); + ProjectileDamage.configureVisualProjectile(visualProjectile); + visualProjectile.setVelocity(getShotVector(eliteEntity, player).multiply(0.9)); + visualProjectile.setGravity(false); + nuggetList.add(visualProjectile); + } + return nuggetList; + } + + private Vector getShotVector(EliteEntity eliteEntity, Player player) { + if (!player.getLocation().getWorld().equals(eliteEntity.getLivingEntity().getLocation())) return null; + return player.getLocation().clone() + .add(new Location(player.getWorld(), 0.0, 1.0, 0.0)) + .add(new Location(player.getWorld(), + ThreadLocalRandom.current().nextDouble() * 2 - 1, + ThreadLocalRandom.current().nextDouble() * 2 - 1, + ThreadLocalRandom.current().nextDouble() * 2 - 1)) + .subtract(eliteEntity.getLivingEntity().getLocation()).toVector().normalize(); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/HyperLoot.java b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/HyperLoot.java new file mode 100644 index 000000000..426310754 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/HyperLoot.java @@ -0,0 +1,23 @@ +package com.magmaguy.elitemobs.powers.bosspowers; + +import com.magmaguy.elitemobs.api.EliteMobDeathEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.items.LootTables; +import com.magmaguy.elitemobs.powers.meta.BossPower; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; + +public class HyperLoot extends BossPower implements Listener { + + public HyperLoot() { + super(PowersConfig.getPower("hyper_loot.yml")); + } + + @EventHandler + public void onEliteMobDeath(EliteMobDeathEvent event) { + if (!event.getEliteEntity().hasPower(this)) return; + for (int i = 0; i < 10; i++) + LootTables.generatePlayerLoot(event.getEliteEntity()); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/LightningBolts.java b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/LightningBolts.java new file mode 100644 index 000000000..a4214691e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/LightningBolts.java @@ -0,0 +1,81 @@ +package com.magmaguy.elitemobs.powers.bosspowers; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerEvent; +import com.magmaguy.elitemobs.collateralminecraftchanges.LightningSpawnBypass; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.meta.BossPower; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + + +public class LightningBolts extends BossPower implements Listener { + + public LightningBolts() { + super(PowersConfig.getPower("lightning_bolts.yml")); + } + + private static void setLightiningPaths(EliteEntity eliteEntity) { + if (eliteEntity.getLivingEntity() == null) return; + eliteEntity.getLivingEntity().setAI(false); + for (Entity entity : eliteEntity.getLivingEntity().getNearbyEntities(20, 20, 20)) { + if (entity.getType().equals(EntityType.PLAYER)) { + Location playerLocationClone = entity.getLocation().clone(); + Location powerLocation = eliteEntity.getLivingEntity().getLocation().clone(); + Vector powerDirection = playerLocationClone.clone().subtract(powerLocation).toVector().normalize(); + int counter = 0; + while (playerLocationClone.distance(powerLocation) > 0.55) { + counter++; + powerLocation.add(powerDirection); + lightningTask(powerLocation.clone(), counter); + } + } + } + new BukkitRunnable() { + @Override + public void run() { + if (eliteEntity != null && eliteEntity.getLivingEntity() != null) + eliteEntity.getLivingEntity().setAI(true); + } + }.runTaskLater(MetadataHandler.PLUGIN, 4L * 20); + } + + public static void lightningTask(Location location, int counter) { + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + counter++; + if (counter > 20 * 2) { + LightningSpawnBypass.bypass(); + location.getWorld().strikeLightning(location); + cancel(); + return; + } + location.getWorld().spawnParticle(Particle.CRIT, location, 10, 0.5, 1.5, 0.5, 0.3); + } + }.runTaskTimer(MetadataHandler.PLUGIN, counter * 5L, 1); + + } + + @EventHandler + public void onDamagedEvent(EliteMobDamagedByPlayerEvent event) { + LightningBolts lightningBolts = (LightningBolts) event.getEliteMobEntity().getPower(this); + if (lightningBolts == null) return; + if (lightningBolts.isInGlobalCooldown()) return; + + lightningBolts.doGlobalCooldown(20 * PowersConfig.getPower("attack_lightning.yml").getFileConfiguration().getInt("delayBetweenStrikes")); + + lightningBolts.setFiring(true); + setLightiningPaths(event.getEliteMobEntity()); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/MeteorShower.java b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/MeteorShower.java new file mode 100644 index 000000000..26984adce --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/MeteorShower.java @@ -0,0 +1,94 @@ +package com.magmaguy.elitemobs.powers.bosspowers; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.meta.BossPower; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Fireball; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import java.util.concurrent.ThreadLocalRandom; + +public class MeteorShower extends BossPower implements Listener { + public MeteorShower() { + super(PowersConfig.getPower("meteor_shower.yml")); + } + + public static void doMeteorShower(EliteEntity eliteEntity) { + eliteEntity.getLivingEntity().setAI(false); + new BukkitRunnable() { + final Location initialLocation = eliteEntity.getLivingEntity().getLocation().clone(); + int counter = 0; + + @Override + public void run() { + + if (!eliteEntity.isValid()) { + cancel(); + return; + } + + if (counter > 10 * 20) { + cancel(); + eliteEntity.getLivingEntity().setAI(true); + eliteEntity.getLivingEntity().teleport(initialLocation); + return; + } + + counter++; + + doCloudEffect(eliteEntity.getLivingEntity().getLocation().clone().add(new Vector(0, 10, 0))); + + if (counter > 2 * 20) { + + doFireballs(eliteEntity.getLivingEntity().getLocation().clone().add(new Vector(0, 10, 0)), eliteEntity); + + } + + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + } + + public static void doCloudEffect(Location location) { + for (int i = 0; i < 1; i++) { + int randX = ThreadLocalRandom.current().nextInt(30) - 15; + int randY = ThreadLocalRandom.current().nextInt(2); + int randZ = ThreadLocalRandom.current().nextInt(30) - 15; + Location newLocation = location.clone().add(new Vector(randX, randY, randZ)); + location.getWorld().spawnParticle(Particle.EXPLOSION_HUGE, newLocation, 1, 0, 0, 0, 0); + } + } + + private static void doFireballs(Location location, EliteEntity eliteEntity) { + for (int i = 0; i < 1; i++) { + int randX = ThreadLocalRandom.current().nextInt(30) - 15; + int randY = ThreadLocalRandom.current().nextInt(2); + int randZ = ThreadLocalRandom.current().nextInt(30) - 15; + Location newLocation = location.clone().add(new Vector(randX, randY, randZ)); + newLocation = newLocation.setDirection(new Vector(ThreadLocalRandom.current().nextDouble() - 0.5, -0.5, ThreadLocalRandom.current().nextDouble() - 0.5)); + Fireball fireball = (Fireball) location.getWorld().spawnEntity(newLocation, EntityType.FIREBALL); + fireball.setShooter(eliteEntity.getLivingEntity()); + fireball.setDirection(fireball.getDirection().multiply(0.5)); + } + } + + @EventHandler + public void onDamage(EliteMobDamagedByPlayerEvent event) { + MeteorShower meteorShower = (MeteorShower) event.getEliteMobEntity().getPower(this); + if (meteorShower == null) return; + if (!eventIsValid(event, meteorShower)) return; + if (ThreadLocalRandom.current().nextDouble() > 0.25) return; + + meteorShower.doGlobalCooldown(20 * 20, event.getEliteMobEntity()); + doMeteorShower(event.getEliteMobEntity()); + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/PhotonRay.java b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/PhotonRay.java new file mode 100644 index 000000000..989c8adbc --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/PhotonRay.java @@ -0,0 +1,178 @@ +package com.magmaguy.elitemobs.powers.bosspowers; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.events.BossCustomAttackDamage; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.meta.CombatEnterScanPower; +import com.magmaguy.elitemobs.utils.WarningMessage; +import org.bukkit.Color; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +public class PhotonRay extends CombatEnterScanPower { + + private int range = 60; + private List playerLocations = new ArrayList<>(5); + private int tickCounter = 0; + + public PhotonRay() { + super(PowersConfig.getPower("photon_ray.yml")); + } + + private void doDamage(Location location, EliteEntity eliteEntity) { + for (Entity entity : location.getWorld().getNearbyEntities(location, 0.5, 0.5, 0.5)) + if (entity instanceof LivingEntity) { + if (eliteEntity.getLivingEntity().equals(entity)) continue; + BossCustomAttackDamage.dealCustomDamage(eliteEntity.getLivingEntity(), (LivingEntity) entity, 1); + } + + tickCounter++; + + } + + @Override + protected void finishActivation(EliteEntity eliteEntity) { + super.bukkitTask = new BukkitRunnable() { + @Override + public void run() { + if (doExit(eliteEntity) || isInCooldown(eliteEntity)) { + return; + } + doPower(eliteEntity); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + } + + private void doPower(EliteEntity eliteEntity) { + doCooldown(eliteEntity); + for (Entity entity : eliteEntity.getLivingEntity().getNearbyEntities(60, 60, 60)) + if (entity.getType().equals(EntityType.PLAYER)) { + if (((Player) entity).getGameMode().equals(GameMode.SPECTATOR)) continue; + //Vector shotVector = entity.getLocation().subtract(eliteEntity.getLivingEntity().getLocation()).toVector().normalize().multiply(0.5); + createRay((Player) entity, eliteEntity.getLocation(), eliteEntity); + break; + } + } + + private void createRay(Player target, Location sourceLocation, EliteEntity sourceEntity) { + sourceEntity.getLivingEntity().setAI(false); + + new BukkitRunnable() { + int counter = 0; + Vector laserVector = generateRayVector(sourceLocation, target.getLocation()); + + @Override + public void run() { + if (counter > 30 || + !target.isValid() || + !target.getLocation().getWorld().equals(sourceLocation.getWorld()) || + target.getLocation().distanceSquared(sourceLocation) > range * range || + !sourceEntity.isValid()) { + if (sourceEntity.getLivingEntity() != null) + sourceEntity.getLivingEntity().setAI(true); + cancel(); + return; + } + + laserVector = dragTarget(laserVector, sourceEntity.getLocation(), target.getLocation()); + + if (counter < 20 / 4d) { + doRaytraceLaser(laserVector, sourceEntity.getLocation(), true, sourceEntity); + } else { + doRaytraceLaser(laserVector, sourceEntity.getLocation(), false, sourceEntity); + } + + counter++; + + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 2); + } + + private void doRaytraceLaser(Vector laserVector, Location source, boolean warningPhase, EliteEntity eliteEntity) { + Location cloneLocation = source.clone().add(new Vector(0, 1, 0)); + for (int i = 0; i < range * 2; i++) { + if (!cloneLocation.clone().add(laserVector).getBlock().isPassable()) { + Vector tentativeDistance = cloneLocation.clone().add(laserVector).getBlock().getLocation().add(new Vector(0.5, 0.5, 0.5)) + .subtract(cloneLocation.clone()).toVector(); + double x = laserVector.getX(), y = laserVector.getY(), z = laserVector.getZ(); + double xAbs = Math.abs(tentativeDistance.getX()), yAbs = Math.abs(tentativeDistance.getY()), zAbs = Math.abs(tentativeDistance.getZ()); + if (xAbs > yAbs && xAbs > zAbs) + x *= -1; + else if (yAbs > xAbs && yAbs > zAbs) + y *= -1; + else if (zAbs > yAbs && zAbs > xAbs) + z *= -1; + else new WarningMessage("MagmaGuy is bad at math!"); + laserVector.setX(x); + laserVector.setY(y); + laserVector.setZ(z); + } + if (warningPhase) + doWarningParticle(cloneLocation.add(laserVector)); + else + doDamageParticles(eliteEntity, cloneLocation.add(laserVector)); + } + } + + private Vector generateRayVector(Location source, Location target) { + return target.clone().add(new Vector(0, 1, 0)) + .subtract(source.clone().add(new Vector(0, 1, 0))).toVector().normalize().multiply(.5); + } + + private Vector dragTarget(Vector originalVector, Location sourceLocation, Location targetLocation) { + if (playerLocations.size() < 5) { + playerLocations.add(targetLocation); + return originalVector; + } + + Location oldTarget = playerLocations.get(0); + Vector newVector = generateRayVector(sourceLocation, oldTarget); + + playerLocations.remove(0); + List newLocation = new ArrayList<>(playerLocations); + newLocation.add(targetLocation); + playerLocations = newLocation; + + + return newVector; + } + + private void doWarningParticle(Location location) { + location.getWorld().spawnParticle(Particle.REDSTONE, location.getX(), location.getY(), location.getZ(), + 5, 0.2, 0.2, 0.2, + 1, new Particle.DustOptions(Color.BLACK, 1)); + } + + private void doDamageParticles(EliteEntity eliteEntity, Location location) { + location.getWorld().spawnParticle(Particle.REDSTONE, location.getX(), location.getY(), location.getZ(), + 5, 0.2, 0.2, 0.2, + 1, new Particle.DustOptions(Color.fromRGB( + ThreadLocalRandom.current().nextInt(0, 100), + ThreadLocalRandom.current().nextInt(0, 100), + ThreadLocalRandom.current().nextInt(100, 255) + ), 1)); + for (Entity entity : location.getWorld().getNearbyEntities(location, 0.25, 0.25, 0.25)) + if (entity.getType() == EntityType.PLAYER) + doDamage(location, eliteEntity); + + + } + + + @Override + protected void finishDeactivation(EliteEntity eliteEntity) { + + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/PlasmaBlaster.java b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/PlasmaBlaster.java new file mode 100644 index 000000000..6055f84be --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/PlasmaBlaster.java @@ -0,0 +1,108 @@ +package com.magmaguy.elitemobs.powers.bosspowers; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.meta.CombatEnterScanPower; +import org.bukkit.Color; +import org.bukkit.GameMode; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import java.util.concurrent.ThreadLocalRandom; + + +public class PlasmaBlaster extends CombatEnterScanPower { + + public PlasmaBlaster() { + super(PowersConfig.getPower("plasma_blaster.yml")); + } + + + @Override + protected void finishActivation(EliteEntity eliteEntity) { + super.bukkitTask = new BukkitRunnable() { + @Override + public void run() { + if (doExit(eliteEntity) || isInCooldown(eliteEntity)) { + return; + } + doPower(eliteEntity); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 20 * 4); + } + + private void doPower(EliteEntity eliteEntity) { + for (Entity entity : eliteEntity.getLivingEntity().getNearbyEntities(30, 30, 30)) + if (entity.getType().equals(EntityType.PLAYER)) { + if (((Player) entity).getGameMode().equals(GameMode.SPECTATOR)) continue; + Vector shotVector = entity.getLocation().subtract(eliteEntity.getLivingEntity().getLocation()).toVector().normalize().multiply(0.5); + createProjectile(shotVector, eliteEntity.getLocation(), eliteEntity); + break; + } + } + + private void createProjectile(Vector shotVector, Location sourceLocation, EliteEntity sourceEntity) { + new BukkitRunnable() { + int counter = 0; + Location currentLocation = sourceLocation.clone().add(new Vector(0, 1, 0)); + + @Override + public void run() { + if (counter > 20 * 3) { + cancel(); + return; + } + counter++; + for (Entity entity : currentLocation.getWorld().getNearbyEntities(currentLocation, 0.1 * counter / 12d, 0.1 * counter / 12d, 0.1 * counter / 12d)) { + if (entity.equals(sourceEntity.getLivingEntity())) continue; + if (!(entity instanceof LivingEntity)) continue; + cancel(); + if (entity.getType() == EntityType.PLAYER) doDamage((Player) entity, sourceEntity); + break; + } + + doVisualEffect(currentLocation, counter); + + currentLocation.add(shotVector); + if (!currentLocation.getBlock().isPassable()) cancel(); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + } + + private void doDamage(Player player, EliteEntity sourceEntity) { + player.damage(1, sourceEntity.getLivingEntity()); + doDamageFireworks(player.getLocation().clone().add(new Vector(0, 1, 0))); + } + + private void doDamageFireworks(Location endLocation) { + for (int i = 0; i < 200; i++) { + endLocation.getWorld().spawnParticle(Particle.REDSTONE, endLocation.getX(), endLocation.getY(), endLocation.getZ(), + 1, 3, 3, 3, + 1, new Particle.DustOptions(Color.fromRGB( + ThreadLocalRandom.current().nextInt(122, 255), + ThreadLocalRandom.current().nextInt(122, 255), + ThreadLocalRandom.current().nextInt(0, 100) + ), 1)); + } + } + + private void doVisualEffect(Location location, int counter) { + location.getWorld().spawnParticle(Particle.REDSTONE, location.getX(), location.getY(), location.getZ(), + 20, 0.1 * counter / 12d, 0.1 * counter / 12d, 0.1 * counter / 12d, 1, new Particle.DustOptions(Color.fromRGB( + ThreadLocalRandom.current().nextInt(0, 100), + ThreadLocalRandom.current().nextInt(122, 255), + ThreadLocalRandom.current().nextInt(0, 100) + ), 1)); + } + + protected void finishDeactivation(EliteEntity eliteEntity) { + + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/ProjectileDamage.java b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/ProjectileDamage.java new file mode 100644 index 000000000..ac0fa90f7 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/ProjectileDamage.java @@ -0,0 +1,80 @@ +package com.magmaguy.elitemobs.powers.bosspowers; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.events.BossCustomAttackDamage; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Item; +import org.bukkit.entity.LivingEntity; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.Iterator; +import java.util.List; + +public class ProjectileDamage { + + public static void doGoldNuggetDamage(List goldNuggets, EliteEntity eliteEntity) { + + new BukkitRunnable() { + + int timer = 0; + + @Override + public void run() { + + timer++; + if (goldNuggets.isEmpty()) { + cancel(); + return; + } + + for (Iterator iterator = goldNuggets.iterator(); iterator.hasNext(); ) { + Item goldNugget = iterator.next(); + if (goldNugget == null) { + iterator.remove(); + continue; + } + boolean removed = false; + for (Entity entity : goldNugget.getNearbyEntities(0.1, 0.1, 0.1)) + if (entity != eliteEntity.getLivingEntity()) + if (entity instanceof LivingEntity) { + BossCustomAttackDamage.dealCustomDamage(eliteEntity.getLivingEntity(), (LivingEntity) entity, 1); + removed = true; + } + + if (removed) { + iterator.remove(); + goldNugget.remove(); + } + + if (!removed && goldNugget.isOnGround()) { + iterator.remove(); + goldNugget.remove(); + } + } + + if (timer < 5 * 20) return; + + for (Iterator endIterator = goldNuggets.iterator(); endIterator.hasNext(); ) { + Item goldNugget = endIterator.next(); + goldNugget.remove(); + endIterator.remove(); + } + + cancel(); + + } + + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + + } + + public static void configureVisualProjectile(Item goldNugget) { + + EntityTracker.registerVisualEffects(goldNugget); + goldNugget.setPickupDelay(Integer.MAX_VALUE); + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/SpiritWalk.java b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/SpiritWalk.java new file mode 100644 index 000000000..61b38e7b5 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/SpiritWalk.java @@ -0,0 +1,269 @@ +package com.magmaguy.elitemobs.powers.bosspowers; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobDamagedEvent; +import com.magmaguy.elitemobs.api.EliteMobExitCombatEvent; +import com.magmaguy.elitemobs.combatsystem.antiexploit.PreventMountExploit; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import com.magmaguy.elitemobs.powers.meta.BossPower; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Mob; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import java.util.concurrent.ThreadLocalRandom; + +public class SpiritWalk extends BossPower implements Listener { + + private int hitCounter = 0; + + public SpiritWalk() { + super(PowersConfig.getPower("spirit_walk.yml")); + } + + public static void spiritWalkAnimation(EliteEntity eliteEntity, Location entityLocation, Location finalLocation) { + + eliteEntity.getLivingEntity().setAI(false); + eliteEntity.getLivingEntity().setInvulnerable(true); + eliteEntity.getLivingEntity().addPotionEffect(new PotionEffect(PotionEffectType.GLOWING, 20 * 10, 1)); + Vector toDestination = finalLocation.clone().subtract(entityLocation.clone()).toVector().normalize().divide(new Vector(2, 2, 2)); + eliteEntity.setCombatGracePeriod(20 * 20); + + new BukkitRunnable() { + + int counter = 0; + + @Override + public void run() { + + if (!eliteEntity.isValid()) { + cancel(); + return; + } + + if (eliteEntity.getLivingEntity().getLocation().clone().distance(finalLocation) < 2 || counter > 20 * 10) { + + eliteEntity.getLivingEntity().teleport(finalLocation); + eliteEntity.getLivingEntity().setAI(true); + eliteEntity.getLivingEntity().setInvulnerable(false); + eliteEntity.getLivingEntity().removePotionEffect(PotionEffectType.GLOWING); + cancel(); + + } + + eliteEntity.getLivingEntity().teleport(eliteEntity.getLivingEntity().getLocation().clone().add(toDestination.clone())); + + counter++; + + } + + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + + } + + public static void spiritWalkRegionalBossAnimation(EliteEntity eliteEntity, Location entityLocation, Location finalLocation) { + + eliteEntity.getLivingEntity().setAI(false); + eliteEntity.getLivingEntity().setInvulnerable(true); + Vector toDestination = finalLocation.clone().subtract(entityLocation.clone()).toVector().normalize().divide(new Vector(2, 2, 2)); + + Entity vehicle = null; + + if (eliteEntity.getLivingEntity().isInsideVehicle()) { + vehicle = eliteEntity.getLivingEntity().getVehicle(); + if (vehicle instanceof LivingEntity) + ((LivingEntity) vehicle).setAI(false); + vehicle.setInvulnerable(true); + if (((CustomBossEntity) eliteEntity).getPhaseBossEntity() != null) + vehicle.remove(); + } + + new BukkitRunnable() { + final Entity vehicle = eliteEntity.getLivingEntity().getVehicle(); + + int counter = 0; + + @Override + public void run() { + if (!eliteEntity.isValid()) { + cancel(); + return; + } + + if (eliteEntity.getLivingEntity().isInsideVehicle()) + eliteEntity.getLivingEntity().leaveVehicle(); + + if (eliteEntity.getLivingEntity().getLocation().clone().distance(finalLocation) < 2 || counter > 20 * 10) { + + eliteEntity.getLivingEntity().setAI(true); + eliteEntity.getLivingEntity().setInvulnerable(false); + + if (vehicle != null && !vehicle.isDead()) + vehicle.teleport(finalLocation); + eliteEntity.getLivingEntity().teleport(finalLocation); + + if (vehicle != null && !vehicle.isDead()) { + if (vehicle instanceof LivingEntity) { + ((LivingEntity) vehicle).setAI(true); + EliteEntity vehicleBoss = EntityTracker.getEliteMobEntity(vehicle); + if (vehicleBoss != null) + Bukkit.getServer().getPluginManager().callEvent(new EliteMobExitCombatEvent(vehicleBoss, EliteMobExitCombatEvent.EliteMobExitCombatReason.SPIRIT_WALK)); + + } + + vehicle.setInvulnerable(false); + new BukkitRunnable() { + @Override + public void run() { + PreventMountExploit.bypass = true; + vehicle.addPassenger(eliteEntity.getLivingEntity()); + } + }.runTaskLater(MetadataHandler.PLUGIN, 1); + } + cancel(); + + Bukkit.getServer().getPluginManager().callEvent(new EliteMobExitCombatEvent(eliteEntity, EliteMobExitCombatEvent.EliteMobExitCombatReason.SPIRIT_WALK)); + if (eliteEntity.getLivingEntity() instanceof Mob) + if (((Mob) eliteEntity.getLivingEntity()).getTarget() == null) + eliteEntity.getLivingEntity().addPotionEffect(new PotionEffect(PotionEffectType.SLOW, Integer.MAX_VALUE, 2)); + + } + + if (vehicle != null && !vehicle.isDead()) { + vehicle.teleport(eliteEntity.getLivingEntity().getLocation().clone().add(toDestination.clone())); + } + eliteEntity.getLivingEntity().teleport(eliteEntity.getLivingEntity().getLocation().clone().add(toDestination.clone())); + + counter++; + + } + + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + + } + + private void incrementHitCounter() { + hitCounter++; + } + + private void resetHitsCounter() { + hitCounter = 0; + } + + private int getHitsCounter() { + return hitCounter; + } + + @EventHandler + public void onBossMobGotHit(EliteMobDamagedEvent event) { + if (event.isCancelled()) return; + if (!event.getEliteMobEntity().hasPower(this)) return; + switch (event.getEntityDamageEvent().getCause()) { + case FIRE: + case FIRE_TICK: + case POISON: + case WITHER: + case THORNS: + case ENTITY_SWEEP_ATTACK: + return; + } + SpiritWalk spiritWalk = (SpiritWalk) event.getEliteMobEntity().getPower(this); + + if (event.getEntityDamageEvent().getCause().equals(EntityDamageEvent.DamageCause.DROWNING) || + event.getEntityDamageEvent().getCause().equals(EntityDamageEvent.DamageCause.SUFFOCATION)) + initializeSpiritWalk(event.getEliteMobEntity()); + + + spiritWalk.incrementHitCounter(); + + if (spiritWalk.getHitsCounter() < 9) return; + + spiritWalk.resetHitsCounter(); + initializeSpiritWalk(event.getEliteMobEntity()); + + } + + public void initializeSpiritWalk(EliteEntity eliteEntity) { + + new BukkitRunnable() { + + int counter = 1; + + @Override + public void run() { + + if (counter > 3 || !eliteEntity.isValid()) { + cancel(); + return; + } + + Location bossLocation = eliteEntity.getLivingEntity().getLocation().clone(); + + for (int i = 0; i < 20; i++) { + + double randomizedX = (ThreadLocalRandom.current().nextDouble() - 0.5) * 5; + double randomizedY = ThreadLocalRandom.current().nextDouble() - 0.5; + double randomizedZ = (ThreadLocalRandom.current().nextDouble() - 0.5) * 5; + + Vector normalizedVector = new Vector(randomizedX, randomizedY, randomizedZ).normalize().multiply(7).multiply(counter); + + Location newSimulatedLocation = bossLocation.add(normalizedVector).clone(); + + Location newValidLocation = checkLocationValidity(newSimulatedLocation); + + if (newValidLocation != null) { + + spiritWalkAnimation(eliteEntity, eliteEntity.getLivingEntity().getLocation(), newValidLocation.add(new Vector(0.5, 1, 0.5))); + cancel(); + break; + } + + } + + counter++; + + } + + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + + } + + private Location checkLocationValidity(Location simulatedLocation) { + + if (simulatedLocation.getBlock().getType().equals(Material.AIR)) { + + int counter = 1; + + while (true) { + + if (simulatedLocation.getY() < 1) return null; + + Location blockUnderCurrentBlock = simulatedLocation.clone().subtract(new Vector(0, counter, 0)); + + if (blockUnderCurrentBlock.getBlock().getType() != Material.AIR) return blockUnderCurrentBlock; + + if (counter > 10) return null; + + counter++; + + } + + } + + return null; + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/SummonEmbers.java b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/SummonEmbers.java new file mode 100644 index 000000000..a3b7575c3 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/SummonEmbers.java @@ -0,0 +1,73 @@ +package com.magmaguy.elitemobs.powers.bosspowers; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import com.magmaguy.elitemobs.powers.meta.BossPower; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import java.util.concurrent.ThreadLocalRandom; + +public class SummonEmbers extends BossPower implements Listener { + public SummonEmbers() { + super(PowersConfig.getPower("summon_embers.yml")); + } + + @EventHandler + public void onDamage(EliteMobDamagedByPlayerEvent event) { + SummonEmbers summonEmbers = (SummonEmbers) event.getEliteMobEntity().getPower(this); + if (summonEmbers == null) return; + if (!eventIsValid(event, summonEmbers)) return; + if (ThreadLocalRandom.current().nextDouble() > 0.25) return; + + summonEmbers.doGlobalCooldown(20 * 20, event.getEliteMobEntity()); + doSummonParticles(event.getEliteMobEntity()); + + } + + private void doSummonParticles(EliteEntity eliteEntity) { + eliteEntity.getLivingEntity().setAI(false); + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + counter++; + if (!eliteEntity.isValid()) { + cancel(); + return; + } + eliteEntity.getLivingEntity().getWorld().spawnParticle(Particle.FLAME, + eliteEntity.getLivingEntity().getLocation().add(new Vector(0, 1, 0)), 50, 0.0001, 0.0001, 0.0001); + if (counter < 20 * 3) return; + cancel(); + doSummon(eliteEntity); + eliteEntity.getLivingEntity().setAI(true); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + + } + + private void doSummon(EliteEntity eliteEntity) { + + for (int i = 0; i < 10; i++) { + Location spawnLocation = eliteEntity.getLivingEntity().getLocation(); + + CustomBossEntity.createCustomBossEntity("ember.yml").spawn(spawnLocation, eliteEntity.getLevel(), false); + + double x = ThreadLocalRandom.current().nextDouble() - 0.5; + double z = ThreadLocalRandom.current().nextDouble() - 0.5; + + eliteEntity.getLivingEntity().setVelocity(new Vector(x, 0.5, z)); + } + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/SummonTheReturned.java b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/SummonTheReturned.java new file mode 100644 index 000000000..9aea6b6d6 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/SummonTheReturned.java @@ -0,0 +1,79 @@ +package com.magmaguy.elitemobs.powers.bosspowers; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import com.magmaguy.elitemobs.powers.meta.BossPower; +import com.magmaguy.elitemobs.utils.WarningMessage; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import java.util.concurrent.ThreadLocalRandom; + +public class SummonTheReturned extends BossPower implements Listener { + + public SummonTheReturned() { + super(PowersConfig.getPower("summon_the_returned.yml")); + } + + @EventHandler + public void onDamage(EliteMobDamagedByPlayerEvent event) { + if (event.isCancelled()) return; + SummonTheReturned summonTheReturned = (SummonTheReturned) event.getEliteMobEntity().getPower(this); + if (summonTheReturned == null) return; + if (!eventIsValid(event, summonTheReturned)) return; + if (ThreadLocalRandom.current().nextDouble() > 0.25) return; + + summonTheReturned.doGlobalCooldown(20 * 20, event.getEliteMobEntity()); + doSummonParticles(event.getEliteMobEntity()); + } + + private void doSummonParticles(EliteEntity eliteEntity) { + eliteEntity.getLivingEntity().setAI(false); + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + if (!eliteEntity.isValid()) { + cancel(); + return; + } + counter++; + eliteEntity.getLivingEntity().getWorld().spawnParticle(Particle.PORTAL, + eliteEntity.getLivingEntity().getLocation().add(new Vector(0, 1, 0)), 50, 0.01, 0.01, 0.01, 1); + if (counter < 20 * 3) return; + cancel(); + doSummon(eliteEntity); + eliteEntity.getLivingEntity().setAI(true); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + + } + + private void doSummon(EliteEntity eliteEntity) { + + for (int i = 0; i < 10; i++) { + Location spawnLocation = eliteEntity.getLivingEntity().getLocation(); + + CustomBossEntity.createCustomBossEntity("the_returned.yml").spawn(spawnLocation, eliteEntity.getLevel(), false); + + double x = ThreadLocalRandom.current().nextDouble() - 0.5; + double z = ThreadLocalRandom.current().nextDouble() - 0.5; + + try { + eliteEntity.getLivingEntity().setVelocity(new Vector(x, 0.5, z)); + } catch (Exception ex) { + new WarningMessage("Attempted to complete Summon the Returned power but a reinforcement mob wasn't detected! Did the boss move to an area that prevents spawning?"); + } + } + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/Thunderstorm.java b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/Thunderstorm.java new file mode 100644 index 000000000..6634a89d3 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/bosspowers/Thunderstorm.java @@ -0,0 +1,91 @@ +package com.magmaguy.elitemobs.powers.bosspowers; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerEvent; +import com.magmaguy.elitemobs.collateralminecraftchanges.LightningSpawnBypass; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.meta.BossPower; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import java.util.concurrent.ThreadLocalRandom; + +public class Thunderstorm extends BossPower implements Listener { + + public Thunderstorm() { + super(PowersConfig.getPower("thunderstorm.yml")); + } + + public static void doThunderstorm(EliteEntity eliteEntity) { + if (eliteEntity == null || !eliteEntity.getLivingEntity().isValid()) return; + eliteEntity.getLivingEntity().setAI(false); + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + counter++; + if (counter > 20 * 5 || eliteEntity.getLivingEntity() == null || !eliteEntity.getLivingEntity().isValid()) { + cancel(); + eliteEntity.getLivingEntity().setAI(true); + return; + } + + if (counter % 2 == 0) { + Location randomLocation = eliteEntity.getLivingEntity().getLocation().clone().add(new Vector( + ThreadLocalRandom.current().nextInt(-20, 20), + 0, + ThreadLocalRandom.current().nextInt(-20, 20))); + lightningTask(randomLocation); + } + + + if (counter % 20 == 0) { + for (Entity entity : eliteEntity.getLivingEntity().getNearbyEntities(20, 20, 20)) + if (entity.getType().equals(EntityType.PLAYER)) + lightningTask(entity.getLocation()); + } + + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + } + + public static void lightningTask(Location location) { + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + counter++; + if (counter > 20 * 3) { + LightningSpawnBypass.bypass(); + location.getWorld().strikeLightning(location); + cancel(); + return; + } + location.getWorld().spawnParticle(Particle.CRIT, location, 10, 0.5, 1.5, 0.5, 0.3); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + + } + + @EventHandler + public void onDamage(EliteMobDamagedByPlayerEvent event) { + Thunderstorm thunderstorm = (Thunderstorm) event.getEliteMobEntity().getPower(this); + if (thunderstorm == null) return; + if (!eventIsValid(event, thunderstorm)) return; + if (ThreadLocalRandom.current().nextDouble() > 0.25) return; + + thunderstorm.doGlobalCooldown(20 * 20, event.getEliteMobEntity()); + doThunderstorm(event.getEliteMobEntity()); + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/defensivepowers/Invisibility.java b/src/main/java/com/magmaguy/elitemobs/powers/defensivepowers/Invisibility.java new file mode 100644 index 000000000..b721d4904 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/defensivepowers/Invisibility.java @@ -0,0 +1,30 @@ +package com.magmaguy.elitemobs.powers.defensivepowers; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.powers.meta.MinorPower; +import org.bukkit.entity.LivingEntity; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.scheduler.BukkitRunnable; + +/** + * Created by MagmaGuy on 28/04/2017. + */ +public class Invisibility extends MinorPower { + + public Invisibility() { + super(PowersConfig.getPower("invisibility.yml")); + } + + @Override + public void applyPowers(LivingEntity livingEntity) { + new BukkitRunnable() { + @Override + public void run() { + livingEntity.addPotionEffect(new PotionEffect(PotionEffectType.INVISIBILITY, Integer.MAX_VALUE, 1)); + } + }.runTaskLater(MetadataHandler.PLUGIN, 1); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/defensivepowers/InvulnerabilityArrow.java b/src/main/java/com/magmaguy/elitemobs/powers/defensivepowers/InvulnerabilityArrow.java new file mode 100644 index 000000000..1e96fdc15 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/defensivepowers/InvulnerabilityArrow.java @@ -0,0 +1,26 @@ +package com.magmaguy.elitemobs.powers.defensivepowers; + +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.powers.meta.MinorPower; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageEvent; + +/** + * Created by MagmaGuy on 05/11/2016. + */ +public class InvulnerabilityArrow extends MinorPower implements Listener { + + public InvulnerabilityArrow() { + super(PowersConfig.getPower("invulnerability_arrow.yml")); + } + + @EventHandler + public void invulnerablityArrow(EliteMobDamagedByPlayerEvent event) { + if (!event.getEliteMobEntity().hasPower(this)) return; + if (!event.getEntityDamageByEntityEvent().getCause().equals(EntityDamageEvent.DamageCause.PROJECTILE)) return; + event.setCancelled(true); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/defensivepowers/InvulnerabilityFallDamage.java b/src/main/java/com/magmaguy/elitemobs/powers/defensivepowers/InvulnerabilityFallDamage.java new file mode 100644 index 000000000..b5de1223b --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/defensivepowers/InvulnerabilityFallDamage.java @@ -0,0 +1,26 @@ +package com.magmaguy.elitemobs.powers.defensivepowers; + +import com.magmaguy.elitemobs.api.EliteMobDamagedEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.powers.meta.MinorPower; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageEvent; + +/** + * Created by MagmaGuy on 28/11/2016. + */ +public class InvulnerabilityFallDamage extends MinorPower implements Listener { + + public InvulnerabilityFallDamage() { + super(PowersConfig.getPower("invulnerability_fall_damage.yml")); + } + + @EventHandler + public void invulnerabilityFallDamage(EliteMobDamagedEvent event) { + if (!event.getEliteMobEntity().hasPower(this)) return; + if (!event.getEntityDamageEvent().getCause().equals(EntityDamageEvent.DamageCause.FALL)) return; + event.setCancelled(true); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/defensivepowers/InvulnerabilityFire.java b/src/main/java/com/magmaguy/elitemobs/powers/defensivepowers/InvulnerabilityFire.java new file mode 100644 index 000000000..d71135745 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/defensivepowers/InvulnerabilityFire.java @@ -0,0 +1,31 @@ +package com.magmaguy.elitemobs.powers.defensivepowers; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.powers.meta.MinorPower; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.Listener; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.scheduler.BukkitRunnable; + +/** + * Created by MagmaGuy on 05/11/2016. + */ +public class InvulnerabilityFire extends MinorPower implements Listener { + + public InvulnerabilityFire() { + super(PowersConfig.getPower("invulnerability_fire.yml")); + } + + @Override + public void applyPowers(LivingEntity livingEntity) { + new BukkitRunnable() { + @Override + public void run() { + livingEntity.addPotionEffect(new PotionEffect(PotionEffectType.FIRE_RESISTANCE, Integer.MAX_VALUE, 1)); + } + }.runTaskLater(MetadataHandler.PLUGIN, 1); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/defensivepowers/InvulnerabilityKnockback.java b/src/main/java/com/magmaguy/elitemobs/powers/defensivepowers/InvulnerabilityKnockback.java new file mode 100644 index 000000000..ebbd6cb67 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/defensivepowers/InvulnerabilityKnockback.java @@ -0,0 +1,40 @@ +package com.magmaguy.elitemobs.powers.defensivepowers; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobDamagedEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import com.magmaguy.elitemobs.powers.meta.MinorPower; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +/** + * Created by MagmaGuy on 30/04/2017. + */ +public class InvulnerabilityKnockback extends MinorPower implements Listener { + + public InvulnerabilityKnockback() { + super(PowersConfig.getPower("invulnerability_knockback.yml")); + } + + @EventHandler + public void invulnerabilityKnockback(EliteMobDamagedEvent event) { + if (event.getEliteMobEntity().hasPower(this) || + event.getEliteMobEntity() instanceof CustomBossEntity && + ((CustomBossEntity) event.getEliteMobEntity()).getCustomBossesConfigFields().isFrozen()) { + if (!event.getEliteMobEntity().isValid()) return; + event.getEntity().setVelocity(new Vector(0, 0, 0)); + new BukkitRunnable() { + @Override + public void run() { + if (!event.getEliteMobEntity().isValid()) return; + event.getEntity().setVelocity(new Vector(0, 0, 0)); + } + }.runTaskLater(MetadataHandler.PLUGIN, 1); + } + } + +} + diff --git a/src/main/java/com/magmaguy/elitemobs/powers/defensivepowers/ShieldWall.java b/src/main/java/com/magmaguy/elitemobs/powers/defensivepowers/ShieldWall.java new file mode 100644 index 000000000..c270ec119 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/defensivepowers/ShieldWall.java @@ -0,0 +1,282 @@ +package com.magmaguy.elitemobs.powers.defensivepowers; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerEvent; +import com.magmaguy.elitemobs.api.EliteMobExitCombatEvent; +import com.magmaguy.elitemobs.api.internal.RemovalReason; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.meta.ElitePower; +import com.magmaguy.elitemobs.powers.meta.MinorPower; +import com.magmaguy.elitemobs.utils.VisualArmorStand; +import lombok.Getter; +import lombok.Setter; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.inventory.EquipmentSlot; +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.EulerAngle; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.ThreadLocalRandom; + +public class ShieldWall extends MinorPower { + private final HashMap> armorStands = new HashMap<>(); + private final HashMap armorStandOffBaseOffsets = new HashMap<>(); + private double northHealthPool; + private double southHealthPool; + private double eastHealthPool; + private double westHealthPool; + @Getter + @Setter + private boolean isActive = false; + + public ShieldWall() { + super(PowersConfig.getPower("shield_wall.yml")); + offsetInitializer(); + } + + public boolean preventDamage(Player player, EliteEntity eliteEntity, double damage) { + if (!Objects.equals(player.getLocation().getWorld(), eliteEntity.getLocation().getWorld())) return false; + Vector direction = player.getLocation().subtract(eliteEntity.getLocation()).toVector().normalize(); + Direction damageDirection; + if (Math.abs(direction.getX()) > Math.abs(direction.getZ())) { + if (direction.getX() > 0) + damageDirection = Direction.EAST; + else + damageDirection = Direction.WEST; + } else if (direction.getZ() > 0) + damageDirection = Direction.SOUTH; + else + damageDirection = Direction.NORTH; + + switch (damageDirection) { + case NORTH: + if (northHealthPool > 0) { + northHealthPool -= damage; + return true; + } + break; + case SOUTH: + if (southHealthPool > 0) { + southHealthPool -= damage; + return true; + } + break; + case EAST: + if (eastHealthPool > 0) { + eastHealthPool -= damage; + return true; + } + break; + case WEST: + default: + if (westHealthPool > 0) { + westHealthPool -= damage; + return true; + } + } + return false; + } + + public void initialize(EliteEntity eliteEntity) { + if (ThreadLocalRandom.current().nextDouble() >= .1) return; + doCooldown(eliteEntity); + /* + 1 = north + 2 = east + 3 = south + 4 = west + */ + int direction = ThreadLocalRandom.current().nextInt(1, 5); + northHealthPool = eliteEntity.getLevel(); + southHealthPool = eliteEntity.getLevel(); + eastHealthPool = eliteEntity.getLevel(); + westHealthPool = eliteEntity.getLevel(); + switch (direction) { + case 1: + northHealthPool = 0; + break; + case 2: + eastHealthPool = 0; + break; + case 3: + southHealthPool = 0; + break; + case 4: + westHealthPool = 0; + break; + } + + for (int i = 1; i < 5; i++) + if (direction != i) + armorStands.put(directionConverter(i), armorStandCreator(directionConverter(i), eliteEntity)); + + armorStandTracker(eliteEntity); + setActive(true); + } + + private Direction directionConverter(int direction) { + switch (direction) { + case 1: + return Direction.NORTH; + case 2: + return Direction.EAST; + case 3: + return Direction.SOUTH; + case 4: + default: + return Direction.WEST; + } + } + + private void offsetInitializer() { + for (int i = 1; i < 5; i++) { + switch (i) { + case 1: + armorStandOffBaseOffsets.put(directionConverter(i), new Vector(0, 0, -1)); + break; + case 2: + armorStandOffBaseOffsets.put(directionConverter(i), new Vector(1, 0, 0)); + break; + case 3: + armorStandOffBaseOffsets.put(directionConverter(i), new Vector(0, 0, 1)); + break; + case 4: + default: + armorStandOffBaseOffsets.put(directionConverter(i), new Vector(-1, 0, 0)); + break; + } + } + } + + private Location getRealLocation(Direction direction, Location livingEntityLocation, int iteration) { + Vector finalOffsetVector; + if (direction.equals(Direction.NORTH) || direction.equals(Direction.SOUTH)) + finalOffsetVector = armorStandOffBaseOffsets.get(direction).clone().add(new Vector(iteration, 0, 0)); + else + finalOffsetVector = armorStandOffBaseOffsets.get(direction).clone().add(new Vector(0, 0, iteration)); + Location realLocation = livingEntityLocation.clone().add(finalOffsetVector); + switch (direction) { + case NORTH: + realLocation.setYaw(180); + break; + case SOUTH: + realLocation.setYaw(0f); + break; + case EAST: + realLocation.setYaw(-90); + break; + case WEST: + default: + realLocation.setYaw(90); + } + realLocation.setPitch(0); + return realLocation; + } + + private List armorStandCreator(Direction direction, EliteEntity eliteEntity) { + List armorStands = new ArrayList<>(); + for (int i = -1; i < 2; i++) { + ArmorStand armorStand = VisualArmorStand.VisualArmorStand(getRealLocation(direction, eliteEntity.getLivingEntity().getLocation(), i), "Barrier"); + armorStands.add(armorStand); + armorStand.getEquipment().setItemInMainHand(new ItemStack(Material.SHIELD)); + armorStand.addEquipmentLock(EquipmentSlot.HAND, ArmorStand.LockType.REMOVING_OR_CHANGING); + armorStand.setRightArmPose(new EulerAngle(Math.PI / 2d, Math.PI + Math.PI / 2d, Math.PI)); + } + return armorStands; + } + + private void armorStandTracker(EliteEntity eliteEntity) { + Bukkit.getScheduler().runTaskTimer(MetadataHandler.PLUGIN, (task) -> { + if (!eliteEntity.isValid() || (northHealthPool == 0 && southHealthPool == 0 && eastHealthPool == 0 && westHealthPool == 0) || !isActive) { + task.cancel(); + setActive(false); + + for (List armorStands : armorStands.values()) + if (armorStands != null) + for (ArmorStand armorStand : armorStands) + if (armorStand != null && armorStand.isValid()) + EntityTracker.unregister(armorStand, RemovalReason.EFFECT_TIMEOUT); + + return; + } + int visualShieldsLeft = 0; + for (Direction direction : armorStands.keySet()) { + for (int i = -1; i < 2; i++) { + ArmorStand armorStand = armorStands.get(direction).get(i + 1); + if (armorStand == null || !armorStand.isValid()) continue; + switch (direction) { + case NORTH: + if (0.33 * (i + 1) >= northHealthPool / (double) eliteEntity.getLevel()) + EntityTracker.unregister(armorStand, RemovalReason.EFFECT_TIMEOUT); + break; + case SOUTH: + if (0.33 * (i + 1) >= southHealthPool / (double) eliteEntity.getLevel()) + EntityTracker.unregister(armorStand, RemovalReason.EFFECT_TIMEOUT); + break; + case EAST: + if (0.33 * (i + 1) >= eastHealthPool / (double) eliteEntity.getLevel()) + EntityTracker.unregister(armorStand, RemovalReason.EFFECT_TIMEOUT); + break; + case WEST: + default: + if (0.33 * (i + 1) >= westHealthPool / (double) eliteEntity.getLevel()) + EntityTracker.unregister(armorStand, RemovalReason.EFFECT_TIMEOUT); + } + + visualShieldsLeft++; + armorStand.teleport(getRealLocation(direction, eliteEntity.getLivingEntity().getLocation(), i)); + } + } + if (visualShieldsLeft == 0) { + task.cancel(); + setActive(false); + return; + } + }, 1, 1); + } + + private enum Direction { + NORTH, + SOUTH, + EAST, + WEST + } + + public static class ShieldWallEvents implements Listener { + @EventHandler + public void onEliteHit(EliteMobDamagedByPlayerEvent event) { + ElitePower elitePower = event.getEliteMobEntity().getPower(PowersConfig.getPower("shield_wall.yml")); + if (elitePower == null) return; + ShieldWall shieldWall = (ShieldWall) elitePower; + if (!shieldWall.isActive()) { + if (!eventIsValid(event, elitePower)) return; + shieldWall.initialize(event.getEliteMobEntity()); + } else { + if (shieldWall.preventDamage(event.getPlayer(), event.getEliteMobEntity(), event.getDamage())) + event.setCancelled(true); + } + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH) + public void onCombatLeaveEvent(EliteMobExitCombatEvent event) { + ElitePower elitePower = event.getEliteMobEntity().getPower(PowersConfig.getPower("shield_wall.yml")); + if (elitePower == null) return; + ShieldWall shieldWall = (ShieldWall) elitePower; + if (shieldWall.isActive) shieldWall.setActive(false); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/blaze/TrackingFireball.java b/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/blaze/TrackingFireball.java new file mode 100644 index 000000000..0cdb477b7 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/blaze/TrackingFireball.java @@ -0,0 +1,134 @@ +package com.magmaguy.elitemobs.powers.majorpowers.blaze; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobTargetPlayerEvent; +import com.magmaguy.elitemobs.combatsystem.EliteProjectile; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.powers.meta.MajorPower; +import org.bukkit.GameMode; +import org.bukkit.entity.*; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.projectiles.ProjectileSource; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import java.util.HashMap; +import java.util.UUID; + +public class TrackingFireball extends MajorPower { + + public TrackingFireball() { + super(PowersConfig.getPower("tracking_fireball.yml")); + } + + public static class TrackingFireballEvents implements Listener { + + public static HashMap trackingFireballs = new HashMap<>(); + + @EventHandler(ignoreCancelled = true) + public void targetEvent(EliteMobTargetPlayerEvent event) { + if (!(event.getEliteMobEntity().getLivingEntity() instanceof Monster)) return; + TrackingFireball trackingFireball = (TrackingFireball) event.getEliteMobEntity().getPower(new TrackingFireball()); + if (trackingFireball == null) return; + if (trackingFireball.isFiring()) return; + + trackingFireball.setFiring(true); + new TrackingFireballTasks((Monster) event.getEntity(), trackingFireball); + } + + @EventHandler(ignoreCancelled = true) + public void onFireballPunched(EntityDamageByEntityEvent event) { + TrackingFireballTasks.TrackingFireballTask trackingFireballTask = trackingFireballs.get(event.getEntity().getUniqueId()); + if (trackingFireballTask == null) return; + trackingFireballTask.isAfterPlayer = !trackingFireballTask.isAfterPlayer; + } + + private class TrackingFireballTasks { + + public TrackingFireballTasks(Monster monster, TrackingFireball trackingFireball) { + + new BukkitRunnable() { + + @Override + public void run() { + + if (!monster.isValid() || monster.getTarget() == null) { + trackingFireball.setFiring(false); + cancel(); + return; + } + + for (Entity nearbyEntity : monster.getNearbyEntities(20, 20, 20)) + if (nearbyEntity instanceof Player) + if (((Player) nearbyEntity).getGameMode().equals(GameMode.ADVENTURE) || + ((Player) nearbyEntity).getGameMode().equals(GameMode.SURVIVAL)) + new TrackingFireballTask(monster, (Player) nearbyEntity); + + } + + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 20 * 8); + + } + + public class TrackingFireballTask { + public boolean isAfterPlayer = true; + private Fireball repeatingFireball = null; + + public TrackingFireballTask(Entity entity, Player player) { + Vector targetterToTargetted = player.getLocation().clone().toVector().subtract(entity.getLocation().toVector()).normalize().multiply(0.0001); + repeatingFireball = (Fireball) EliteProjectile.create(EntityType.FIREBALL, entity, player, targetterToTargetted, true); + repeatingFireball.setYield(3F); + repeatingFireball.setIsIncendiary(true); + repeatingFireball.setShooter((ProjectileSource) entity); + trackingFireballs.put(repeatingFireball.getUniqueId(), this); + + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + if (repeatingFireball == null || + !repeatingFireball.isValid() || + !entity.isValid() || + player.isDead() || + counter > 20 * 60 * 3) { + cancel(); + return; + } + + if (isAfterPlayer) { + repeatingFireball.setDirection(setFireballDirection(player)); + repeatingFireball.setVelocity(setFireballDirection(player)); + } else { + repeatingFireball.setDirection(setFireballDirection(entity)); + repeatingFireball.setVelocity(setFireballDirection(entity)); + } + counter++; + } + }.runTaskTimer(MetadataHandler.PLUGIN, 1, 1); + } + + + private Vector setFireballDirection(Entity target) { + double fireballVelocity = PowersConfig.getPower("tracking_fireball.yml").getFileConfiguration().getDouble("fireballSpeed"); + if (target.getLocation().distanceSquared(repeatingFireball.getLocation()) > 1) + return target.getLocation().clone() + .add(new Vector(0, 1, 0)) + .toVector() + .subtract(repeatingFireball.getLocation().toVector()) + .normalize() + .multiply(fireballVelocity); + //when close aim for the ground due to a bug where entity speed syncs up with fireball speed + return target.getLocation().clone() + .toVector() + .subtract(repeatingFireball.getLocation().toVector()) + .normalize() + .multiply(fireballVelocity); + } + } + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/enderdragon/EnderDragonDiscoFireballs.java b/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/enderdragon/EnderDragonDiscoFireballs.java new file mode 100644 index 000000000..94ac54a41 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/enderdragon/EnderDragonDiscoFireballs.java @@ -0,0 +1,164 @@ +package com.magmaguy.elitemobs.powers.majorpowers.enderdragon; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.combatsystem.EliteProjectile; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.meta.CombatEnterScanPower; +import com.magmaguy.elitemobs.utils.EnderDragonPhaseSimplifier; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.entity.EnderDragon; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Fireball; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.concurrent.ThreadLocalRandom; + +public class EnderDragonDiscoFireballs extends CombatEnterScanPower { + + int randomTiltSeed; + private ArrayList relativeLocationOffsets; + private ArrayList realLocations = new ArrayList<>(); + private int warningCounter = 0; + private ArrayList fireballs = new ArrayList<>(); + + public EnderDragonDiscoFireballs() { + super(PowersConfig.getPower("ender_dragon_disco_fireballs.yml")); + } + + @Override + protected void finishActivation(EliteEntity eliteEntity) { + super.bukkitTask = new BukkitRunnable() { + @Override + public void run() { + if (doExit(eliteEntity) || isInCooldown(eliteEntity)) { + return; + } + + if (eliteEntity.getLivingEntity().getType().equals(EntityType.ENDER_DRAGON)) + if (!EnderDragonPhaseSimplifier.isLanded(((EnderDragon) eliteEntity.getLivingEntity()).getPhase())) + return; + + doPower(eliteEntity); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 10); + } + + @Override + protected void finishDeactivation(EliteEntity eliteEntity) { + + } + + private void doPower(EliteEntity eliteEntity) { + doCooldown(eliteEntity); + + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + + if (doExit(eliteEntity) || + eliteEntity.getLivingEntity().getType().equals(EntityType.ENDER_DRAGON) && + !EnderDragonPhaseSimplifier.isLanded(((EnderDragon) eliteEntity.getLivingEntity()).getPhase())) { + cancel(); + return; + } + + if (eliteEntity.getLivingEntity().getType().equals(EntityType.ENDER_DRAGON)) + ((EnderDragon) eliteEntity.getLivingEntity()).setPhase(EnderDragon.Phase.SEARCH_FOR_BREATH_ATTACK_TARGET); + + if (counter == 0) { + //todo: reset fields if needed + generateLocations(); + commitLocations(eliteEntity); + randomTiltSeed = ThreadLocalRandom.current().nextInt(); + warningCounter = 0; + } + + if (counter < 20 * 6) { + //todo: warning phase + doWarningPhase(eliteEntity); + warningCounter++; + } + + if (counter > 20 * 6) { + doDamagePhase(eliteEntity); + cancel(); + } + + counter++; + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + } + + private void generateLocations() { + relativeLocationOffsets = new ArrayList<>(); + for (int i = 0; i < 12; i++) + relativeLocationOffsets.add(new Vector(7, 0, 0).rotateAroundY(2D * Math.PI / 12D * i)); + } + + private void commitLocations(EliteEntity eliteEntity) { + realLocations = new ArrayList<>(); + for (Vector vector : relativeLocationOffsets) + realLocations.add(eliteEntity.getLivingEntity().getLocation().clone().add(vector)); + } + + private void doWarningPhase(EliteEntity eliteEntity) { + //spawn fireballs and start rotation + if (warningCounter == 0) { + fireballs = new ArrayList<>(); + for (Location location : realLocations) { + Fireball fireball = (Fireball) location.getWorld().spawnEntity(location, EntityType.FIREBALL); + EntityTracker.registerProjectileEntity(fireball); + EliteProjectile.signExplosiveWithPower(fireball, getFileName()); + fireballs.add(fireball); + } + } + + warningCounter++; + + for (Fireball fireball : fireballs) { + if (fireball.isValid()) { + + if (warningCounter % 5 == 0) { + Vector relativeLocation = fireball.getLocation().clone().subtract(eliteEntity.getLivingEntity().getLocation()) + .toVector().rotateAroundY(2D * Math.PI / 96D); + Location rotatedLocation = eliteEntity.getLivingEntity().getLocation().clone().add(relativeLocation); + Vector velocity = rotatedLocation.clone().subtract(fireball.getLocation()).toVector().multiply(0.001); + fireball.setDirection(velocity); + fireball.setVelocity(velocity); + fireball.setYield(5F); + } + + generateVisualParticles(eliteEntity, fireball); + } + } + + } + + private void doDamagePhase(EliteEntity eliteEntity) { + for (Fireball fireball : fireballs) + fireball.setDirection(generateDownwardsVector(eliteEntity, fireball).multiply(0.1)); + } + + private Vector generateDownwardsVector(EliteEntity eliteEntity, Fireball fireball) { + double yValue = Math.cos(warningCounter) / 2 - 0.5; + return fireball.getLocation().clone().subtract(eliteEntity.getLivingEntity().getLocation()).toVector().normalize().setY(yValue); + } + + private void generateVisualParticles(EliteEntity eliteEntity, Fireball fireball) { + Vector downwardsVector = generateDownwardsVector(eliteEntity, fireball); + Location particleLocation = fireball.getLocation().clone(); + for (int i = 0; i < 200; i++) { + particleLocation.add(downwardsVector.clone().multiply(0.3)); + if (!particleLocation.getBlock().isPassable()) break; + fireball.getWorld().spawnParticle(Particle.SMOKE_NORMAL, particleLocation, 1, 1, 0, 0, 0); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/enderdragon/EnderDragonEmpoweredLightning.java b/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/enderdragon/EnderDragonEmpoweredLightning.java new file mode 100644 index 000000000..df5418b3d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/enderdragon/EnderDragonEmpoweredLightning.java @@ -0,0 +1,138 @@ +package com.magmaguy.elitemobs.powers.majorpowers.enderdragon; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobEnterCombatEvent; +import com.magmaguy.elitemobs.api.EliteMobExitCombatEvent; +import com.magmaguy.elitemobs.collateralminecraftchanges.LightningSpawnBypass; +import com.magmaguy.elitemobs.combatsystem.EliteProjectile; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.meta.MajorPower; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Fireball; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scheduler.BukkitTask; +import org.bukkit.util.Vector; + +import java.util.concurrent.ThreadLocalRandom; + +public class EnderDragonEmpoweredLightning extends MajorPower { + + private boolean isActive = false; + private BukkitTask bukkitTask = null; + + public EnderDragonEmpoweredLightning() { + super(PowersConfig.getPower("ender_dragon_empowered_lightning.yml")); + } + + public static void lightningTask(Location location) { + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + counter++; + if (counter > 20 * 3) { + LightningSpawnBypass.bypass(); + location.getWorld().strikeLightning(location); + Fireball fireball = (Fireball) location.getWorld().spawnEntity(location, EntityType.FIREBALL); + EntityTracker.registerProjectileEntity(fireball); + fireball.setDirection(new Vector(0, -3, 0)); + fireball.setVelocity(new Vector(0, -3, 0)); + fireball.setYield(5F); + EliteProjectile.signExplosiveWithPower(fireball, "ender_dragon_empowered_lightning.yml"); + cancel(); + return; + } + location.getWorld().spawnParticle(Particle.SOUL_FIRE_FLAME, location, 10, 0.5, 1.5, 0.5, 0.3); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + + } + + private void activate(EliteEntity eliteEntity) { + if (isActive) + return; + + isActive = true; + + bukkitTask = new BukkitRunnable() { + @Override + public void run() { + if (!eliteEntity.isValid()) { + cancel(); + return; + } + if (isInCooldown(eliteEntity)) return; + fireLightning(eliteEntity); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 20); + + } + + private void deactivate() { + isActive = false; + if (bukkitTask != null) + bukkitTask.cancel(); + } + + public void fireLightning(EliteEntity eliteEntity) { + + doCooldown(eliteEntity); + + for (Entity entity : eliteEntity.getLivingEntity().getLocation().getWorld().getNearbyEntities(eliteEntity.getLivingEntity().getLocation(), 150, 150, 150)) + if (entity.getType().equals(EntityType.PLAYER)) + lightningTask(entity.getLocation().clone()); + + for (int i = 0; i < 50; i++) { + Location randomLocation = locationRandomizer(eliteEntity.getLivingEntity().getLocation(), 0); + if (randomLocation == null) continue; + + new BukkitRunnable() { + @Override + public void run() { + lightningTask(randomLocation); + } + }.runTaskLater(MetadataHandler.PLUGIN, ThreadLocalRandom.current().nextInt(20 * 5)); + + } + } + + private Location locationRandomizer(Location location, int counter) { + if (counter > 5) return null; + Location randomLocation = location.clone().add(new Vector( + ThreadLocalRandom.current().nextInt(-150, 150), + 0, + ThreadLocalRandom.current().nextInt(-150, 150))); + + randomLocation.setY(randomLocation.getWorld().getHighestBlockAt(randomLocation).getY()); + if (randomLocation.getY() == -1) + locationRandomizer(location, counter + 1); + + return randomLocation; + } + + public static class EnderDragonEmpoweredLightningEvents implements Listener { + @EventHandler + public void onCombatEnter(EliteMobEnterCombatEvent event) { + EnderDragonEmpoweredLightning empoweredLightning = (EnderDragonEmpoweredLightning) event.getEliteMobEntity().getPower("ender_dragon_empowered_lightning.yml"); + if (empoweredLightning == null) return; + empoweredLightning.activate(event.getEliteMobEntity()); + } + + @EventHandler + public void onCombatLeave(EliteMobExitCombatEvent event) { + EnderDragonEmpoweredLightning empoweredLightning = (EnderDragonEmpoweredLightning) event.getEliteMobEntity().getPower("ender_dragon_empowered_lightning.yml"); + if (empoweredLightning == null) return; + empoweredLightning.deactivate(); + } + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/enderdragon/EnderDragonShockwave.java b/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/enderdragon/EnderDragonShockwave.java new file mode 100644 index 000000000..9ed4d2e2e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/enderdragon/EnderDragonShockwave.java @@ -0,0 +1,208 @@ +package com.magmaguy.elitemobs.powers.majorpowers.enderdragon; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.events.BossCustomAttackDamage; +import com.magmaguy.elitemobs.explosionregen.Explosion; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.meta.CombatEnterScanPower; +import com.magmaguy.elitemobs.utils.EnderDragonPhaseSimplifier; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.block.Block; +import org.bukkit.entity.EnderDragon; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.BoundingBox; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +public class EnderDragonShockwave extends CombatEnterScanPower { + + private final int radius = 30; + //this is structured like this because the relative block generator is moving out of this class + private final ArrayList realBlocks = new ArrayList<>(); + private ArrayList pieBlocks = new ArrayList<>(); + private int warningPhaseCounter = 0; + private int damagePhaseCounter = 0; + + public EnderDragonShockwave() { + super(PowersConfig.getPower("ender_dragon_shockwave.yml")); + } + + @Override + protected void finishActivation(EliteEntity eliteEntity) { + super.bukkitTask = new BukkitRunnable() { + + @Override + public void run() { + if (doExit(eliteEntity) || isInCooldown(eliteEntity)) { + return; + } + + if (eliteEntity.getLivingEntity().getType().equals(EntityType.ENDER_DRAGON)) { + EnderDragon.Phase phase = ((EnderDragon) eliteEntity.getLivingEntity()).getPhase(); + if (!EnderDragonPhaseSimplifier.isLanded(phase)) return; + } + + doPower(eliteEntity); + + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 10); + } + + private void doPower(EliteEntity eliteEntity) { + doCooldown(eliteEntity); + + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + + if (eliteEntity.isValid()) + if (eliteEntity.getLivingEntity().getType().equals(EntityType.ENDER_DRAGON)) + ((EnderDragon) eliteEntity.getLivingEntity()).setPhase(EnderDragon.Phase.SEARCH_FOR_BREATH_ATTACK_TARGET); + + if (doExit(eliteEntity) || eliteEntity.getLivingEntity().getType().equals(EntityType.ENDER_DRAGON) && + !EnderDragonPhaseSimplifier.isLanded(((EnderDragon) eliteEntity.getLivingEntity()).getPhase())) { + cancel(); + return; + } + + if (counter == 0) { + setAffectedBlocks(); + generateRealCircle(eliteEntity); + warningPhaseCounter = 0; + damagePhaseCounter = 0; + } + + if (counter < 20 * 3) { + doWarningPhase(eliteEntity); + } + + if (counter > 20 * 3) { + doDamagePhase(eliteEntity); + } + + if (counter >= 20 * (3 + 6)) { + cancel(); + } + + counter++; + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + } + + //todo: move this to its own class, make sure it only generates once ever and then just randomizes rotations + private void setAffectedBlocks() { + pieBlocks = new ArrayList<>(); + double rotation = ThreadLocalRandom.current().nextDouble(2); + Vector relative0 = new Vector(0, 0, 0); + for (int x = -radius; x < radius; x++) + for (int z = -radius; z < radius; z++) { + if (x > 0 && z > 0) continue; + double distance = relative0.distance(new Vector(x, 0, z)); + if (distance > radius) continue; + + pieBlocks.add(new PieBlock((int) Math.ceil(distance), new Vector(x, 0, z).rotateAroundY(rotation))); + } + + } + + private void generateRealCircle(EliteEntity eliteEntity) { + for (PieBlock pieBlock : pieBlocks) { + Location rawPieBlock = eliteEntity.getLivingEntity().getLocation().clone().add(pieBlock.vector); + for (int y = 0; y > -10; y--) { + Location tempLocation = rawPieBlock.clone(); + tempLocation.setY(rawPieBlock.getY() + y); + if (!tempLocation.getBlock().isPassable()) { + Vector newVector = pieBlock.vector.clone(); + newVector.setY(newVector.getY() + y); + realBlocks.add(new PieBlock(pieBlock.distance, newVector)); + break; + } + } + } + + } + + private void doWarningPhase(EliteEntity eliteEntity) { + + Iterator pieBlockIterator = ((ArrayList) realBlocks.clone()).iterator(); + + while (pieBlockIterator.hasNext()) { + PieBlock pieBlock = pieBlockIterator.next(); + if (pieBlock.distance < warningPhaseCounter) { + Location rawPieBlock = eliteEntity.getLivingEntity().getLocation().clone().add(pieBlock.vector); + + pieBlockIterator.remove(); + + if (rawPieBlock.getBlock().isPassable()) + continue; + + rawPieBlock.getWorld().spawnParticle(Particle.SOUL, rawPieBlock.clone().add(0.5, 1, 0.5), 1, 0.1, 0.1, 0.1, 0.1); + } + } + + warningPhaseCounter++; + + } + + private void doDamagePhase(EliteEntity eliteEntity) { + List blockList = new ArrayList<>(); + Iterator pieBlockIterator = realBlocks.iterator(); + while (pieBlockIterator.hasNext()) { + PieBlock pieBlock = pieBlockIterator.next(); + + if (pieBlock.distance < damagePhaseCounter) { + Location rawPieBlock = eliteEntity.getLivingEntity().getLocation().clone().add(pieBlock.vector); + + if (rawPieBlock.getBlock().isPassable()) continue; + + for (Entity entity : rawPieBlock.getWorld().getNearbyEntities( + new BoundingBox(rawPieBlock.getX(), rawPieBlock.getY(), rawPieBlock.getZ(), + rawPieBlock.getX() + 1, rawPieBlock.getY() + 3, rawPieBlock.getZ() + 1))) { + if (entity.getType().equals(EntityType.FALLING_BLOCK)) continue; + entity.setVelocity(entity.getLocation().clone().subtract(eliteEntity.getLivingEntity().getLocation()).toVector().setY(1).normalize().multiply(3)); + if (entity.getType().equals(EntityType.PLAYER)) + BossCustomAttackDamage.dealCustomDamage(eliteEntity.getLivingEntity(), (LivingEntity) entity, 20); + } + + if (rawPieBlock.getBlock().getType().getBlastResistance() >= 7) + continue; + + blockList.add(rawPieBlock.getBlock()); + pieBlockIterator.remove(); + + } + } + + damagePhaseCounter++; + + Explosion.generateFakeExplosion(blockList, eliteEntity.getLivingEntity()); + + } + + @Override + protected void finishDeactivation(EliteEntity eliteEntity) { + + } + + private class PieBlock { + public Integer distance; + public Vector vector; + + public PieBlock(Integer distance, Vector vector) { + this.distance = distance; + this.vector = vector; + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/enderdragon/EnderDragonTornado.java b/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/enderdragon/EnderDragonTornado.java new file mode 100644 index 000000000..527c4c894 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/enderdragon/EnderDragonTornado.java @@ -0,0 +1,141 @@ +package com.magmaguy.elitemobs.powers.majorpowers.enderdragon; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.explosionregen.Explosion; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.meta.CombatEnterScanPower; +import com.magmaguy.elitemobs.utils.EnderDragonPhaseSimplifier; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.block.Block; +import org.bukkit.entity.EnderDragon; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +public class EnderDragonTornado extends CombatEnterScanPower { + + private Location tornadoEye = null; + private Vector tornadoSpeed = null; + + public EnderDragonTornado() { + super(PowersConfig.getPower("ender_dragon_tornado.yml")); + } + + @Override + protected void finishActivation(EliteEntity eliteEntity) { + super.bukkitTask = new BukkitRunnable() { + + @Override + public void run() { + if (doExit(eliteEntity) || isInCooldown(eliteEntity)) { + return; + } + + if (eliteEntity.getLivingEntity().getType().equals(EntityType.ENDER_DRAGON)) { + EnderDragon.Phase phase = ((EnderDragon) eliteEntity.getLivingEntity()).getPhase(); + if (!EnderDragonPhaseSimplifier.isLanded(phase)) return; + } + + doPower(eliteEntity); + + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 10); + } + + private void doPower(EliteEntity eliteEntity) { + doCooldown(eliteEntity); + + tornadoEye = eliteEntity.getLivingEntity().getLocation().clone().add(new Vector(6, -6, 0)) + .toVector().rotateAroundY(ThreadLocalRandom.current().nextDouble(0, 2 * Math.PI)) + .toLocation(eliteEntity.getLivingEntity().getWorld()); + + tornadoSpeed = tornadoEye.clone().subtract(eliteEntity.getLivingEntity().getLocation()).toVector().setY(0).normalize().multiply(0.2); + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + + if (!eliteEntity.isValid()) { + cancel(); + return; + } + + if (eliteEntity.getLivingEntity().getType().equals(EntityType.ENDER_DRAGON)) + ((EnderDragon) eliteEntity.getLivingEntity()).setPhase(EnderDragon.Phase.SEARCH_FOR_BREATH_ATTACK_TARGET); + + if (doExit(eliteEntity) || eliteEntity.getLivingEntity().getType().equals(EntityType.ENDER_DRAGON) && !EnderDragonPhaseSimplifier.isLanded(((EnderDragon) eliteEntity.getLivingEntity()).getPhase())) { + cancel(); + return; + } + + tornadoEye.add(tornadoSpeed); + + if (counter % 2 == 0) { + doTornadoParticles(); + doTerrainDestruction(eliteEntity); + doEntityDisplacement(eliteEntity.getLivingEntity()); + } + + if (counter > 20 * 6) { + cancel(); + } + + counter++; + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + } + + private void doTornadoParticles() { + for (int i = 0; i < 21; i++) + for (int x = 0; x < (i ^ 2 + 1); x++) { + Location randomParticleLocation = tornadoEye.clone().add((new Vector(i / 2, i, 0)) + .rotateAroundY(ThreadLocalRandom.current().nextDouble(2 * Math.PI))); + randomParticleLocation.setDirection(randomParticleLocation.toVector().rotateAroundY(0.5 * Math.PI)); + if (ThreadLocalRandom.current().nextDouble() < 0.7) + tornadoEye.getWorld().spawnParticle(Particle.SMOKE_LARGE, randomParticleLocation, 1, 0, 0, 0, 0.05); + else + tornadoEye.getWorld().spawnParticle(Particle.SOUL_FIRE_FLAME, randomParticleLocation, 1, 0, 0, 0, 0.05); + } + } + + private void doTerrainDestruction(EliteEntity eliteEntity) { + List blockList = new ArrayList<>(); + for (int i = 0; i < 5; i++) { + Location location = tornadoEye.clone().add(new Vector( + ThreadLocalRandom.current().nextInt(-5, 5), + 0, + ThreadLocalRandom.current().nextInt(-5, 5))); + Block block = location.getWorld().getHighestBlockAt(location); + if (block.getType().getBlastResistance() > 7) continue; + if (block.getLocation().getY() != -1) + blockList.add(block); + } + Explosion.generateFakeExplosion(blockList, eliteEntity.getLivingEntity(), this, tornadoEye.clone()); + } + + private void doEntityDisplacement(LivingEntity sourceEntity) { + for (Entity entity : tornadoEye.getWorld().getNearbyEntities(tornadoEye, 7, 21, 7)) + if (entity instanceof LivingEntity) { + if (entity.equals(sourceEntity)) continue; + Vector vector = entity.getLocation().clone().subtract(tornadoEye).toVector().rotateAroundY(0.5 * Math.PI) + .toLocation(entity.getWorld()).subtract(entity.getLocation().clone().subtract(tornadoEye).toVector()).toVector().normalize().multiply(0.5); + vector.setY(0.5); + entity.setVelocity(entity.getVelocity().add(vector)); + } + } + + @Override + protected void finishDeactivation(EliteEntity eliteEntity) { + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/enderdragon/bombardments/EnderDragonAimedFireball.java b/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/enderdragon/bombardments/EnderDragonAimedFireball.java new file mode 100644 index 000000000..a0e97e37d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/enderdragon/bombardments/EnderDragonAimedFireball.java @@ -0,0 +1,32 @@ +package com.magmaguy.elitemobs.powers.majorpowers.enderdragon.bombardments; + +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.meta.Bombardment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Fireball; + +public class EnderDragonAimedFireball extends Bombardment { + + public EnderDragonAimedFireball() { + super(PowersConfig.getPower("ender_dragon_aimed_fireball.yml")); + } + + @Override + public void taskBehavior(EliteEntity eliteEntity) { + if (super.firingTimer % 20 != 0) + return; + for (Entity entity : eliteEntity.getLivingEntity().getNearbyEntities(200, 100, 200)) + if (entity.getType().equals(EntityType.PLAYER)) { + Fireball fireball = ((Fireball) eliteEntity.getLivingEntity().getWorld().spawnEntity( + eliteEntity.getLivingEntity().getLocation(), + EntityType.FIREBALL)); + fireball.setDirection(entity.getLocation().clone().subtract(eliteEntity.getLivingEntity().getLocation()).toVector().normalize()); + fireball.setYield(5F); + EntityTracker.registerProjectileEntity(fireball); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/enderdragon/bombardments/EnderDragonArrowBombardment.java b/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/enderdragon/bombardments/EnderDragonArrowBombardment.java new file mode 100644 index 000000000..dda39c888 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/enderdragon/bombardments/EnderDragonArrowBombardment.java @@ -0,0 +1,45 @@ +package com.magmaguy.elitemobs.powers.majorpowers.enderdragon.bombardments; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.combatsystem.EliteProjectile; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.meta.Bombardment; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Projectile; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import java.util.concurrent.ThreadLocalRandom; + +public class EnderDragonArrowBombardment extends Bombardment { + + public EnderDragonArrowBombardment() { + super(PowersConfig.getPower("ender_dragon_arrow_bombardment.yml")); + } + + @Override + public void taskBehavior(EliteEntity eliteEntity) { + for (Entity entity : eliteEntity.getLivingEntity().getNearbyEntities(200, 100, 200)) + + if (entity.getType().equals(EntityType.PLAYER)) { + Vector shotVector = entity.getLocation().clone().add(new Vector(0, 1, 0)) + .subtract(eliteEntity.getLivingEntity().getLocation().clone()) + .add(new Vector(ThreadLocalRandom.current().nextDouble() - 0.5, + ThreadLocalRandom.current().nextDouble() - 0.5, + ThreadLocalRandom.current().nextDouble() - 0.5)) + .toVector().normalize().multiply(2); + + Projectile arrow = EliteProjectile.create(EntityType.ARROW, eliteEntity.getLivingEntity(), shotVector, false); + + //anti-lag measure, culls arrows after 4 seconds + new BukkitRunnable() { + @Override + public void run() { + arrow.remove(); + } + }.runTaskLater(MetadataHandler.PLUGIN, 20L * 4); + } + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/enderdragon/bombardments/EnderDragonEnderFireballBombardment.java b/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/enderdragon/bombardments/EnderDragonEnderFireballBombardment.java new file mode 100644 index 000000000..f146034c0 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/enderdragon/bombardments/EnderDragonEnderFireballBombardment.java @@ -0,0 +1,29 @@ +package com.magmaguy.elitemobs.powers.majorpowers.enderdragon.bombardments; + +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.meta.Bombardment; +import org.bukkit.entity.DragonFireball; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; + +import java.util.concurrent.ThreadLocalRandom; + +public class EnderDragonEnderFireballBombardment extends Bombardment { + + public EnderDragonEnderFireballBombardment() { + super(PowersConfig.getPower("ender_dragon_ender_fireball_bombardment.yml")); + } + + @Override + public void taskBehavior(EliteEntity eliteEntity) { + if (ThreadLocalRandom.current().nextDouble() > 0.1) return; + for (Entity entity : eliteEntity.getLivingEntity().getNearbyEntities(200, 100, 200)) + if (entity.getType().equals(EntityType.PLAYER)) + ((DragonFireball) eliteEntity.getLivingEntity().getWorld().spawnEntity( + eliteEntity.getLivingEntity().getLocation(), + EntityType.DRAGON_FIREBALL)).setDirection( + entity.getLocation().clone().subtract(eliteEntity.getLivingEntity().getLocation()).toVector().normalize()); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/enderdragon/bombardments/EnderDragonEndermiteBombardment.java b/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/enderdragon/bombardments/EnderDragonEndermiteBombardment.java new file mode 100644 index 000000000..1f039ed71 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/enderdragon/bombardments/EnderDragonEndermiteBombardment.java @@ -0,0 +1,47 @@ +package com.magmaguy.elitemobs.powers.majorpowers.enderdragon.bombardments; + +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import com.magmaguy.elitemobs.powers.meta.Bombardment; +import com.magmaguy.elitemobs.utils.WarningMessage; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.util.Vector; + +public class EnderDragonEndermiteBombardment extends Bombardment { + public EnderDragonEndermiteBombardment() { + super(PowersConfig.getPower("ender_dragon_endermite_bombardment.yml")); + } + + @Override + public void taskBehavior(EliteEntity eliteEntity) { + try { + + Vector direction = eliteEntity.getLivingEntity().getLocation().getDirection(); + + float rotation = (float) (Math.atan2(direction.getX(), direction.getZ()) * 180 / Math.PI); + + Vector direction1 = new Vector(1, -4, 0); + Vector direction2 = new Vector(-1, -4, 0); + + direction1 = direction1.rotateAroundY(rotation); + direction2 = direction2.rotateAroundY(rotation); + + + CustomBossEntity customBossEntity1 = CustomBossEntity.createCustomBossEntity("binder_of_worlds_phase_1_endermite_reinforcement.yml"); + customBossEntity1.spawn(eliteEntity.getLivingEntity().getLocation().clone().add(direction1), false); + customBossEntity1.getLivingEntity().addPotionEffect(new PotionEffect(PotionEffectType.SLOW_FALLING, 20 * 5, 0)); + eliteEntity.addReinforcement(customBossEntity1); + + CustomBossEntity customBossEntity2 = CustomBossEntity.createCustomBossEntity("binder_of_worlds_phase_1_endermite_reinforcement.yml"); + customBossEntity2.spawn(eliteEntity.getLivingEntity().getLocation().clone().add(direction2), false); + customBossEntity2.getLivingEntity().addPotionEffect(new PotionEffect(PotionEffectType.SLOW_FALLING, 20 * 5, 0)); + eliteEntity.addReinforcement(customBossEntity2); + + } catch (Exception ex) { + new WarningMessage("Failed to spawn binder of world's reinforcement endermite!"); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/enderdragon/bombardments/EnderDragonFireballBombardment.java b/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/enderdragon/bombardments/EnderDragonFireballBombardment.java new file mode 100644 index 000000000..0ea7f2683 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/enderdragon/bombardments/EnderDragonFireballBombardment.java @@ -0,0 +1,44 @@ +package com.magmaguy.elitemobs.powers.majorpowers.enderdragon.bombardments; + +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.meta.Bombardment; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Fireball; +import org.bukkit.util.Vector; + +public class EnderDragonFireballBombardment extends Bombardment { + public EnderDragonFireballBombardment() { + super(PowersConfig.getPower("ender_dragon_fireball_bombardment.yml")); + } + + @Override + public void taskBehavior(EliteEntity eliteEntity) { + if (super.firingTimer % 10 != 0) + return; + + Vector direction = eliteEntity.getLivingEntity().getLocation().getDirection(); + + float rotation = (float) (Math.atan2(direction.getX(), direction.getZ()) * 180 / Math.PI); + + Vector direction1 = new Vector(3, -4, 0); + Vector direction2 = new Vector(-3, -4, 0); + + direction1 = direction1.rotateAroundY(rotation); + direction2 = direction2.rotateAroundY(rotation); + + generateFireball(eliteEntity, direction1); + generateFireball(eliteEntity, direction2); + } + + private void generateFireball(EliteEntity eliteEntity, Vector vector) { + Fireball fireball = ((Fireball) eliteEntity.getLivingEntity().getWorld().spawnEntity( + eliteEntity.getLivingEntity().getLocation().clone().add(vector), + EntityType.FIREBALL)); + fireball.setDirection(new Vector(0, -0.1, 0)); + fireball.setYield(5F); + EntityTracker.registerProjectileEntity(fireball); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/enderdragon/bombardments/EnderDragonPotionBombardment.java b/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/enderdragon/bombardments/EnderDragonPotionBombardment.java new file mode 100644 index 000000000..30f5464e2 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/enderdragon/bombardments/EnderDragonPotionBombardment.java @@ -0,0 +1,54 @@ +package com.magmaguy.elitemobs.powers.majorpowers.enderdragon.bombardments; + +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.meta.Bombardment; +import org.bukkit.Material; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.ThrownPotion; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.PotionMeta; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.util.Vector; + +import java.util.concurrent.ThreadLocalRandom; + + +public class EnderDragonPotionBombardment extends Bombardment { + + public EnderDragonPotionBombardment() { + super(PowersConfig.getPower("ender_dragon_potion_bombardment.yml")); + } + + @Override + public void taskBehavior(EliteEntity eliteEntity) { + for (int i = 0; i < 5; i++) { + + ItemStack itemStack = new ItemStack(Material.SPLASH_POTION); + PotionMeta potionMeta = (PotionMeta) itemStack.getItemMeta(); + if (ThreadLocalRandom.current().nextBoolean()) + potionMeta.addCustomEffect(new PotionEffect(PotionEffectType.HARM, 0, 1), true); + else potionMeta.addCustomEffect(new PotionEffect(PotionEffectType.SLOW, 0, 1), true); + + itemStack.setItemMeta(potionMeta); + + + ThrownPotion thrownPotion = (ThrownPotion) eliteEntity.getLivingEntity().getWorld().spawnEntity( + eliteEntity.getLivingEntity().getLocation().clone().subtract( + new Vector(ThreadLocalRandom.current().nextInt(-1, 1), + 1, + ThreadLocalRandom.current().nextInt(-1, 1))) + , EntityType.SPLASH_POTION); + + thrownPotion.setItem(itemStack); + + thrownPotion.setVelocity( + new Vector(ThreadLocalRandom.current().nextDouble() - 0.5, + 0, + ThreadLocalRandom.current().nextDouble() - 0.5)); + + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/skeleton/SkeletonPillar.java b/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/skeleton/SkeletonPillar.java new file mode 100644 index 000000000..9675072aa --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/skeleton/SkeletonPillar.java @@ -0,0 +1,300 @@ +package com.magmaguy.elitemobs.powers.majorpowers.skeleton; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.powers.meta.MajorPower; +import com.magmaguy.elitemobs.powerstances.GenericRotationMatrixMath; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.Sound; +import org.bukkit.entity.*; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.concurrent.ThreadLocalRandom; + +public class SkeletonPillar extends MajorPower implements Listener { + + private Location soundLocation; + + public SkeletonPillar() { + super(PowersConfig.getPower("skeleton_pillar.yml")); + } + + @EventHandler + public void onHit(EliteMobDamagedByPlayerEvent event) { + SkeletonPillar skeletonPillar = (SkeletonPillar) event.getEliteMobEntity().getPower(this); + if (skeletonPillar == null) return; + if (skeletonPillar.isInGlobalCooldown()) return; + + /* + Run random check to see if the power should activate + */ + if (ThreadLocalRandom.current().nextDouble() > 0.20) return; + skeletonPillar.doGlobalCooldown(20 * 27); + + event.getEliteMobEntity().getLivingEntity().setAI(false); + playPillarSong(event.getEntity().getLocation()); + + Location location1 = event.getEliteMobEntity().getLivingEntity().getLocation().clone() + .add(locationMover(event.getEliteMobEntity().getLivingEntity().getLocation().clone(), 20, 7)); + Location location2 = event.getEliteMobEntity().getLivingEntity().getLocation().clone() + .add(locationMover(event.getEliteMobEntity().getLivingEntity().getLocation().clone(), 20, -7)); + + new BukkitRunnable() { + + int timer = 1; + + @Override + public void run() { + + if (timer > 20 * 7 || !event.getEliteMobEntity().isValid()) { + + if (event.getEliteMobEntity().getLivingEntity() != null) + event.getEliteMobEntity().getLivingEntity().setAI(true); + cancel(); + + } else if (timer > 20 * 1 && timer < 20 * 7) { + + pillarEffect(event.getEliteMobEntity().getLivingEntity().getLocation().clone(), timer, 7); + pillarEffect(event.getEliteMobEntity().getLivingEntity().getLocation().clone(), timer, -7); + + } else { + + pillarWarningEffect(location1); + pillarWarningEffect(location2); + + } + + timer++; + + } + + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + + } + + private void pillarEffect(Location location, int timer, int offset) { + location.add(locationMover(location, timer, offset)); + location.getWorld().spawnParticle(Particle.EXPLOSION_NORMAL, location, 15, 0.1, 5, 0.1, 0.05); + pillarDamage(location); + } + + private void pillarWarningEffect(Location location) { + location.getWorld().spawnParticle(Particle.SMOKE_LARGE, location, 5, 0.1, 5, 0.1, 0.05); + } + + private void pillarDamage(Location location) { + for (Entity entity : location.getWorld().getNearbyEntities(location, 2, 5, 2)) + if (entity instanceof LivingEntity && !(entity instanceof Pig || entity instanceof Cow || entity instanceof Chicken || + entity instanceof Wolf || entity instanceof Llama || entity instanceof Ocelot || entity instanceof Horse || + entity instanceof Sheep || entity instanceof Rabbit || entity instanceof Parrot || entity instanceof Villager)) { + + LivingEntity livingEntity = (LivingEntity) entity; + + if (livingEntity.isValid()) + livingEntity.damage(1); + } + } + + private Location locationMover(Location location, int timer, int offset) { + int numberOfPointsPerRotation = 20 * 3; + Location newLocation = GenericRotationMatrixMath.applyRotation(0, 1, 0, numberOfPointsPerRotation, + 0, 0, offset, timer).toLocation(location.getWorld()); + return newLocation; + } + + private void playPillarSong(Location location) { + soundLocation = location; + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + counter++; + switch (counter) { + case 1: + playSound(d()); + break; + case 2: + playSound(d()); + break; + case 4: + playSound(eHigher()); + break; + case 7: + playSound(aHigher()); + break; + case 10: + playSound(aSharpHigher()); + break; + case 12: + playSound(gHigher()); + break; + case 14: + playSound(f()); + break; + case 16: + playSound(f()); + break; + case 17: + playSound(d()); + break; + case 18: + playSound(f()); + break; + case 19: + playSound(gHigher()); + break; + case 21: + playSound(c()); + break; + case 22: + playSound(c()); + break; + case 24: + playSound(eHigher()); + break; + case 27: + playSound(aHigher()); + break; + case 30: + playSound(aSharpHigher()); + break; + case 32: + playSound(gHigher()); + break; + case 34: + playSound(f()); + break; + case 36: + playSound(f()); + break; + case 37: + playSound(d()); + break; + case 38: + playSound(f()); + break; + case 39: + playSound(gHigher()); + break; + case 41: + playSound(b()); + break; + case 42: + playSound(b()); + break; + case 44: + playSound(eHigher()); + break; + case 47: + playSound(aHigher()); + break; + case 50: + playSound(aSharpHigher()); + break; + case 52: + playSound(gHigher()); + break; + case 54: + playSound(f()); + break; + case 56: + playSound(f()); + break; + case 57: + playSound(d()); + break; + case 58: + playSound(f()); + break; + case 59: + playSound(gHigher()); + break; + case 61: + playSound(aSharp()); + break; + case 62: + playSound(aSharp()); + break; + case 64: + playSound(eHigher()); + break; + case 67: + playSound(aHigher()); + break; + case 70: + playSound(aSharpHigher()); + break; + case 72: + playSound(gHigher()); + break; + case 74: + playSound(f()); + break; + case 76: + playSound(f()); + break; + case 77: + playSound(d()); + break; + case 78: + playSound(f()); + break; + case 79: + playSound(gHigher()); + break; + case 80: + cancel(); + break; + default: + break; + } + } + }.runTaskTimer(MetadataHandler.PLUGIN, 1, 2); + } + + private void playSound(float pitch) { + soundLocation.getWorld().playSound(soundLocation, Sound.BLOCK_NOTE_BLOCK_IRON_XYLOPHONE, 2f, pitch); + } + + private float d() { + return 0.793701f; + } + + private float eHigher() { + return 1.781797f; + } + + private float aHigher() { + return 1.189207f; + } + + private float aSharpHigher() { + return 1.259921f; + } + + private float gHigher() { + return 1.122462f; + } + + private float f() { + return 0.943874f; + } + + private float c() { + return 0.707107f; + } + + private float b() { + return 0.667420f; + } + + private float aSharp() { + return 0.629961f; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/skeleton/SkeletonTrackingArrow.java b/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/skeleton/SkeletonTrackingArrow.java new file mode 100644 index 000000000..353313b15 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/skeleton/SkeletonTrackingArrow.java @@ -0,0 +1,87 @@ +package com.magmaguy.elitemobs.powers.majorpowers.skeleton; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobTargetPlayerEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.meta.MajorPower; +import com.magmaguy.elitemobs.powers.offensivepowers.AttackArrow; +import org.bukkit.GameMode; +import org.bukkit.Particle; +import org.bukkit.entity.Arrow; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +public class SkeletonTrackingArrow extends MajorPower implements Listener { + + public SkeletonTrackingArrow() { + super(PowersConfig.getPower("skeleton_tracking_arrow.yml")); + } + + private static void trackingArrowLoop(Player player, Arrow arrow) { + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + if (player.isValid() && arrow.isValid() && arrow.getWorld().equals(player.getWorld()) + && player.getLocation().distanceSquared(arrow.getLocation()) < 900 && !arrow.isOnGround()) { + if (counter % 10 == 0) + arrow.setVelocity(arrow.getVelocity().add(arrowAdjustmentVector(arrow, player))); + arrow.getWorld().spawnParticle(Particle.FLAME, arrow.getLocation(), 10, 0.01, 0.01, 0.01, 0.01); + } else { + arrow.setGravity(true); + cancel(); + } + if (counter > 20 * 60) { + arrow.setGravity(true); + cancel(); + } + counter++; + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + } + + private static Vector arrowAdjustmentVector(Arrow arrow, Player player) { + return player.getEyeLocation().clone().subtract(new Vector(0, 0.5, 0)).subtract(arrow.getLocation()).toVector().normalize().multiply(0.1); + } + + @EventHandler + public void targetEvent(EliteMobTargetPlayerEvent event) { + SkeletonTrackingArrow skeletonTrackingArrow = (SkeletonTrackingArrow) event.getEliteMobEntity().getPower(this); + if (skeletonTrackingArrow == null) return; + if (skeletonTrackingArrow.isFiring()) return; + + skeletonTrackingArrow.setFiring(true); + repeatingTrackingArrowTask(event.getEliteMobEntity(), skeletonTrackingArrow); + } + + private void repeatingTrackingArrowTask(EliteEntity eliteEntity, SkeletonTrackingArrow skeletonTrackingArrow) { + new BukkitRunnable() { + + @Override + public void run() { + if (!eliteEntity.isValid()) { + skeletonTrackingArrow.setFiring(false); + cancel(); + return; + } + for (Entity nearbyEntity : eliteEntity.getLivingEntity().getNearbyEntities(20, 20, 20)) + if (nearbyEntity instanceof Player) + if (((Player) nearbyEntity).getGameMode().equals(GameMode.ADVENTURE) || + ((Player) nearbyEntity).getGameMode().equals(GameMode.SURVIVAL)) { + Arrow arrow = AttackArrow.shootArrow(eliteEntity.getLivingEntity(), (Player) nearbyEntity); + arrow.setVelocity(arrow.getVelocity().multiply(0.1)); + arrow.setGravity(false); + trackingArrowLoop((Player) nearbyEntity, arrow); + } + } + + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 20 * 8); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobpowers/majorpowers/ZombieBloat.java b/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/zombie/ZombieBloat.java similarity index 53% rename from src/main/java/com/magmaguy/elitemobs/mobpowers/majorpowers/ZombieBloat.java rename to src/main/java/com/magmaguy/elitemobs/powers/majorpowers/zombie/ZombieBloat.java index c49f91fe0..4633e7dc2 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobpowers/majorpowers/ZombieBloat.java +++ b/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/zombie/ZombieBloat.java @@ -1,94 +1,47 @@ -/* - * 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 . - */ - -/* - * 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 . - */ - -/* - * 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 . - */ - -package com.magmaguy.elitemobs.mobpowers.majorpowers; +package com.magmaguy.elitemobs.powers.majorpowers.zombie; import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.config.ConfigValues; +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerEvent; import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; -import com.magmaguy.elitemobs.mobpowers.PowerCooldown; -import com.magmaguy.elitemobs.mobpowers.minorpowers.EventValidator; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.powers.meta.MajorPower; import org.bukkit.Location; import org.bukkit.Particle; -import org.bukkit.entity.*; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Giant; +import org.bukkit.entity.LivingEntity; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageEvent; import org.bukkit.scheduler.BukkitRunnable; import org.bukkit.util.Vector; import java.util.ArrayList; -import java.util.HashSet; import java.util.List; import java.util.concurrent.ThreadLocalRandom; public class ZombieBloat extends MajorPower implements Listener { - private static HashSet cooldowns = new HashSet<>(); - - @Override - public void applyPowers(Entity entity) { + public ZombieBloat() { + super(PowersConfig.getPower("zombie_bloat.yml")); } @EventHandler - public void onHit(EntityDamageEvent event) { + public void onHit(EliteMobDamagedByPlayerEvent event) { + ZombieBloat zombieBloat = (ZombieBloat) event.getEliteMobEntity().getPower(this); + if (zombieBloat == null) return; + if (zombieBloat.isInGlobalCooldown()) return; - EliteMobEntity eliteMobEntity = EventValidator.getEventEliteMob(this, event); - if (eliteMobEntity == null) return; - if (cooldowns.contains(eliteMobEntity)) return; if (ThreadLocalRandom.current().nextDouble() > 0.20) return; - cooldowns.add(eliteMobEntity); + zombieBloat.doGlobalCooldown(20 * 10); /* Create early warning that entity is about to bloat */ new BukkitRunnable() { - int timer = 1; - Zombie eventZombie = (Zombie) event.getEntity(); + final LivingEntity eventZombie = (LivingEntity) event.getEntity(); + int timer = 0; @Override public void run() { @@ -98,33 +51,23 @@ public void run() { cancel(); } - if (timer == 21) { - /* - Remove AI to prevent entity from moving while effect activates - */ + if (timer == 21) eventZombie.setAI(false); - /* - Start power cooldown, 10 seconds - */ - PowerCooldown.startCooldownTimer(eliteMobEntity, cooldowns, 10 * 20); - } - if (ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.ENABLE_WARNING_VISUAL_EFFECTS)) + + if (MobCombatSettingsConfig.isEnableWarningVisualEffects()) eventZombie.getWorld().spawnParticle(Particle.TOTEM, new Location(eventZombie.getWorld(), eventZombie.getLocation().getX(), eventZombie.getLocation().getY() + eventZombie.getHeight(), eventZombie.getLocation().getZ()), 20, timer / 24, - timer / 9, timer / 24, 0.1); + timer / 9d, timer / 24d, 0.1); timer++; - } }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); - - } - private void bloatEffect(Zombie eventZombie) { + private void bloatEffect(LivingEntity eventZombie) { /* Spawn giant for "bloat" effect */ @@ -146,7 +89,6 @@ private void bloatEffect(Zombie eventZombie) { for (LivingEntity livingEntity : nearbyValidLivingEntities) { - Location livingEntityLocation = livingEntity.getLocation(); Vector toLivingEntityVector = livingEntityLocation.subtract(entityLocation).toVector(); @@ -157,13 +99,9 @@ private void bloatEffect(Zombie eventZombie) { normalizedVector = normalizedVector.multiply(new Vector(2, 0, 2)).add(new Vector(0, 1, 0)); try { - livingEntity.setVelocity(normalizedVector); - } catch (Exception e) { - - //Entity was too recent to set a velocity? - + livingEntity.setVelocity(new Vector(0, 1.5, 0)); } } @@ -177,10 +115,8 @@ private void bloatEffect(Zombie eventZombie) { @Override public void run() { - giant.remove(); eventZombie.setAI(true); - } }.runTaskLater(MetadataHandler.PLUGIN, 10); @@ -188,21 +124,17 @@ public void run() { } private void livingEntityEffect(List livingEntities) { - if (livingEntities.size() == 0) return; - if (!ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.ENABLE_WARNING_VISUAL_EFFECTS)) + if (!MobCombatSettingsConfig.isEnableWarningVisualEffects()) return; new BukkitRunnable() { - int counter = 0; @Override public void run() { - if (counter > 1.5 * 20) cancel(); - for (LivingEntity livingEntity : livingEntities) if (!(livingEntity == null || livingEntity.isDead() || !livingEntity.isValid())) livingEntity.getWorld().spawnParticle(Particle.CLOUD, new Location(livingEntity.getWorld(), @@ -210,13 +142,10 @@ public void run() { livingEntity.getLocation().getY() + livingEntity.getHeight() - 1, livingEntity.getLocation().getZ()), 0, 0, 0, 0); - counter++; - } }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); - } } diff --git a/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/zombie/ZombieFriends.java b/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/zombie/ZombieFriends.java new file mode 100644 index 000000000..ad58d0ba1 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/zombie/ZombieFriends.java @@ -0,0 +1,98 @@ +package com.magmaguy.elitemobs.powers.majorpowers.zombie; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.config.powers.premade.ZombieFriendsConfig; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import com.magmaguy.elitemobs.powers.meta.MajorPower; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.concurrent.ThreadLocalRandom; + +/** + * Created by MagmaGuy on 18/05/2017. + */ +public class ZombieFriends extends MajorPower implements Listener { + + public ZombieFriends() { + super(PowersConfig.getPower("zombie_friends.yml")); + } + + @EventHandler + public void onHit(EliteMobDamagedByPlayerEvent event) { + ZombieFriends zombieFriendConfig = (ZombieFriends) event.getEliteMobEntity().getPower(this); + if (zombieFriendConfig == null) return; + if (zombieFriendConfig.isFiring()) return; + + if (ThreadLocalRandom.current().nextDouble() > 0.01) return; + zombieFriendConfig.setFiring(true); + + CustomBossEntity reinforcement1 = CustomBossEntity.createCustomBossEntity("zombie_friends_friend.yml"); + reinforcement1.spawn(event.getEntity().getLocation(), event.getEliteMobEntity().getLevel(), false); + CustomBossEntity reinforcement2 = CustomBossEntity.createCustomBossEntity("zombie_friends_friend.yml"); + reinforcement2.spawn(event.getEntity().getLocation(), event.getEliteMobEntity().getLevel(), false); + + new BukkitRunnable() { + @Override + public void run() { + if (!event.getEliteMobEntity().isValid() || !reinforcement1.isValid() && !reinforcement2.isValid()) { + + if (reinforcement1 != null && reinforcement1.isValid()) { + nameClearer(reinforcement1); + reinforcement1.getLivingEntity().setCustomName(ChatColorConverter.convert(ZombieFriendsConfig.friendDeathMessage + .get(ThreadLocalRandom.current().nextInt(ZombieFriendsConfig.friendDeathMessage.size())))); + } + + if (reinforcement2 != null && reinforcement2.isValid()) { + nameClearer(reinforcement2); + reinforcement2.getLivingEntity().setCustomName(ChatColorConverter.convert(ZombieFriendsConfig.friendDeathMessage + .get(ThreadLocalRandom.current().nextInt(ZombieFriendsConfig.friendDeathMessage.size())))); + } + + cancel(); + return; + + } else { + + if (ThreadLocalRandom.current().nextDouble() < 0.5) { + nameClearer(event.getEliteMobEntity()); + event.getEliteMobEntity().getLivingEntity().setCustomName(ChatColorConverter.convert(ZombieFriendsConfig.originalEntityDialog + .get(ThreadLocalRandom.current().nextInt(ZombieFriendsConfig.originalEntityDialog.size())))); + } + + if (ThreadLocalRandom.current().nextDouble() < 0.5 && reinforcement1.isValid()) { + nameClearer(reinforcement1); + reinforcement1.getLivingEntity().setCustomName(ChatColorConverter.convert(ZombieFriendsConfig.reinforcementDialog + .get(ThreadLocalRandom.current().nextInt(ZombieFriendsConfig.reinforcementDialog.size())))); + } + + if (ThreadLocalRandom.current().nextDouble() < 0.5 && reinforcement2.isValid()) { + nameClearer(reinforcement2); + reinforcement2.getLivingEntity().setCustomName(ChatColorConverter.convert(ZombieFriendsConfig.reinforcementDialog + .get(ThreadLocalRandom.current().nextInt(ZombieFriendsConfig.reinforcementDialog.size())))); + } + + } + } + }.runTaskTimer(MetadataHandler.PLUGIN, 20, 20 * 8); + + } + + private void nameClearer(EliteEntity eliteEntity) { + + new BukkitRunnable() { + @Override + public void run() { + if (eliteEntity.isValid()) + eliteEntity.setName(eliteEntity.getName(), true); + } + }.runTaskLater(MetadataHandler.PLUGIN, 20 * 3); + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/zombie/ZombieNecronomicon.java b/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/zombie/ZombieNecronomicon.java new file mode 100644 index 000000000..ecdb61ea4 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/zombie/ZombieNecronomicon.java @@ -0,0 +1,267 @@ +package com.magmaguy.elitemobs.powers.majorpowers.zombie; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerEvent; +import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import com.magmaguy.elitemobs.powers.meta.MajorPower; +import com.magmaguy.elitemobs.powerstances.GenericRotationMatrixMath; +import com.magmaguy.elitemobs.powerstances.VisualItemInitializer; +import com.magmaguy.elitemobs.utils.WarningMessage; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Item; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.inventory.ItemStack; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +import static com.magmaguy.elitemobs.ChatColorConverter.convert; + +/** + * Created by MagmaGuy on 18/05/2017. + */ +public class ZombieNecronomicon extends MajorPower implements Listener { + + private int chantIndex = 0; + //todo: Shouldn't this be static? + + public ZombieNecronomicon() { + super(PowersConfig.getPower("zombie_necronomicon.yml")); + } + + @EventHandler + public void onPlayerDetect(EliteMobDamagedByPlayerEvent event) { + ZombieNecronomicon zombieNecronomicon = (ZombieNecronomicon) event.getEliteMobEntity().getPower(this); + if (zombieNecronomicon == null) return; + if (zombieNecronomicon.isFiring()) return; + + zombieNecronomicon.setFiring(true); + necronomiconVisualEffect(event.getEliteMobEntity(), zombieNecronomicon); + spawnReinforcements(event.getEliteMobEntity(), event.getPlayer(), zombieNecronomicon); + } + + private void necronomiconVisualEffect(EliteEntity eliteEntity, ZombieNecronomicon zombieNecronomicon) { + + LivingEntity livingEntity = eliteEntity.getLivingEntity(); + livingEntity.setAI(false); + zombieNecronomicon.setFiring(true); + nameScroller(livingEntity, zombieNecronomicon); + + if (!MobCombatSettingsConfig.isEnableWarningVisualEffects()) + return; + + new BukkitRunnable() { + final HashMap> fourTrack = new HashMap<>(); + int counter = 0; + + @Override + public void run() { + if (!livingEntity.isValid() || livingEntity.hasAI()) { + for (List itemList : fourTrack.values()) + for (Item item : itemList) + item.remove(); + if (livingEntity.isValid()) + livingEntity.setCustomName(EntityTracker.getEliteMobEntity(livingEntity).getName()); + zombieNecronomicon.setFiring(false); + cancel(); + return; + } + + if (counter == 0) { + + //establish 4tracks + for (int i = 0; i < 8; i++) { + List itemList = new ArrayList<>(); + for (int j = 0; j < 4; j++) { + ItemStack itemStack = new ItemStack(Material.WRITTEN_BOOK, 1); + Item item = VisualItemInitializer.initializeItem(itemStack, livingEntity.getLocation()); + itemList.add(item); + } + fourTrack.put(i, itemList); + } + } else + itemMover(fourTrack, livingEntity, counter); + + counter++; + } + + }.runTaskTimer(MetadataHandler.PLUGIN, 5, 5); + + } + + private void itemMover(HashMap> xTrack, Entity entity, int counter) { + + double a = 0; + double b = 1; + double c = 0; + + double numberOfPointsPerFullRotation = 64; + + double x = 0; + double y = 0; + double z; + + for (int trackNumber : xTrack.keySet()) { + + List itemList = xTrack.get(trackNumber); + + for (Item item : itemList) { + + //each track is offset by 45 degrees + //items are then offset on the Z value depending on their position + + z = (itemList.indexOf(item) + 1); + + //to predict the counter offset value you have to divide 8 (for 8 tracks total) + + int newCounter = (int) (counter + trackNumber * (numberOfPointsPerFullRotation / 8)); + + Location currentLocation = item.getLocation(); + + Location centerLocationFixed = entity.getLocation().add(0, 3, 0); + + Vector vector = GenericRotationMatrixMath.applyRotation(a, b, c, numberOfPointsPerFullRotation, x, y, z, newCounter); + Location newLocation = new Location(entity.getWorld(), vector.getX(), vector.getY(), vector.getZ()).add(centerLocationFixed); + + Vector velocity = (newLocation.subtract(currentLocation)).toVector().multiply(0.3); + item.setVelocity(velocity); + + } + + } + + } + + private void nameScroller(LivingEntity livingEntity, ZombieNecronomicon zombieNecronomicon) { + + new BukkitRunnable() { + final String fullChant = convert(PowersConfig.getPower("zombie_necronomicon.yml").getFileConfiguration().getString("summoningChant")); + + @Override + public void run() { + + if (!livingEntity.isValid() || livingEntity.hasAI()) { + cancel(); + return; + } + + if (zombieNecronomicon.chantIndex + 31 > fullChant.length()) + zombieNecronomicon.chantIndex = 0; + + String subString = fullChant.substring(zombieNecronomicon.chantIndex, zombieNecronomicon.chantIndex + 31); + livingEntity.setCustomName(subString); + zombieNecronomicon.chantIndex++; + } + + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + + } + + private void spawnReinforcements(EliteEntity eliteEntity, LivingEntity targetted, ZombieNecronomicon zombieNecronomicon) { + + LivingEntity targetter = eliteEntity.getLivingEntity(); + + new BukkitRunnable() { + + final ArrayList entityList = new ArrayList<>(); + + @Override + public void run() { + + if (!eliteEntity.isValid() || !targetted.isValid() || !targetter.isValid() || targetted.getWorld() != targetter.getWorld() + || targetted.getLocation().distance(targetter.getLocation()) > 30) { + + for (Entity entity : entityList) + if (entity.isValid()) + entity.remove(); + + if (eliteEntity.isValid()) + targetter.setAI(true); + cancel(); + return; + + } + + int randomizedNumber = ThreadLocalRandom.current().nextInt(5) + 1; + + entityList.removeIf(currentEntity -> !currentEntity.isValid()); + + if (entityList.size() < 11) { + + targetter.setAI(false); + + if (!zombieNecronomicon.isFiring()) + necronomiconVisualEffect(eliteEntity, zombieNecronomicon); + + if (randomizedNumber < 5) { + + CustomBossEntity customBossEntity = CustomBossEntity.createCustomBossEntity("necronomicon_zombie.yml"); + if (customBossEntity == null) { + new WarningMessage("necronomicon_zombie.yml is not valid!"); + return; + } + customBossEntity.spawn(targetter.getLocation(), eliteEntity.getLevel(), false); + + if (!customBossEntity.exists() || !customBossEntity.getLivingEntity().isValid()) { + targetter.setAI(true); + cancel(); + targetter.setAI(true); + cancel(); + return; + } + + customBossEntity.getLivingEntity().setVelocity(new Vector((ThreadLocalRandom.current().nextDouble() - 0.5) / 30, 0.5, + (ThreadLocalRandom.current().nextDouble() - 0.5) / 30)); + + eliteEntity.addReinforcement(customBossEntity); + + entityList.add(customBossEntity.getLivingEntity()); + + } else { + + CustomBossEntity customBossEntity = CustomBossEntity.createCustomBossEntity("necronomicon_skeleton.yml"); + if (customBossEntity == null) { + new WarningMessage("necronomicon_skeleton.yml is not valid!"); + targetter.setAI(true); + cancel(); + return; + } + customBossEntity.spawn(targetter.getLocation(), eliteEntity.getLevel(), false); + + if (!customBossEntity.getLivingEntity().isValid()) { + targetter.setAI(true); + cancel(); + return; + } + + customBossEntity.getLivingEntity().setVelocity(new Vector((ThreadLocalRandom.current().nextDouble() - 0.5) / 30, 0.5, + (ThreadLocalRandom.current().nextDouble() - 0.5) / 30)); + + eliteEntity.addReinforcement(customBossEntity); + + entityList.add(customBossEntity.getLivingEntity()); + + } + + } else + targetter.setAI(true); + + } + + }.runTaskTimer(MetadataHandler.PLUGIN, 20 * 3L, 20 * 3L); + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/zombie/ZombieParents.java b/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/zombie/ZombieParents.java new file mode 100644 index 000000000..5e91e8dd0 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/majorpowers/zombie/ZombieParents.java @@ -0,0 +1,113 @@ +package com.magmaguy.elitemobs.powers.majorpowers.zombie; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.config.powers.premade.ZombieParentsConfig; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import com.magmaguy.elitemobs.powers.meta.MajorPower; +import com.magmaguy.elitemobs.utils.WarningMessage; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.concurrent.ThreadLocalRandom; + +/** + * Created by MagmaGuy on 13/05/2017. + */ +public class ZombieParents extends MajorPower implements Listener { + + public ZombieParents() { + super(PowersConfig.getPower("zombie_parents.yml")); + } + + private static void startDialog(CustomBossEntity reinforcementMom, CustomBossEntity reinforcementDad, EliteEntity bossEntity) { + new BukkitRunnable() { + @Override + public void run() { + if (!bossEntity.isValid()) { + doDeathMessages(reinforcementDad, reinforcementMom); + cancel(); + } else { + doDialog(reinforcementDad, reinforcementMom, bossEntity); + } + } + }.runTaskTimer(MetadataHandler.PLUGIN, 20, 20L * 8); + } + + private static void doDeathMessages(CustomBossEntity reinforcementDad, CustomBossEntity reinforcementMom) { + if (reinforcementDad.isValid()) { + nameClearer(reinforcementDad); + reinforcementDad.getLivingEntity().setCustomName(ZombieParentsConfig.getDeathMessage(). + get(ThreadLocalRandom.current().nextInt(ZombieParentsConfig.getDeathMessage().size()))); + } + + if (reinforcementMom.isValid()) { + nameClearer(reinforcementMom); + reinforcementMom.getLivingEntity().setCustomName(ZombieParentsConfig.getDeathMessage(). + get(ThreadLocalRandom.current().nextInt(ZombieParentsConfig.getDeathMessage().size()))); + } + } + + private static void doDialog(CustomBossEntity reinforcementDad, CustomBossEntity reinforcementMom, EliteEntity bossEntity) { + if (ThreadLocalRandom.current().nextDouble() < 0.5) { + nameClearer(bossEntity); + bossEntity.getLivingEntity().setCustomName(ZombieParentsConfig.getBossEntityDialog(). + get(ThreadLocalRandom.current().nextInt(ZombieParentsConfig.getBossEntityDialog().size()))); + } + + if (ThreadLocalRandom.current().nextDouble() < 0.5 && reinforcementDad.isValid()) { + nameClearer(reinforcementDad); + reinforcementDad.getLivingEntity().setCustomName(ZombieParentsConfig.getZombieDad(). + get(ThreadLocalRandom.current().nextInt(ZombieParentsConfig.getZombieDad().size()))); + } + + if (ThreadLocalRandom.current().nextDouble() < 0.5 && reinforcementMom.isValid()) { + nameClearer(reinforcementMom); + reinforcementMom.getLivingEntity().setCustomName(ZombieParentsConfig.getZombieMom(). + get(ThreadLocalRandom.current().nextInt(ZombieParentsConfig.getZombieMom().size()))); + } + } + + private static void nameClearer(EliteEntity eliteEntity) { + + new BukkitRunnable() { + @Override + public void run() { + if (eliteEntity.isValid()) + eliteEntity.setName(eliteEntity.getName(), true); + } + }.runTaskLater(MetadataHandler.PLUGIN, 20L * 3); + + } + + @EventHandler + public void onHit(EliteMobDamagedByPlayerEvent event) { + ZombieParents zombieParents = (ZombieParents) event.getEliteMobEntity().getPower(this); + if (zombieParents == null) return; + if (zombieParents.isFiring()) return; + + if (ThreadLocalRandom.current().nextDouble() > 0.01) return; + zombieParents.setFiring(false); + + CustomBossEntity reinforcementMom = CustomBossEntity.createCustomBossEntity("zombie_parents_mom.yml"); + try { + reinforcementMom.spawn(event.getEntity().getLocation(), event.getEliteMobEntity().getLevel(), false); + } catch (Exception ex) { + new WarningMessage("Failed to spawn Zombie Parents Mom reinforcement!"); + return; + } + CustomBossEntity reinforcementDad = CustomBossEntity.createCustomBossEntity("zombie_parents_dad.yml"); + try { + reinforcementDad.spawn(event.getEntity().getLocation(), event.getEliteMobEntity().getLevel(), false); + } catch (Exception ex) { + new WarningMessage("Failed to spawn Zombie Parents Dad reinforcement!"); + return; + } + + startDialog(reinforcementMom, reinforcementDad, event.getEliteMobEntity()); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/meta/Bombardment.java b/src/main/java/com/magmaguy/elitemobs/powers/meta/Bombardment.java new file mode 100644 index 000000000..010d97790 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/meta/Bombardment.java @@ -0,0 +1,148 @@ +package com.magmaguy.elitemobs.powers.meta; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobEnterCombatEvent; +import com.magmaguy.elitemobs.api.EliteMobExitCombatEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.utils.EnderDragonPhaseSimplifier; +import org.bukkit.entity.EnderDragon; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scheduler.BukkitTask; + +import java.util.ArrayList; +import java.util.concurrent.ThreadLocalRandom; + +public abstract class Bombardment extends MajorPower implements Listener { + + public static ArrayList bombardments = new ArrayList<>(); + public int firingTimer = 0; + private boolean isActive = false; + private boolean firing = false; + private BukkitTask task = null; + + public Bombardment(PowersConfigFields powersConfigFields) { + super(powersConfigFields); + bombardments.add(powersConfigFields.getFilename()); + } + + public void activate(EliteEntity eliteEntity) { + + if (isActive) return; + isActive = true; + + task = new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + + counter++; + + if (stopCondition(eliteEntity)) + return; + + if (firing || isInCooldown(eliteEntity)) + return; + + if (ThreadLocalRandom.current().nextDouble() > 0.1) return; + + if (eliteEntity.getLivingEntity().getType().equals(EntityType.ENDER_DRAGON)) { + EnderDragon.Phase phase = ((EnderDragon) eliteEntity.getLivingEntity()).getPhase(); + if (phase.equals(EnderDragon.Phase.DYING) || + phase.equals(EnderDragon.Phase.HOVER) || + phase.equals(EnderDragon.Phase.ROAR_BEFORE_ATTACK) || + phase.equals(EnderDragon.Phase.FLY_TO_PORTAL) || + phase.equals(EnderDragon.Phase.SEARCH_FOR_BREATH_ATTACK_TARGET)) { + return; + } + } + + for (Entity entity : eliteEntity.getLivingEntity().getNearbyEntities(10, 100, 10)) { + if (entity.getType().equals(EntityType.PLAYER)) { + firing = true; + fire(eliteEntity); + return; + } + } + + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 5); + } + + public void deactivate() { + firing = false; + isActive = false; + if (task != null) + task.cancel(); + } + + private boolean stopCondition(EliteEntity eliteEntity) { + if (eliteEntity == null || + eliteEntity.getLivingEntity() == null || + !eliteEntity.isValid() || + !eliteEntity.isInCombat()) { + deactivate(); + return true; + } + + if (eliteEntity.getLivingEntity().getType().equals(EntityType.ENDER_DRAGON)) + return !EnderDragonPhaseSimplifier.isFlying( + ((EnderDragon) eliteEntity.getLivingEntity()).getPhase(), + false); + + return false; + } + + private void fire(EliteEntity eliteEntity) { + + doCooldown(eliteEntity); + + isActive = true; + + firingTimer = 0; + + new BukkitRunnable() { + + @Override + public void run() { + firingTimer++; + if (stopCondition(eliteEntity) || firingTimer > 20 * 5) { + cancel(); + firing = false; + return; + } + + taskBehavior(eliteEntity); + + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + } + + public abstract void taskBehavior(EliteEntity eliteEntity); + + public static class BombardmentEvents implements Listener { + @EventHandler + public void onCombatEnter(EliteMobEnterCombatEvent event) { + for (String bombardmentPower : bombardments) { + Bombardment bombardment = (Bombardment) event.getEliteMobEntity().getPower(bombardmentPower); + if (bombardment == null) continue; + bombardment.activate(event.getEliteMobEntity()); + } + } + + @EventHandler + public void onCombatLeave(EliteMobExitCombatEvent event) { + for (String bombardmentPower : bombardments) { + Bombardment bombardment = (Bombardment) event.getEliteMobEntity().getPower(bombardmentPower); + if (bombardment == null) continue; + bombardment.deactivate(); + } + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/meta/BossPower.java b/src/main/java/com/magmaguy/elitemobs/powers/meta/BossPower.java new file mode 100644 index 000000000..3a6c1a2b0 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/meta/BossPower.java @@ -0,0 +1,9 @@ +package com.magmaguy.elitemobs.powers.meta; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; + +public abstract class BossPower extends ElitePower { + protected BossPower(PowersConfigFields powersConfigFields) { + super(powersConfigFields); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/meta/CombatEnterScanPower.java b/src/main/java/com/magmaguy/elitemobs/powers/meta/CombatEnterScanPower.java new file mode 100644 index 000000000..7d1cd88cb --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/meta/CombatEnterScanPower.java @@ -0,0 +1,74 @@ +package com.magmaguy.elitemobs.powers.meta; + +import com.magmaguy.elitemobs.api.EliteMobEnterCombatEvent; +import com.magmaguy.elitemobs.api.EliteMobExitCombatEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.scheduler.BukkitTask; + +import java.util.HashSet; + +public abstract class CombatEnterScanPower extends MajorPower implements Listener { + + public static HashSet combatEnterScanPowers = new HashSet<>(); + public BukkitTask bukkitTask = null; + private boolean isActive = false; + + public CombatEnterScanPower(PowersConfigFields powersConfigFields) { + super(powersConfigFields); + combatEnterScanPowers.add(this); + } + + protected void activate(EliteEntity eliteEntity) { + if (isActive) return; + isActive = true; + finishActivation(eliteEntity); + } + + protected abstract void finishActivation(EliteEntity eliteEntity); + + public void deactivate(EliteEntity eliteEntity) { + if (bukkitTask != null) + bukkitTask.cancel(); + isActive = false; + finishDeactivation(eliteEntity); + } + + protected abstract void finishDeactivation(EliteEntity eliteEntity); + + protected boolean doExit(EliteEntity eliteEntity) { + if (eliteEntity == null || + !eliteEntity.isValid()) { + deactivate(eliteEntity); + return true; + } + + return false; + } + + public static class MajorCombatEnterScanningPowerEvents implements Listener { + @EventHandler + public void onCombatEnter(EliteMobEnterCombatEvent event) { + for (CombatEnterScanPower combatEnterScanPower : combatEnterScanPowers) { + ElitePower elitePowerInstance = event.getEliteMobEntity().getPower(combatEnterScanPower); + if (elitePowerInstance == null) + continue; + ((CombatEnterScanPower) elitePowerInstance).activate(event.getEliteMobEntity()); + } + + } + + @EventHandler + public void onCombatExit(EliteMobExitCombatEvent event) { + for (CombatEnterScanPower combatEnterScanPower : combatEnterScanPowers) { + ElitePower elitePowerInstance = event.getEliteMobEntity().getPower(combatEnterScanPower); + if (elitePowerInstance == null) + continue; + ((CombatEnterScanPower) elitePowerInstance).deactivate(event.getEliteMobEntity()); + } + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/meta/CustomSummonPower.java b/src/main/java/com/magmaguy/elitemobs/powers/meta/CustomSummonPower.java new file mode 100644 index 000000000..4b0c1fda7 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/meta/CustomSummonPower.java @@ -0,0 +1,539 @@ +package com.magmaguy.elitemobs.powers.meta; + +import com.magmaguy.elitemobs.CrashFix; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerEvent; +import com.magmaguy.elitemobs.api.EliteMobDeathEvent; +import com.magmaguy.elitemobs.api.EliteMobEnterCombatEvent; +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfig; +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfigFields; +import com.magmaguy.elitemobs.config.customspawns.CustomSpawnConfig; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.mobconstructor.CustomSpawn; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import com.magmaguy.elitemobs.mobconstructor.custombosses.RegionalBossEntity; +import com.magmaguy.elitemobs.powers.specialpowers.EnderCrystalLightningRod; +import com.magmaguy.elitemobs.utils.WarningMessage; +import org.bukkit.Location; +import org.bukkit.NamespacedKey; +import org.bukkit.entity.*; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.persistence.PersistentDataType; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scheduler.BukkitTask; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +public class CustomSummonPower extends ElitePower implements Listener { + + private List customBossReinforcements = new ArrayList<>(); + + public CustomSummonPower(String powerString) { + super(PowersConfig.getPower("custom_summon.yml")); + //This allows an arbitrary amount of reinforcements to be added at any point, class initialization just prepares the stage + addEntry(powerString); + } + + public static BukkitTask summonGlobalReinforcement(CustomBossReinforcement customBossReinforcement, CustomBossEntity summoningEntity) { + if (customBossReinforcement.customSpawn == null || customBossReinforcement.customSpawn.isEmpty()) { + new WarningMessage("Reinforcement for boss " + summoningEntity.getCustomBossesConfigFields().getFilename() + " has an incorrectly configured global reinforcement for " + customBossReinforcement.bossFileName); + return null; + } + return new BukkitRunnable() { + @Override + public void run() { + if (summoningEntity.getGlobalReinforcementsCount() > 30 * summoningEntity.getSpawnLocation().getWorld().getPlayers().size()) + return; + for (int i = 0; i < customBossReinforcement.amount; i++) { + CustomBossEntity customBossEntity = CustomBossEntity.createCustomBossEntity(customBossReinforcement.bossFileName); + if (customBossEntity == null) { + new WarningMessage("Failed to spawn reinforcement because boss " + customBossReinforcement.bossFileName + " was invalid! Does the file exist? Is it configured correctly?"); + return; + } + CustomSpawn customSpawn = new CustomSpawn(customBossReinforcement.customSpawn, customBossEntity); + //Case if the spawn fails + if (customSpawn.getCustomSpawnConfigFields() == null) continue; + customSpawn.setWorld(summoningEntity.getSpawnLocation().getWorld()); + customSpawn.queueSpawn(); + summoningEntity.addGlobalReinforcement(customBossEntity); + customBossReinforcement.isSummoned = true; + customBossEntity.setSummoningEntity(summoningEntity); + } + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 20L * 10); + } + + public List getCustomBossReinforcements() { + return customBossReinforcements; + } + + public void addEntry(String powerString) { + /* + valid formats: + summonable: + summonType=ONCE/ON_HIT/ON_COMBAT_ENTER/ON_COMBAT_ENTER_PLACE_CRYSTAL/GLOBAL/ON_DEATH: + filename=filename.yml: + chance=double; + location=x,y,z: + lightningRod=true/false: + inheritAggro=true/false: + amount=int: + customSpawn=filename.yml + + summon:once:filename.yml + summon:onHit:%:filename.yml + summon:onCombatEnter:x,y,z:filename.yml + summon:onCombatEnterPlaceCrystal:x,y,z:boolean + */ + + //this is now considered to be legacy + if (powerString.split(":")[0].equalsIgnoreCase("summon")) { + if (powerString.split(":")[1].equalsIgnoreCase("once")) + parseOnce(powerString); + else if (powerString.split(":")[1].equalsIgnoreCase("onHit")) + parseOnHit(powerString); + else if (powerString.split(":")[1].equalsIgnoreCase("onCombatEnter")) + parseOnCombatEnter(powerString); + else if (powerString.split(":")[1].equalsIgnoreCase("onCombatEnterPlaceCrystal")) + parseOnCombatEnterPlaceCrystal(powerString); + } + + //this is the new recommended format for reinforcements + if (powerString.split(":")[0].equalsIgnoreCase("summonable")) { + SummonType summonType = null; + String filename = null; + Vector location = null; + Double chance = null; + boolean lightningRod = false; + boolean inheritAggro = false; + boolean inheritLevel = false; + String customSpawn = ""; + int amount = 1; + boolean spawnNearby = false; + for (String substring : powerString.split(":")) { + switch (substring.split("=")[0].toLowerCase()) { + //this just tags it for parsing + case "summonable": + break; + case "summontype": + try { + summonType = SummonType.valueOf(getSubstringField(substring)); + } catch (Exception ex) { + new WarningMessage("Failed to determine summon type from " + getSubstringField(substring)); + } + break; + case "filename": + try { + filename = getSubstringField(substring); + } catch (Exception ex) { + new WarningMessage("Failed to determine filename from " + getSubstringField(substring)); + } + break; + case "chance": + try { + chance = Double.parseDouble(getSubstringField(substring)); + } catch (Exception ex) { + new WarningMessage("Failed to determine chance from " + getSubstringField(substring)); + } + break; + case "location": + try { + String locationString = getSubstringField(substring); + location = new Vector( + Double.parseDouble(locationString.split(",")[0]), + Double.parseDouble(locationString.split(",")[1]), + Double.parseDouble(locationString.split(",")[2])); + } catch (Exception ex) { + new WarningMessage("Failed to determine location from " + getSubstringField(substring)); + } + break; + case "lightningrod": + try { + lightningRod = Boolean.parseBoolean(getSubstringField(substring)); + } catch (Exception ex) { + new WarningMessage("Failed to determine lightningRod from " + getSubstringField(substring)); + } + break; + case "inheritaggro": + try { + inheritAggro = Boolean.parseBoolean(getSubstringField(substring)); + } catch (Exception ex) { + new WarningMessage("Failed to determine inheritAggro from " + getSubstringField(substring)); + } + break; + case "amount": + try { + amount = Integer.parseInt(getSubstringField(substring)); + } catch (Exception ex) { + new WarningMessage("Failed to determine inheritAggro from " + getSubstringField(substring)); + } + break; + case "inheritlevel": + try { + inheritLevel = Boolean.parseBoolean(getSubstringField(substring)); + } catch (Exception ex) { + new WarningMessage("Failed to determine inheritLevel from " + getSubstringField(substring)); + } + break; + case "spawnnearby": + try { + spawnNearby = Boolean.parseBoolean(getSubstringField(substring)); + } catch (Exception ex) { + new WarningMessage("Failed to determine spawnNearby from " + getSubstringField(substring)); + } + break; + case "customspawn": + if (CustomSpawnConfig.getCustomEvent(getSubstringField(substring)) == null) + new WarningMessage("Failed to determine Custom Spawn file for filename " + substring); + else + customSpawn = getSubstringField(substring); + break; + default: + new WarningMessage("Invalid boss reinforcement string for line " + powerString + " !"); + new WarningMessage("Problematic entry: " + substring); + } + } + + if (summonType == null) { + new WarningMessage("No summon type detected in " + powerString + " ! This reinforcement will not work."); + return; + } + + CustomBossReinforcement customBossReinforcement; + switch (summonType) { + case ONCE: + customBossReinforcement = doOnce(filename); + break; + case ON_HIT: + customBossReinforcement = doOnHit(filename, chance); + break; + case ON_DEATH: + customBossReinforcement = doOnDeath(filename); + break; + case ON_COMBAT_ENTER: + customBossReinforcement = doOnCombatEnter(filename); + break; + case ON_COMBAT_ENTER_PLACE_CRYSTAL: + customBossReinforcement = doOnCombatEnterPlaceCrystal(location, lightningRod); + break; + case GLOBAL: + customBossReinforcement = doGlobalSummonReinforcement(filename); + break; + default: + customBossReinforcement = null; + new WarningMessage("Failed to determine summon type for reinforcement " + powerString + " ! Contact the developer with this error!"); + } + + if (customBossReinforcement == null) + return; + + customBossReinforcement.inheritAggro = inheritAggro; + customBossReinforcement.amount = amount; + customBossReinforcement.inheritLevel = inheritLevel; + customBossReinforcement.spawnNearby = spawnNearby; + customBossReinforcement.customSpawn = customSpawn; + customBossReinforcement.summonChance = chance; + customBossReinforcement.setSpawnLocationOffset(location); + + } + } + + private String getSubstringField(String string) { + return string.split("=")[1]; + } + + //summon:once:filename.yml + private void parseOnce(String powerString) { + String[] strings = powerString.split(":"); + doOnce(strings[2]); + } + + private CustomBossReinforcement doOnce(String filename) { + CustomBossReinforcement customBossReinforcement = new CustomBossReinforcement(SummonType.ONCE, filename); + if (CustomBossesConfig.getCustomBoss(customBossReinforcement.bossFileName) == null) { + new WarningMessage("Reinforcement mob " + customBossReinforcement.bossFileName + " is not valid!"); + return null; + } + customBossReinforcements.add(customBossReinforcement); + return customBossReinforcement; + } + + //summon:onHit:%:filename.yml + private void parseOnHit(String powerString) { + String[] strings = powerString.split(":"); + doOnHit(strings[3], Double.parseDouble(strings[2])); + } + + private CustomBossReinforcement doOnHit(String filename, double chance) { + CustomBossReinforcement customBossReinforcement = new CustomBossReinforcement(SummonType.ON_HIT, filename); + customBossReinforcement.setSummonChance(chance); + if (CustomBossesConfig.getCustomBoss(customBossReinforcement.bossFileName) == null) { + new WarningMessage("Reinforcement mob " + customBossReinforcement.bossFileName + " is not valid!"); + return customBossReinforcement; + } + customBossReinforcements.add(customBossReinforcement); + return customBossReinforcement; + } + + private CustomBossReinforcement doOnDeath(String filename) { + CustomBossReinforcement customBossReinforcement = new CustomBossReinforcement(SummonType.ON_DEATH, filename); + if (CustomBossesConfig.getCustomBoss(customBossReinforcement.bossFileName) == null) { + new WarningMessage("Reinforcement mob " + customBossReinforcement.bossFileName + " is not valid!"); + return null; + } + customBossReinforcements.add(customBossReinforcement); + return customBossReinforcement; + } + + //summon:onCombatEnter:x,y,z:filename.yml + private void parseOnCombatEnter(String powerString) { + String[] strings = powerString.split(":"); + doOnCombatEnter(strings[3], new Vector( + Double.parseDouble(strings[2].split(",")[0]), + Double.parseDouble(strings[2].split(",")[1]), + Double.parseDouble(strings[2].split(",")[2]))); + + } + + private CustomBossReinforcement doOnCombatEnter(String filename, Vector vector) { + CustomBossReinforcement customBossReinforcement = new CustomBossReinforcement(SummonType.ON_COMBAT_ENTER, filename); + customBossReinforcement.setSpawnLocationOffset(vector); + return doOnCombatEnter(filename); + } + + private CustomBossReinforcement doOnCombatEnter(String filename) { + CustomBossReinforcement customBossReinforcement = new CustomBossReinforcement(SummonType.ON_COMBAT_ENTER, filename); + + if (CustomBossesConfig.getCustomBoss(customBossReinforcement.bossFileName) == null) { + new WarningMessage("Reinforcement mob " + customBossReinforcement.bossFileName + " is not valid!"); + return customBossReinforcement; + } + customBossReinforcements.add(customBossReinforcement); + return customBossReinforcement; + } + + //summon:onCombatEnterPlaceCrystal:x,y,z:boolean + private void parseOnCombatEnterPlaceCrystal(String powerString) { + String[] strings = powerString.split(":"); + doOnCombatEnterPlaceCrystal(new Vector( + Double.parseDouble(strings[2].split(",")[0]), + Double.parseDouble(strings[2].split(",")[1]), + Double.parseDouble(strings[2].split(",")[2])), Boolean.parseBoolean(strings[3])); + } + + private CustomBossReinforcement doOnCombatEnterPlaceCrystal(Vector location, boolean lightningRod) { + CustomBossReinforcement customBossReinforcement = new CustomBossReinforcement(SummonType.ON_COMBAT_ENTER, EntityType.ENDER_CRYSTAL, lightningRod); + customBossReinforcement.setSpawnLocationOffset(location); + customBossReinforcements.add(customBossReinforcement); + return customBossReinforcement; + } + + private CustomBossReinforcement doGlobalSummonReinforcement(String filename) { + CustomBossReinforcement customBossReinforcement = new CustomBossReinforcement(SummonType.GLOBAL, filename); + CustomBossesConfigFields customBossesConfigFields = CustomBossesConfig.getCustomBoss(customBossReinforcement.bossFileName); + if (customBossesConfigFields == null) { + new WarningMessage("Reinforcement mob " + customBossReinforcement.bossFileName + " is not valid!"); + return null; + } + customBossReinforcement.entityType = customBossesConfigFields.getEntityType(); + customBossReinforcements.add(customBossReinforcement); + return customBossReinforcement; + } + + private void onHitSummonReinforcement(EliteEntity spawningEntity) { + for (CustomBossReinforcement customBossReinforcement : customBossReinforcements) { + if (customBossReinforcement.summonType.equals(SummonType.ONCE) && !customBossReinforcement.isSummoned) + summonReinforcement(spawningEntity, customBossReinforcement); + + if (customBossReinforcement.summonType.equals(SummonType.ON_HIT)) + summonReinforcement(spawningEntity, customBossReinforcement); + } + } + + private void onCombatEnterSummonReinforcement(EliteEntity spawningEntity) { + for (CustomBossReinforcement customBossReinforcement : customBossReinforcements) { + if (!customBossReinforcement.summonType.equals(SummonType.ON_COMBAT_ENTER)) continue; + if (customBossReinforcement.bossFileName != null) { + summonReinforcement(spawningEntity, customBossReinforcement); + } else { + + Location spawnLocation = getFinalSpawnLocation(spawningEntity, customBossReinforcement.spawnLocationOffset); + + Entity entity = spawnLocation.getWorld().spawnEntity(spawnLocation, customBossReinforcement.entityType); + entity.getPersistentDataContainer().set(new NamespacedKey(MetadataHandler.PLUGIN, "eliteCrystal"), PersistentDataType.STRING, "eliteCrystal"); + entity.setPersistent(false); + CrashFix.persistentTracker(entity); + + if (entity instanceof Mob && !spawningEntity.getDamagers().isEmpty()) { + Player target = null; + double damageDealt = 0; + for (Player player : spawningEntity.getDamagers().keySet()) { + if (spawningEntity.getDamagers().get(player) < damageDealt) continue; + target = player; + damageDealt = spawningEntity.getDamagers().get(player); + } + if (target != null) + ((Mob) entity).setTarget(target); + + } + + + if (customBossReinforcement.isLightningRod) + new EnderCrystalLightningRod(spawningEntity, (EnderCrystal) entity); + + customBossReinforcement.isSummoned = true; + spawningEntity.addReinforcement(entity); + } + } + + } + + private void onDeathSummonReinforcement(EliteEntity spawningEntity) { + for (CustomBossReinforcement customBossReinforcement : customBossReinforcements) + if (customBossReinforcement.summonType.equals(SummonType.ON_DEATH)) + summonReinforcement(spawningEntity, customBossReinforcement); + } + + private void summonReinforcement(EliteEntity eliteEntity, CustomBossReinforcement customBossReinforcement) { + if (customBossReinforcement.summonChance != null && ThreadLocalRandom.current().nextDouble() > customBossReinforcement.summonChance) + return; + for (int i = 0; i < customBossReinforcement.amount; i++) { + Location spawnLocation = eliteEntity.getLocation(); + if (customBossReinforcement.spawnLocationOffset != null) + spawnLocation = getFinalSpawnLocation(eliteEntity, customBossReinforcement.spawnLocationOffset); + if (customBossReinforcement.spawnNearby) + for (int loc = 0; loc < 30; loc++) { + Location randomLocation = spawnLocation.clone().add(new Vector( + ThreadLocalRandom.current().nextInt(-15, 15), + 0, + ThreadLocalRandom.current().nextInt(-15, 15))); + randomLocation.setY(CustomSpawn.getHighestValidBlock(randomLocation, 256)); + if (randomLocation.getY() == -100) continue; + spawnLocation = randomLocation; + break; + } + + if (CustomBossesConfig.getCustomBoss(customBossReinforcement.bossFileName).isRegionalBoss()) { + RegionalBossEntity regionalBossEntity = RegionalBossEntity.createTemporaryRegionalBossEntity(customBossReinforcement.bossFileName, spawnLocation); + if (regionalBossEntity == null) { + new WarningMessage("Failed to spawn reinforcement for " + eliteEntity.getName() + " because boss " + customBossReinforcement.bossFileName + " was invalid! Does the file exist? Is it configured correctly?"); + return; + } + if (customBossReinforcement.inheritLevel) + regionalBossEntity.setLevel(eliteEntity.getLevel()); + if (!customBossReinforcement.summonType.equals(SummonType.ON_DEATH)) + eliteEntity.addReinforcement(regionalBossEntity); + customBossReinforcement.isSummoned = true; + regionalBossEntity.setSummoningEntity(eliteEntity); + regionalBossEntity.initialize(); + } else { + CustomBossEntity customBossEntity = CustomBossEntity.createCustomBossEntity(customBossReinforcement.bossFileName); + if (customBossEntity == null) { + new WarningMessage("Failed to spawn reinforcement for " + eliteEntity.getName() + " because boss " + customBossReinforcement.bossFileName + " was invalid! Does the file exist? Is it configured correctly?"); + return; + } + customBossEntity.setSpawnLocation(spawnLocation); + customBossEntity.setBypassesProtections(eliteEntity.getBypassesProtections()); + if (customBossReinforcement.inheritLevel) + customBossEntity.setLevel(eliteEntity.getLevel()); + customBossEntity.spawn(false); + if (customBossEntity.getLivingEntity() != null) + customBossEntity.getLivingEntity().setVelocity(new Vector(ThreadLocalRandom.current().nextDouble(0.2), 0.2, ThreadLocalRandom.current().nextDouble(0.2))); + if (!customBossReinforcement.summonType.equals(SummonType.ON_DEATH)) + eliteEntity.addReinforcement(customBossEntity); + customBossReinforcement.isSummoned = true; + customBossEntity.setSummoningEntity(eliteEntity); + } + } + } + + private Location getFinalSpawnLocation(EliteEntity summoningEntity, Vector spawnLocationOffset) { + Location finalSpawnLocation; + if (summoningEntity instanceof RegionalBossEntity) + finalSpawnLocation = ((RegionalBossEntity) summoningEntity).getSpawnLocation().clone().add(spawnLocationOffset); + else if (summoningEntity == null) + finalSpawnLocation = null; + else + finalSpawnLocation = summoningEntity.getLocation().add(spawnLocationOffset); + if (summoningEntity instanceof CustomBossEntity && ((CustomBossEntity) summoningEntity).getMinidungeon() != null) + if (summoningEntity instanceof RegionalBossEntity) + return ((CustomBossEntity) summoningEntity).getMinidungeon().getRotatedFinalLocation(((RegionalBossEntity) summoningEntity).getSpawnLocation(), spawnLocationOffset); + else + return ((CustomBossEntity) summoningEntity).getMinidungeon().getRotatedFinalLocation((summoningEntity).getLocation(), spawnLocationOffset); + + else return finalSpawnLocation; + } + + public enum SummonType { + ONCE, + ON_HIT, + ON_COMBAT_ENTER, + ON_DEATH, + ON_COMBAT_ENTER_PLACE_CRYSTAL, + GLOBAL + } + + public static class CustomSummonPowerEvent implements Listener { + @EventHandler(ignoreCancelled = true) + public void onHit(EliteMobDamagedByPlayerEvent event) { + CustomSummonPower customSummonPower = (CustomSummonPower) event.getEliteMobEntity().getPower("custom_summon.yml"); + if (customSummonPower == null) return; + if (!eventIsValid(event, customSummonPower)) return; + customSummonPower.onHitSummonReinforcement(event.getEliteMobEntity()); + } + + @EventHandler(ignoreCancelled = true) + public void onCombatEnter(EliteMobEnterCombatEvent event) { + CustomSummonPower customSummonPower = (CustomSummonPower) event.getEliteMobEntity().getPower("custom_summon.yml"); + if (customSummonPower == null) return; + customSummonPower.onCombatEnterSummonReinforcement(event.getEliteMobEntity()); + } + + @EventHandler + public void onDeath(EliteMobDeathEvent event) { + CustomSummonPower customSummonPower = (CustomSummonPower) event.getEliteEntity().getPower("custom_summon.yml"); + if (customSummonPower == null) return; + customSummonPower.onDeathSummonReinforcement(event.getEliteEntity()); + } + } + + public class CustomBossReinforcement { + public final SummonType summonType; + public Double summonChance; + public String bossFileName = null; + public Vector spawnLocationOffset; + public EntityType entityType; + public boolean isLightningRod; + public boolean inheritAggro = false; + public int amount = 1; + public boolean inheritLevel = false; + public boolean spawnNearby = false; + public String customSpawn; + private boolean isSummoned = false; + + public CustomBossReinforcement(SummonType summonType, String bossFileName) { + this.summonType = summonType; + this.bossFileName = bossFileName; + } + + public CustomBossReinforcement(SummonType summonType, EntityType entityType, boolean isLightningRod) { + this.summonType = summonType; + this.entityType = entityType; + this.isLightningRod = isLightningRod; + } + + public void setSummonChance(double summonChance) { + this.summonChance = summonChance; + } + + public void setSpawnLocationOffset(Vector vector) { + this.spawnLocationOffset = vector; + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/meta/ElitePower.java b/src/main/java/com/magmaguy/elitemobs/powers/meta/ElitePower.java new file mode 100644 index 000000000..d77b46edb --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/meta/ElitePower.java @@ -0,0 +1,171 @@ +package com.magmaguy.elitemobs.powers.meta; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.utils.WarningMessage; +import lombok.Getter; +import lombok.Setter; +import org.bukkit.entity.LivingEntity; +import org.bukkit.scheduler.BukkitRunnable; +import org.reflections.Reflections; + +import java.util.HashSet; + +public class ElitePower { + + @Getter + private static final HashSet elitePowers = new HashSet<>(); + @Getter + private static final HashSet bossPowers = new HashSet<>(); + @Getter + private static final HashSet majorPowers = new HashSet<>(); + @Getter + private static final HashSet defensivePowers = new HashSet<>(); + @Getter + private static final HashSet miscellaneousPowers = new HashSet<>(); + @Getter + private static final HashSet offensivePowers = new HashSet<>(); + @Getter + private static final HashSet specialPowers = new HashSet<>(); + + @Getter + private final String fileName; + @Getter + private final String trail; + @Getter + private final String name; + @Getter + private final int powerCooldownTime; + @Getter + private final int globalCooldownTime; + @Getter + private final PowersConfigFields powersConfigFields; + @Getter + @Setter + private boolean inGlobalCooldown = false; + @Getter + private boolean powerCooldownActive = false; + @Getter + @Setter + private boolean isFiring = false; + + public ElitePower(PowersConfigFields powersConfigFields) { + this.powersConfigFields = powersConfigFields; + this.fileName = powersConfigFields.getFilename(); + this.name = powersConfigFields.getName(); + this.trail = powersConfigFields.getEffect(); + this.powerCooldownTime = powersConfigFields.getPowerCooldown(); + this.globalCooldownTime = powersConfigFields.getGlobalCooldown(); + } + + public static void initializePowers() { + //boss powers + initializePackage("bosspowers", bossPowers); + //defensive powers + initializePackage("defensivepowers", defensivePowers); + //major powers + initializePackage("majorpowers", majorPowers); + //miscellaneous powers + initializePackage("miscellaneouspowers", miscellaneousPowers); + //offensive powers + initializePackage("offensivepowers", offensivePowers); + //special powers + initializePackage("specialpowers", specialPowers); + //all powers + elitePowers.addAll(bossPowers); + elitePowers.addAll(defensivePowers); + elitePowers.addAll(majorPowers); + elitePowers.addAll(miscellaneousPowers); + elitePowers.addAll(offensivePowers); + elitePowers.addAll(specialPowers); + } + + private static void initializePackage(String specificPackage, HashSet elitePowers) { + Reflections reflections = new Reflections("com.magmaguy.elitemobs.powers." + specificPackage); + reflections.getSubTypesOf(ElitePower.class).forEach(power -> { + try { + elitePowers.add(power.newInstance()); + } catch (Exception ex) { + //Not sure why stuff in the meta package is getting scanned, seems like the package scan isn't working as intended + //todo: figure out why package scanning is getting more than what is in the packages here + //new WarningMessage("Failed to initialize power " + specificPackage + " " + power.getName()); + } + }); + } + + public static ElitePower getElitePower(String elitePowerName) { + for (ElitePower elitePower : getElitePowers()) + if (elitePower.getFileName().equalsIgnoreCase(elitePowerName)) { + try { + return elitePower.getClass().newInstance(); + } catch (Exception ex) { + new WarningMessage("Failed to instance power"); + } + } + return null; + } + + + protected static boolean eventIsValid(EliteMobDamagedByPlayerEvent event, ElitePower elitePower) { + if (event.isCancelled()) return false; + if (event.getEliteMobEntity().getLivingEntity() == null) return false; + if (!event.getEliteMobEntity().getLivingEntity().hasAI()) return false; + if (elitePower.isInGlobalCooldown()) return false; + return !event.getEliteMobEntity().isInCooldown(); + } + + /** + * This is overwritten by certain classes to apply powers to a living entity upon activation + * + * @param livingEntity + */ + public void applyPowers(LivingEntity livingEntity) { + //This is overwritten by certain classes to apply powers to a living entity upon activation + } + + public boolean isInCooldown(EliteEntity eliteEntity) { + return this.powerCooldownActive || eliteEntity.isInCooldown(); + } + + public void setInCooldown(EliteEntity eliteEntity, boolean inCooldown) { + eliteEntity.setInCooldown(inCooldown); + setInGlobalCooldown(inCooldown); + } + + public void doCooldown(EliteEntity eliteEntity) { + this.powerCooldownActive = true; + eliteEntity.doGlobalPowerCooldown(globalCooldownTime * 20); + + new BukkitRunnable() { + @Override + public void run() { + powerCooldownActive = false; + } + }.runTaskLater(MetadataHandler.PLUGIN, powerCooldownTime * 20L); + + } + + protected void doGlobalCooldown(int ticks, EliteEntity eliteEntity) { + setInGlobalCooldown(true); + eliteEntity.doCooldown(); + new BukkitRunnable() { + @Override + public void run() { + setInGlobalCooldown(false); + } + }.runTaskLater(MetadataHandler.PLUGIN, ticks); + } + + protected void doGlobalCooldown(int ticks) { + setInGlobalCooldown(true); + new BukkitRunnable() { + @Override + public void run() { + setInGlobalCooldown(false); + } + }.runTaskLater(MetadataHandler.PLUGIN, ticks); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/meta/MajorPower.java b/src/main/java/com/magmaguy/elitemobs/powers/meta/MajorPower.java new file mode 100644 index 000000000..2913df338 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/meta/MajorPower.java @@ -0,0 +1,12 @@ +package com.magmaguy.elitemobs.powers.meta; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; + +/** + * Created by MagmaGuy on 10/05/2017. + */ +public abstract class MajorPower extends ElitePower { + protected MajorPower(PowersConfigFields powersConfigFields) { + super(powersConfigFields); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/meta/MinorPower.java b/src/main/java/com/magmaguy/elitemobs/powers/meta/MinorPower.java new file mode 100644 index 000000000..98b803157 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/meta/MinorPower.java @@ -0,0 +1,12 @@ +package com.magmaguy.elitemobs.powers.meta; + +import com.magmaguy.elitemobs.config.powers.PowersConfigFields; + +/** + * Created by MagmaGuy on 05/11/2016. + */ +public abstract class MinorPower extends ElitePower { + protected MinorPower(PowersConfigFields powersConfigFields) { + super(powersConfigFields); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/mobpowers/PowerCooldown.java b/src/main/java/com/magmaguy/elitemobs/powers/meta/PowerCooldown.java similarity index 79% rename from src/main/java/com/magmaguy/elitemobs/mobpowers/PowerCooldown.java rename to src/main/java/com/magmaguy/elitemobs/powers/meta/PowerCooldown.java index ecd534150..661b9fbf3 100644 --- a/src/main/java/com/magmaguy/elitemobs/mobpowers/PowerCooldown.java +++ b/src/main/java/com/magmaguy/elitemobs/powers/meta/PowerCooldown.java @@ -13,10 +13,10 @@ * along with this program. If not, see . */ -package com.magmaguy.elitemobs.mobpowers; +package com.magmaguy.elitemobs.powers.meta; import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; import org.bukkit.scheduler.BukkitRunnable; import java.util.HashSet; @@ -26,7 +26,7 @@ public class PowerCooldown { /* This class just removes metadata after a variable delay, allows */ - public static void startCooldownTimer(EliteMobEntity eliteMob, HashSet cooldownList, int duration) { + public static void startCooldownTimer(EliteEntity eliteMob, HashSet cooldownList, int duration) { cooldownList.add(eliteMob); @@ -46,7 +46,7 @@ public void run() { /* This method checks if the cooldown is active */ - public static boolean isInCooldown(EliteMobEntity eliteMob, HashSet cooldownList) { + public static boolean isInCooldown(EliteEntity eliteMob, HashSet cooldownList) { return cooldownList.contains(eliteMob); } diff --git a/src/main/java/com/magmaguy/elitemobs/powers/meta/ProjectileLocationGenerator.java b/src/main/java/com/magmaguy/elitemobs/powers/meta/ProjectileLocationGenerator.java new file mode 100644 index 000000000..5aeb9ebcd --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/meta/ProjectileLocationGenerator.java @@ -0,0 +1,12 @@ +package com.magmaguy.elitemobs.powers.meta; + +import org.bukkit.Location; +import org.bukkit.entity.LivingEntity; + +public class ProjectileLocationGenerator { + + public static Location generateLocation(LivingEntity targetter, LivingEntity targetted) { + return targetter.getLocation().clone().add(0, 1, 0).add(targetted.getLocation().clone().subtract(targetter.getLocation().clone()).toVector().normalize()).setDirection(targetted.getLocation().clone().subtract(targetter.getLocation()).toVector()); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/meta/ProjectileTagger.java b/src/main/java/com/magmaguy/elitemobs/powers/meta/ProjectileTagger.java new file mode 100644 index 000000000..15a29b640 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/meta/ProjectileTagger.java @@ -0,0 +1,26 @@ +package com.magmaguy.elitemobs.powers.meta; + +import com.magmaguy.elitemobs.MetadataHandler; +import org.bukkit.NamespacedKey; +import org.bukkit.entity.Projectile; +import org.bukkit.persistence.PersistentDataType; + +public class ProjectileTagger { + + public static final NamespacedKey customDamageKey = new NamespacedKey(MetadataHandler.PLUGIN, "custom_damage"); + + public static void tagProjectileWithCustomDamage(Projectile projectile, double customDamage) { + projectile.getPersistentDataContainer().set(customDamageKey, PersistentDataType.DOUBLE, customDamage); + } + + public static boolean projectileHasCustomDamage(Projectile projectile) { + return projectile.getPersistentDataContainer().has(customDamageKey, PersistentDataType.DOUBLE); + } + + public static double getProjectileCustomDamage(Projectile projectile) { + if (!projectileHasCustomDamage(projectile)) + return -1; + return projectile.getPersistentDataContainer().get(customDamageKey, PersistentDataType.DOUBLE); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/miscellaneouspowers/BonusLoot.java b/src/main/java/com/magmaguy/elitemobs/powers/miscellaneouspowers/BonusLoot.java new file mode 100644 index 000000000..ac5fb0002 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/miscellaneouspowers/BonusLoot.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.powers.miscellaneouspowers; + +import com.magmaguy.elitemobs.api.EliteMobDeathEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.items.LootTables; +import com.magmaguy.elitemobs.powers.meta.MinorPower; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; + +/** + * Created by MagmaGuy on 28/04/2017. + */ +public class BonusLoot extends MinorPower implements Listener { + + public BonusLoot() { + super(PowersConfig.getPower("bonus_loot.yml")); + } + + @EventHandler + public void onDeath(EliteMobDeathEvent event) { + if (!event.getEliteEntity().hasPower(this)) return; + LootTables.generatePlayerLoot(event.getEliteEntity()); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/miscellaneouspowers/Corpse.java b/src/main/java/com/magmaguy/elitemobs/powers/miscellaneouspowers/Corpse.java new file mode 100644 index 000000000..0cfba8234 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/miscellaneouspowers/Corpse.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.powers.miscellaneouspowers; + +import com.magmaguy.elitemobs.api.EliteMobDeathEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.powers.meta.MinorPower; +import org.bukkit.Material; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; + +public class Corpse extends MinorPower implements Listener { + + public Corpse() { + super(PowersConfig.getPower("corpse.yml")); + } + + @EventHandler + public void onDeath(EliteMobDeathEvent event) { + if (!event.getEliteEntity().hasPower(this)) return; + if (!event.getEntity().getLocation().getBlock().getType().equals(Material.AIR)) return; + + EntityTracker.addTemporaryBlock(event.getEliteEntity().getUnsyncedLivingEntity().getLocation().getBlock(), 20 * 60 * 2, Material.BONE_BLOCK); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/miscellaneouspowers/GroundPound.java b/src/main/java/com/magmaguy/elitemobs/powers/miscellaneouspowers/GroundPound.java new file mode 100644 index 000000000..e1c68c9a6 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/miscellaneouspowers/GroundPound.java @@ -0,0 +1,127 @@ +package com.magmaguy.elitemobs.powers.miscellaneouspowers; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.meta.MinorPower; +import com.magmaguy.elitemobs.utils.NonSolidBlockTypes; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import java.util.concurrent.ThreadLocalRandom; + +public class GroundPound extends MinorPower implements Listener { + + public GroundPound() { + super(PowersConfig.getPower("ground_pound.yml")); + } + + private static void cloudParticle(Location location) { + location.getWorld().spawnParticle(Particle.CLOUD, location, 10, 0.01, 0.01, 0.01, 0.7); + } + + private static void landCloudParticle(Location location) { + location.getWorld().spawnParticle(Particle.CLOUD, location, 20, 0.1, 0.01, 0.1, 0.7); + } + + @EventHandler + public void onEliteDamaged(EliteMobDamagedByPlayerEvent event) { + GroundPound groundPound = (GroundPound) event.getEliteMobEntity().getPower(this); + if (groundPound == null) return; + if (groundPound.isInGlobalCooldown()) return; + + if (ThreadLocalRandom.current().nextDouble() > 0.10) return; + groundPound.doGlobalCooldown(20 * 10); + + doGroundPound(event.getEliteMobEntity()); + + } + + public void doGroundPound(EliteEntity eliteEntity) { + + //step 1: make boss go up + new BukkitRunnable() { + @Override + public void run() { + if (!eliteEntity.isValid()) { + cancel(); + return; + } + eliteEntity.getLivingEntity().setVelocity(new Vector(0, 1.5, 0)); + cloudParticle(eliteEntity.getLivingEntity().getLocation()); + + } + }.runTaskLater(MetadataHandler.PLUGIN, 1); + + //step 2: make boss go down + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + if (!eliteEntity.isValid()) { + cancel(); + return; + } + counter++; + if (!NonSolidBlockTypes.isPassthrough(eliteEntity.getLivingEntity().getLocation().clone().subtract(new Vector(0, 0.2, 0)).getBlock().getType())) { + + eliteEntity.getLivingEntity().setVelocity(new Vector(0, -2, 0)); + cloudParticle(eliteEntity.getLivingEntity().getLocation()); + + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + if (counter > 20 * 5 || !eliteEntity.isValid()) { + cancel(); + return; + } + + counter++; + + if (!eliteEntity.getLivingEntity().isOnGround()) + return; + + cancel(); + + landCloudParticle(eliteEntity.getLivingEntity().getLocation()); + + for (Entity entity : eliteEntity.getLivingEntity().getNearbyEntities(10, 10, 10)) { + try { + entity.setVelocity(entity.getLocation().clone().subtract(eliteEntity.getLivingEntity().getLocation()).toVector().normalize().multiply(2).setY(1.5)); + } catch (Exception ex) { + entity.setVelocity(new Vector(0, 1.5, 0)); + } + if (entity instanceof LivingEntity) + ((LivingEntity) entity).addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 20 * 3, 2)); + } + + + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + + cancel(); + return; + + } + + if (counter > 20 * 5) + cancel(); + + } + }.runTaskTimer(MetadataHandler.PLUGIN, 20, 1); + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/miscellaneouspowers/Implosion.java b/src/main/java/com/magmaguy/elitemobs/powers/miscellaneouspowers/Implosion.java new file mode 100644 index 000000000..56c5ccc62 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/miscellaneouspowers/Implosion.java @@ -0,0 +1,62 @@ +package com.magmaguy.elitemobs.powers.miscellaneouspowers; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobDeathEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import com.magmaguy.elitemobs.powers.meta.MinorPower; +import org.bukkit.GameMode; +import org.bukkit.Particle; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.scheduler.BukkitRunnable; + +public class Implosion extends MinorPower implements Listener { + + public Implosion() { + super(PowersConfig.getPower("implosion.yml")); + } + + @EventHandler + public void onDeath(EliteMobDeathEvent event) { + if (!event.getEliteEntity().hasPower(this)) return; + + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + if (counter < 20) + for (int i = 0; i < 20; i++) + event.getEntity().getLocation().getWorld().spawnParticle(Particle.PORTAL, event.getEntity().getLocation(), 1, 0.1, 0.1, 0.1, 1); + if (counter > 20 * 3) { + for (Entity entity : event.getEntity().getWorld().getNearbyEntities(event.getEntity().getLocation(), 10, 10, 10)) + if (entity instanceof LivingEntity) { + EliteEntity eliteEntity = EntityTracker.getEliteMobEntity(entity); + if (eliteEntity instanceof CustomBossEntity) { + CustomBossEntity customBossEntity = (CustomBossEntity) eliteEntity; + if (customBossEntity.getCustomBossesConfigFields().isFrozen()) + continue; + } + if (entity.getType().equals(EntityType.PLAYER) && ((Player) entity).getGameMode().equals(GameMode.SPECTATOR)) + continue; + try { + entity.setVelocity(event.getEliteEntity().getLocation().clone().subtract(entity.getLocation()).toVector().normalize()); + } catch (Exception ex) { + //Sometimes this is infinite. That just means players shouldn't move. + } + } + cancel(); + } + counter++; + } + }.runTaskTimer(MetadataHandler.PLUGIN, 1, 0); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/miscellaneouspowers/MoonWalk.java b/src/main/java/com/magmaguy/elitemobs/powers/miscellaneouspowers/MoonWalk.java new file mode 100644 index 000000000..e7ecb9769 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/miscellaneouspowers/MoonWalk.java @@ -0,0 +1,28 @@ +package com.magmaguy.elitemobs.powers.miscellaneouspowers; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.powers.meta.MinorPower; +import org.bukkit.entity.LivingEntity; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.scheduler.BukkitRunnable; + +public class MoonWalk extends MinorPower { + + public MoonWalk() { + super(PowersConfig.getPower("moonwalk.yml")); + } + + @Override + public void applyPowers(LivingEntity livingEntity) { + new BukkitRunnable() { + @Override + public void run() { + livingEntity.addPotionEffect(new PotionEffect(PotionEffectType.JUMP, 100000, 3)); + } + }.runTaskLater(MetadataHandler.PLUGIN, 1); + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/miscellaneouspowers/MovementSpeed.java b/src/main/java/com/magmaguy/elitemobs/powers/miscellaneouspowers/MovementSpeed.java new file mode 100644 index 000000000..735490f87 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/miscellaneouspowers/MovementSpeed.java @@ -0,0 +1,30 @@ +package com.magmaguy.elitemobs.powers.miscellaneouspowers; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.powers.meta.MinorPower; +import org.bukkit.entity.LivingEntity; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.scheduler.BukkitRunnable; + +/** + * Created by MagmaGuy on 05/11/2016. + */ +public class MovementSpeed extends MinorPower { + + public MovementSpeed() { + super(PowersConfig.getPower("movement_speed.yml")); + } + + @Override + public void applyPowers(LivingEntity livingEntity) { + new BukkitRunnable() { + @Override + public void run() { + livingEntity.addPotionEffect(new PotionEffect(PotionEffectType.SPEED, 100000, 1)); + } + }.runTaskLater(MetadataHandler.PLUGIN, 1); + } + +} \ No newline at end of file diff --git a/src/main/java/com/magmaguy/elitemobs/powers/miscellaneouspowers/Taunt.java b/src/main/java/com/magmaguy/elitemobs/powers/miscellaneouspowers/Taunt.java new file mode 100644 index 000000000..8383eaa48 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/miscellaneouspowers/Taunt.java @@ -0,0 +1,117 @@ +package com.magmaguy.elitemobs.powers.miscellaneouspowers; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobDamagedEvent; +import com.magmaguy.elitemobs.api.EliteMobDeathEvent; +import com.magmaguy.elitemobs.api.EliteMobTargetPlayerEvent; +import com.magmaguy.elitemobs.api.PlayerDamagedByEliteMobEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.meta.MinorPower; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +/** + * Created by MagmaGuy on 06/05/2017. + */ +public class Taunt extends MinorPower implements Listener { + + private static final List TARGET_TAUNT_LIST = PowersConfig.getPower("taunt.yml").getFileConfiguration().getStringList("onTarget"); + private static final List GENERIC_DAMAGED_LIST = PowersConfig.getPower("taunt.yml").getFileConfiguration().getStringList("onDamaged"); + private static final List DAMAGED_BY_BOW_LIST = PowersConfig.getPower("taunt.yml").getFileConfiguration().getStringList("onDamagedByBow"); + private static final List HIT_LIST = PowersConfig.getPower("taunt.yml").getFileConfiguration().getStringList("onDamage"); + private static final List DEATH_LIST = PowersConfig.getPower("taunt.yml").getFileConfiguration().getStringList("onDeath"); + + public Taunt() { + super(PowersConfig.getPower("taunt.yml")); + } + + //Also used by the custom bosses + public static void nameTagProcessor(EliteEntity eliteEntity, Entity entity, List list) { + if (entity == null || !eliteEntity.isValid()) return; + int randomizedKey = ThreadLocalRandom.current().nextInt(list.size()); + String tempName = list.get(randomizedKey); + entity.setCustomName(ChatColorConverter.convert(tempName)); + new BukkitRunnable() { + + @Override + public void run() { + if (!entity.isValid()) + return; + entity.setCustomName(eliteEntity.getName()); + } + + + }.runTaskLater(MetadataHandler.PLUGIN, 4 * 20L); + } + + /** + * Runs when the Elite Mob targets a player + * + * @param event + */ + @EventHandler + public void onTarget(EliteMobTargetPlayerEvent event) { + if (!event.getEliteMobEntity().hasPower(this)) return; + nameTagProcessor(event.getEliteMobEntity(), event.getEliteMobEntity().getLivingEntity(), TARGET_TAUNT_LIST); + } + + /** + * Runs when the Elite Mob is damaged by a player + * + * @param event + */ + @EventHandler + public void onDamaged(EliteMobDamagedEvent event) { + if (!event.getEliteMobEntity().hasPower(this)) return; + + if (!(event.getEntity() instanceof LivingEntity) || + ((LivingEntity) event.getEntity()).getHealth() - event.getEntityDamageEvent().getFinalDamage() <= 0 || + !event.getEliteMobEntity().isValid()) + return; + + EliteEntity eliteEntity = EntityTracker.getEliteMobEntity(event.getEntity()); + if (eliteEntity == null) return; + if (eliteEntity.hasPower(this)) { + Entity entity = event.getEntity(); + + if (event.getEntityDamageEvent().getCause().equals(EntityDamageEvent.DamageCause.PROJECTILE)) + nameTagProcessor(eliteEntity, entity, DAMAGED_BY_BOW_LIST); + else + nameTagProcessor(eliteEntity, entity, GENERIC_DAMAGED_LIST); + } + + } + + /** + * Runs when the Elite Mob damages a player + * + * @param event + */ + @EventHandler + public void onHit(PlayerDamagedByEliteMobEvent event) { + if (!event.getEliteMobEntity().hasPower(this)) return; + nameTagProcessor(event.getEliteMobEntity(), event.getEliteMobEntity().getLivingEntity(), HIT_LIST); + } + + /** + * Runs when the Elite Mob dies + * + * @param event + */ + @EventHandler + public void onDeath(EliteMobDeathEvent event) { + if (!event.getEliteEntity().hasPower(this)) return; + nameTagProcessor(event.getEliteEntity(), event.getEntity(), DEATH_LIST); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/ArrowFireworks.java b/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/ArrowFireworks.java new file mode 100644 index 000000000..d24d23850 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/ArrowFireworks.java @@ -0,0 +1,102 @@ +package com.magmaguy.elitemobs.powers.offensivepowers; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.meta.MinorPower; +import com.magmaguy.elitemobs.utils.NonSolidBlockTypes; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.entity.Arrow; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Monster; +import org.bukkit.entity.SpectralArrow; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import java.util.concurrent.ThreadLocalRandom; + +public class ArrowFireworks extends MinorPower implements Listener { + + public ArrowFireworks() { + super(PowersConfig.getPower("arrow_fireworks.yml")); + } + + private static void doArrowFireworks(EliteEntity eliteEntity) { + + Location centeredLocation = eliteEntity.getLivingEntity().getLocation().clone().add(new Vector(0, 3, 0)); + + for (int x = 0; x < eliteEntity.getDamagers().size(); x++) { + + Location newLocation = centeredLocation.clone(); + + boolean validBlockFound = false; + for (int i = 0; i < 5; i++) { + Vector randomizedVector = new Vector(ThreadLocalRandom.current().nextInt(9) - 4, 0, ThreadLocalRandom.current().nextInt(9) - 4); + newLocation = centeredLocation.clone().add(randomizedVector); + if (NonSolidBlockTypes.isPassthrough(newLocation.getBlock().getType())) { + validBlockFound = true; + break; + } + } + + if (!validBlockFound) return; + + SpectralArrow rocketArrow = (SpectralArrow) newLocation.getWorld().spawnEntity(newLocation, EntityType.SPECTRAL_ARROW); + rocketArrow.setShooter(eliteEntity.getLivingEntity()); + rocketArrow.setVelocity(new Vector(0, 0.5, 0)); + rocketArrow.setGravity(false); + rocketArrow.setGlowing(true); + + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + if (!rocketArrow.isValid() || !eliteEntity.isValid()) { + cancel(); + return; + } + + if (counter < 20 * 1.5) { + rocketArrow.getWorld().spawnParticle(Particle.CRIT, rocketArrow.getLocation(), 1); + } else { + + for (int i = 0; i < 30; i++) { + Arrow fireworkArrow = (Arrow) rocketArrow.getWorld().spawnEntity(rocketArrow.getLocation(), EntityType.ARROW); + Vector randomizedDirection = new Vector((ThreadLocalRandom.current().nextDouble() - 0.5) * 2, (ThreadLocalRandom.current().nextDouble() - 0.5) * 2, (ThreadLocalRandom.current().nextDouble() - 0.5) * 2); + fireworkArrow.setVelocity(randomizedDirection); + fireworkArrow.setShooter(eliteEntity.getLivingEntity()); + fireworkArrow.setGlowing(true); + } + + rocketArrow.remove(); + + cancel(); + } + + counter++; + + + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + + } + + } + + @EventHandler + public void onEliteDamagedByPlayer(EliteMobDamagedByPlayerEvent event) { + if (event.isCancelled()) return; + if (!(event.getEliteMobEntity().getLivingEntity() instanceof Monster)) return; + ArrowFireworks arrowFireworks = (ArrowFireworks) event.getEliteMobEntity().getPower(this); + if (arrowFireworks == null) return; + + if (ThreadLocalRandom.current().nextDouble() > 0.15) return; + doArrowFireworks(event.getEliteMobEntity()); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/ArrowRain.java b/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/ArrowRain.java new file mode 100644 index 000000000..7a8de5805 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/ArrowRain.java @@ -0,0 +1,78 @@ +package com.magmaguy.elitemobs.powers.offensivepowers; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.bosspowers.MeteorShower; +import com.magmaguy.elitemobs.powers.meta.MinorPower; +import org.bukkit.Location; +import org.bukkit.entity.Arrow; +import org.bukkit.entity.EntityType; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import java.util.Objects; +import java.util.concurrent.ThreadLocalRandom; + +public class ArrowRain extends MinorPower implements Listener { + + public ArrowRain() { + super(PowersConfig.getPower("arrow_rain.yml")); + } + + public static void doArrowRain(EliteEntity eliteEntity) { + new BukkitRunnable() { + final Location initialLocation = eliteEntity.getLivingEntity().getLocation().clone(); + int counter = 0; + + @Override + public void run() { + + if (!eliteEntity.isValid()) { + cancel(); + return; + } + + if (counter > 10 * 20) { + cancel(); + eliteEntity.getLivingEntity().teleport(initialLocation); + return; + } + + counter++; + MeteorShower.doCloudEffect(eliteEntity.getLivingEntity().getLocation().clone().add(new Vector(0, 10, 0))); + if (counter > 20) + doArrows(eliteEntity.getLivingEntity().getLocation().clone().add(new Vector(0, 10, 0)), eliteEntity); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + } + + private static void doArrows(Location location, EliteEntity eliteEntity) { + for (int i = 0; i < 1; i++) { + int randX = ThreadLocalRandom.current().nextInt(30) - 15; + int randY = ThreadLocalRandom.current().nextInt(2); + int randZ = ThreadLocalRandom.current().nextInt(30) - 15; + Location newLocation = location.clone().add(new Vector(randX, randY, randZ)); + newLocation = newLocation.setDirection(new Vector(ThreadLocalRandom.current().nextDouble() - 0.5, -0.5, ThreadLocalRandom.current().nextDouble() - 0.5)); + Arrow arrow = (Arrow) Objects.requireNonNull(location.getWorld()).spawnEntity(newLocation, EntityType.ARROW); + arrow.setShooter(eliteEntity.getLivingEntity()); + } + } + + @EventHandler + public void onEliteDamaged(EliteMobDamagedByPlayerEvent event) { + + ArrowRain arrowRain = (ArrowRain) event.getEliteMobEntity().getPower(this); + if (arrowRain == null) return; + if (!eventIsValid(event, arrowRain)) return; + if (ThreadLocalRandom.current().nextDouble() > 0.15) return; + + arrowRain.doGlobalCooldown(20 * 15, event.getEliteMobEntity()); + doArrowRain(event.getEliteMobEntity()); + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackArrow.java b/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackArrow.java new file mode 100644 index 000000000..c5a80d981 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackArrow.java @@ -0,0 +1,64 @@ +package com.magmaguy.elitemobs.powers.offensivepowers; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobTargetPlayerEvent; +import com.magmaguy.elitemobs.combatsystem.EliteProjectile; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.meta.MinorPower; +import org.bukkit.GameMode; +import org.bukkit.entity.*; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.scheduler.BukkitRunnable; + +/** + * Created by MagmaGuy on 06/05/2017. + */ +public class AttackArrow extends MinorPower implements Listener { + + public AttackArrow() { + super(PowersConfig.getPower("attack_arrow.yml")); + } + + public static Arrow shootArrow(Entity entity, Player player) { + return (Arrow) EliteProjectile.create(EntityType.ARROW, entity, player, true); + } + + @EventHandler + public void targetEvent(EliteMobTargetPlayerEvent event) { + if (!(event.getEliteMobEntity().getLivingEntity() instanceof Monster)) return; + AttackArrow attackArrow = (AttackArrow) event.getEliteMobEntity().getPower(this); + if (attackArrow == null) return; + if (attackArrow.isFiring()) return; + + attackArrow.setFiring(true); + repeatingArrowTask(attackArrow, event.getEliteMobEntity()); + } + + private void repeatingArrowTask(AttackArrow attackArrow, EliteEntity eliteEntity) { + + new BukkitRunnable() { + + @Override + public void run() { + + if (!eliteEntity.isValid() || ((Monster) eliteEntity.getLivingEntity()).getTarget() == null) { + attackArrow.setFiring(false); + cancel(); + return; + } + + for (Entity nearbyEntity : eliteEntity.getLivingEntity().getNearbyEntities(20, 20, 20)) + if (nearbyEntity instanceof Player) + if (((Player) nearbyEntity).getGameMode().equals(GameMode.ADVENTURE) || + ((Player) nearbyEntity).getGameMode().equals(GameMode.SURVIVAL)) + shootArrow(eliteEntity.getLivingEntity(), (Player) nearbyEntity); + + } + + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 20 * 8); + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackBlinding.java b/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackBlinding.java new file mode 100644 index 000000000..84191a96b --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackBlinding.java @@ -0,0 +1,31 @@ +package com.magmaguy.elitemobs.powers.offensivepowers; + +import com.magmaguy.elitemobs.api.PlayerDamagedByEliteMobEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.powers.meta.MinorPower; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +/** + * Created by MagmaGuy on 30/04/2017. + */ +public class AttackBlinding extends MinorPower implements Listener { + + public AttackBlinding() { + super(PowersConfig.getPower("attack_blinding.yml")); + } + + @EventHandler + public void attackBlinding(PlayerDamagedByEliteMobEvent event) { + if (event.isCancelled()) return; + AttackBlinding attackBlinding = (AttackBlinding) event.getEliteMobEntity().getPower(this); + if (attackBlinding == null) return; + if (attackBlinding.isInGlobalCooldown()) return; + + attackBlinding.doGlobalCooldown(20 * 10); + event.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 20 * 5, 3)); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackConfusing.java b/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackConfusing.java new file mode 100644 index 000000000..ea7ee9e76 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackConfusing.java @@ -0,0 +1,31 @@ +package com.magmaguy.elitemobs.powers.offensivepowers; + +import com.magmaguy.elitemobs.api.PlayerDamagedByEliteMobEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.powers.meta.MinorPower; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +/** + * Created by MagmaGuy on 30/04/2017. + */ +public class AttackConfusing extends MinorPower implements Listener { + + public AttackConfusing() { + super(PowersConfig.getPower("attack_confusing.yml")); + } + + @EventHandler + public void attackConfusing(PlayerDamagedByEliteMobEvent event) { + if (event.isCancelled()) return; + AttackConfusing attackConfusing = (AttackConfusing) event.getEliteMobEntity().getPower(this); + if (attackConfusing == null) return; + if (attackConfusing.isInGlobalCooldown()) return; + + attackConfusing.doGlobalCooldown(20 * 10); + event.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.CONFUSION, 20 * 10, 3)); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackFire.java b/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackFire.java new file mode 100644 index 000000000..f0c5b53cb --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackFire.java @@ -0,0 +1,29 @@ +package com.magmaguy.elitemobs.powers.offensivepowers; + +import com.magmaguy.elitemobs.api.PlayerDamagedByEliteMobEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.powers.meta.MinorPower; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; + +/** + * Created by MagmaGuy on 28/04/2017. + */ +public class AttackFire extends MinorPower implements Listener { + + public AttackFire() { + super(PowersConfig.getPower("attack_fire.yml")); + } + + @EventHandler + public void attackFire(PlayerDamagedByEliteMobEvent event) { + + if (event.isCancelled()) return; + AttackFire attackFire = (AttackFire) event.getEliteMobEntity().getPower(this); + if (attackFire == null) return; + + event.getPlayer().setFireTicks(40); + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackFireball.java b/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackFireball.java new file mode 100644 index 000000000..b1e50f3d3 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackFireball.java @@ -0,0 +1,70 @@ +package com.magmaguy.elitemobs.powers.offensivepowers; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobTargetPlayerEvent; +import com.magmaguy.elitemobs.combatsystem.EliteProjectile; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.powers.meta.MinorPower; +import org.bukkit.GameMode; +import org.bukkit.entity.*; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.projectiles.ProjectileSource; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +/** + * Created by MagmaGuy on 06/05/2017. + */ +public class AttackFireball extends MinorPower implements Listener { + + public AttackFireball() { + super(PowersConfig.getPower("attack_fireball.yml")); + } + + public static Fireball shootFireball(Entity entity, Player player) { + Vector targetterToTargetted = player.getLocation().toVector().subtract(entity.getLocation().toVector()).normalize().multiply(0.01); + Fireball repeatingFireball = (Fireball) EliteProjectile.create(EntityType.FIREBALL, entity, player, targetterToTargetted, true); + repeatingFireball.setYield(3F); + repeatingFireball.setIsIncendiary(true); + repeatingFireball.setShooter((ProjectileSource) entity); + return repeatingFireball; + } + + @EventHandler + public void targetEvent(EliteMobTargetPlayerEvent event) { + if (!(event.getEliteMobEntity().getLivingEntity() instanceof Monster)) return; + AttackFireball attackFireball = (AttackFireball) event.getEliteMobEntity().getPower(this); + if (attackFireball == null) return; + if (attackFireball.isFiring()) return; + + attackFireball.setFiring(true); + repeatingFireballTask((Monster) event.getEntity(), attackFireball); + } + + private void repeatingFireballTask(Monster monster, AttackFireball attackFireball) { + + new BukkitRunnable() { + + @Override + public void run() { + + if (!monster.isValid() || monster.getTarget() == null) { + attackFireball.setFiring(false); + cancel(); + return; + } + + for (Entity nearbyEntity : monster.getNearbyEntities(20, 20, 20)) + if (nearbyEntity instanceof Player && + (((Player) nearbyEntity).getGameMode().equals(GameMode.ADVENTURE) || + ((Player) nearbyEntity).getGameMode().equals(GameMode.SURVIVAL))) + shootFireball(monster, (Player) nearbyEntity); + + } + + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 20L * 8); + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackFreeze.java b/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackFreeze.java new file mode 100644 index 000000000..1d68400c0 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackFreeze.java @@ -0,0 +1,56 @@ +package com.magmaguy.elitemobs.powers.offensivepowers; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.api.PlayerDamagedByEliteMobEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.config.powers.premade.AttackFreezeConfig; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.powers.meta.MinorPower; +import net.md_5.bungee.api.ChatMessageType; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +/** + * Created by MagmaGuy on 28/04/2017. + */ +public class AttackFreeze extends MinorPower implements Listener { + + public AttackFreeze() { + super(PowersConfig.getPower("attack_freeze.yml")); + } + + @EventHandler + public void attackFreeze(PlayerDamagedByEliteMobEvent event) { + if (event.isCancelled()) return; + AttackFreeze attackFreeze = (AttackFreeze) event.getEliteMobEntity().getPower(this); + if (attackFreeze == null) return; + if (attackFreeze.isInGlobalCooldown()) return; + + attackFreeze.doGlobalCooldown(20 * 15); + + /* + Slow player down + */ + event.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 20 * 3, 20)); + event.getPlayer().spigot().sendMessage(ChatMessageType.ACTION_BAR, + TextComponent.fromLegacyText(ChatColorConverter.convert(AttackFreezeConfig.freezeMessage))); + + /* + Add block effect + */ + Block block = event.getPlayer().getLocation().getBlock(); + Material originalMaterial = block.getType(); + + if (!originalMaterial.equals(Material.AIR)) + return; + + EntityTracker.addTemporaryBlock(block, 20 * 3, Material.PACKED_ICE); + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackGravity.java b/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackGravity.java new file mode 100644 index 000000000..07dde390c --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackGravity.java @@ -0,0 +1,31 @@ +package com.magmaguy.elitemobs.powers.offensivepowers; + +import com.magmaguy.elitemobs.api.PlayerDamagedByEliteMobEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.powers.meta.MinorPower; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +/** + * Created by MagmaGuy on 05/11/2016. + */ +public class AttackGravity extends MinorPower implements Listener { + + public AttackGravity() { + super(PowersConfig.getPower("attack_gravity.yml")); + } + + @EventHandler + public void attackGravity(PlayerDamagedByEliteMobEvent event) { + if (event.isCancelled()) return; + AttackGravity attackGravity = (AttackGravity) event.getEliteMobEntity().getPower(this); + if (attackGravity == null) return; + if (attackGravity.isInGlobalCooldown()) return; + + attackGravity.doGlobalCooldown(20 * 10); + event.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.LEVITATION, 2 * 20, 3)); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackLightning.java b/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackLightning.java new file mode 100644 index 000000000..bf1e0b74b --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackLightning.java @@ -0,0 +1,59 @@ +package com.magmaguy.elitemobs.powers.offensivepowers; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.EliteMobDamagedByPlayerEvent; +import com.magmaguy.elitemobs.collateralminecraftchanges.LightningSpawnBypass; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.meta.MinorPower; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.entity.Entity; +import org.bukkit.entity.EntityType; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.scheduler.BukkitRunnable; + +public class AttackLightning extends MinorPower implements Listener { + public AttackLightning() { + super(PowersConfig.getPower("attack_lightning.yml")); + } + + @EventHandler + public void onDamagedEvent(EliteMobDamagedByPlayerEvent event) { + AttackLightning attackLightning = (AttackLightning) event.getEliteMobEntity().getPower(this); + if (attackLightning == null) return; + if (attackLightning.isInGlobalCooldown()) return; + + attackLightning.doGlobalCooldown(20 * PowersConfig.getPower("attack_lightning.yml").getFileConfiguration().getInt("delayBetweenStrikes")); + + attackLightning.setFiring(true); + fireLightning(event.getEliteMobEntity()); + } + + public void fireLightning(EliteEntity eliteEntity) { + for (Entity entity : eliteEntity.getLivingEntity().getLocation().getWorld().getNearbyEntities(eliteEntity.getLivingEntity().getLocation(), 20, 20, 20)) + if (entity.getType().equals(EntityType.PLAYER)) + lightningTask(entity.getLocation().clone()); + } + + public void lightningTask(Location location) { + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + counter++; + if (counter > 20 * 3) { + LightningSpawnBypass.bypass(); + location.getWorld().strikeLightning(location); + cancel(); + return; + } + location.getWorld().spawnParticle(Particle.CRIT, location, 10, 0.5, 1.5, 0.5, 0.3); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackPoison.java b/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackPoison.java new file mode 100644 index 000000000..6d6c71910 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackPoison.java @@ -0,0 +1,29 @@ +package com.magmaguy.elitemobs.powers.offensivepowers; + +import com.magmaguy.elitemobs.api.PlayerDamagedByEliteMobEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.powers.meta.MinorPower; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +/** + * Created by MagmaGuy on 12/12/2016. + */ +public class AttackPoison extends MinorPower implements Listener { + + public AttackPoison() { + super(PowersConfig.getPower("attack_poison.yml")); + } + + @EventHandler + public void onHit(PlayerDamagedByEliteMobEvent event) { + if (event.isCancelled()) return; + AttackPoison attackPoison = (AttackPoison) event.getEliteMobEntity().getPower(this); + if (attackPoison == null) return; + + event.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.POISON, 20 * 2, 3)); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackPush.java b/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackPush.java new file mode 100644 index 000000000..0b140abad --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackPush.java @@ -0,0 +1,35 @@ +package com.magmaguy.elitemobs.powers.offensivepowers; + +import com.magmaguy.elitemobs.api.PlayerDamagedByEliteMobEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.powers.meta.MinorPower; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; + +/** + * Created by MagmaGuy on 05/11/2016. + */ +public class AttackPush extends MinorPower implements Listener { + + public AttackPush() { + super(PowersConfig.getPower("attack_push.yml")); + } + + @EventHandler + public void attackPush(PlayerDamagedByEliteMobEvent event) { + if (event.isCancelled()) return; + AttackPush attackPush = (AttackPush) event.getEliteMobEntity().getPower(this); + if (!event.getPlayer().isValid()) return; + if (!event.getEliteMobEntity().isValid()) return; + if (!event.getPlayer().getWorld().equals(event.getEliteMobEntity().getLivingEntity().getWorld())) return; + if (attackPush == null) return; + if (attackPush.isInGlobalCooldown()) return; + + attackPush.doGlobalCooldown(20 * 10); + try { + event.getPlayer().setVelocity(event.getPlayer().getLocation().clone().subtract(event.getEliteMobEntity().getLivingEntity().getLocation()).toVector().normalize().multiply(3)); + } catch (Exception ex) { + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackVacuum.java b/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackVacuum.java new file mode 100644 index 000000000..7724e8869 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackVacuum.java @@ -0,0 +1,30 @@ +package com.magmaguy.elitemobs.powers.offensivepowers; + +import com.magmaguy.elitemobs.api.PlayerDamagedByEliteMobEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.powers.meta.MinorPower; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; + +public class AttackVacuum extends MinorPower implements Listener { + + public AttackVacuum() { + super(PowersConfig.getPower("attack_vacuum.yml")); + } + + @EventHandler + public void onHit(PlayerDamagedByEliteMobEvent event) { + if (event.isCancelled()) return; + AttackVacuum attackVacuum = (AttackVacuum) event.getEliteMobEntity().getPower(this); + if (attackVacuum == null) return; + + if (event.getPlayer().isValid() && event.getEliteMobEntity().isValid() && + event.getPlayer().getWorld().equals(event.getEliteMobEntity().getLivingEntity().getWorld())) + try { + event.getPlayer().setVelocity(event.getEliteMobEntity().getLivingEntity().getLocation().clone().subtract(event.getPlayer().getLocation()).toVector().normalize()); + } catch (Exception ex) { + //sometimes this results in non-finite vectors + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackWeakness.java b/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackWeakness.java new file mode 100644 index 000000000..6826e08da --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackWeakness.java @@ -0,0 +1,31 @@ +package com.magmaguy.elitemobs.powers.offensivepowers; + +import com.magmaguy.elitemobs.api.PlayerDamagedByEliteMobEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.powers.meta.MinorPower; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +/** + * Created by MagmaGuy on 06/05/2017. + */ +public class AttackWeakness extends MinorPower implements Listener { + + public AttackWeakness() { + super(PowersConfig.getPower("attack_weakness.yml")); + } + + @EventHandler + public void attackWeakness(PlayerDamagedByEliteMobEvent event) { + if (event.isCancelled()) return; + AttackWeakness attackWeakness = (AttackWeakness) event.getEliteMobEntity().getPower(this); + if (attackWeakness == null) return; + if (attackWeakness.isInGlobalCooldown()) return; + + attackWeakness.doGlobalCooldown(20 * 10); + event.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.WEAKNESS, 20 * 3, 0)); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackWeb.java b/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackWeb.java new file mode 100644 index 000000000..9931f5723 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackWeb.java @@ -0,0 +1,34 @@ +package com.magmaguy.elitemobs.powers.offensivepowers; + +import com.magmaguy.elitemobs.api.PlayerDamagedByEliteMobEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.powers.meta.MinorPower; +import org.bukkit.Material; +import org.bukkit.block.Block; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; + +/** + * Created by MagmaGuy on 28/04/2017. + */ +public class AttackWeb extends MinorPower implements Listener { + + public AttackWeb() { + super(PowersConfig.getPower("attack_web.yml")); + } + + @EventHandler + public void attackWeb(PlayerDamagedByEliteMobEvent event) { + if (event.isCancelled()) return; + AttackWeb attackWeb = (AttackWeb) event.getEliteMobEntity().getPower(this); + if (attackWeb == null) return; + + Block block = event.getPlayer().getLocation().getBlock(); + Material originalMaterial = block.getType(); + if (!originalMaterial.equals(Material.AIR)) + return; + EntityTracker.addTemporaryBlock(block, 20 * 3, Material.COBWEB); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackWither.java b/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackWither.java new file mode 100644 index 000000000..2c1b3bbf0 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/offensivepowers/AttackWither.java @@ -0,0 +1,29 @@ +package com.magmaguy.elitemobs.powers.offensivepowers; + +import com.magmaguy.elitemobs.api.PlayerDamagedByEliteMobEvent; +import com.magmaguy.elitemobs.config.powers.PowersConfig; +import com.magmaguy.elitemobs.powers.meta.MinorPower; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; + +/** + * Created by MagmaGuy on 12/12/2016. + */ +public class AttackWither extends MinorPower implements Listener { + + public AttackWither() { + super(PowersConfig.getPower("attack_wither.yml")); + } + + @EventHandler + public void onHit(PlayerDamagedByEliteMobEvent event) { + if (event.isCancelled()) return; + AttackWither attackWither = (AttackWither) event.getEliteMobEntity().getPower(this); + if (attackWither == null) return; + + event.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.WITHER, 20 * 2, 1)); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powers/specialpowers/EnderCrystalLightningRod.java b/src/main/java/com/magmaguy/elitemobs/powers/specialpowers/EnderCrystalLightningRod.java new file mode 100644 index 000000000..d5ea5e232 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/powers/specialpowers/EnderCrystalLightningRod.java @@ -0,0 +1,58 @@ +package com.magmaguy.elitemobs.powers.specialpowers; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.majorpowers.enderdragon.EnderDragonEmpoweredLightning; +import org.bukkit.NamespacedKey; +import org.bukkit.entity.EnderCrystal; +import org.bukkit.entity.EntityType; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageEvent; +import org.bukkit.persistence.PersistentDataType; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +import java.util.concurrent.ThreadLocalRandom; + +public class EnderCrystalLightningRod { + + public EnderCrystalLightningRod(EliteEntity eliteEntity, EnderCrystal enderCrystal) { + new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + if (!eliteEntity.isValid() || !enderCrystal.isValid()) { + cancel(); + return; + } + + if (counter % 5 == 0) { + Vector randomVector = new Vector( + ThreadLocalRandom.current().nextInt(-15, 15), + 0, + ThreadLocalRandom.current().nextInt(-15, 15)); + + EnderDragonEmpoweredLightning.lightningTask(enderCrystal.getLocation().clone().add(randomVector)); + } + + counter++; + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 20); + } + + public static class EnderCrystalLightningRodEvents implements Listener { + @EventHandler(ignoreCancelled = true) + public void damageEvent(EntityDamageEvent event) { + if (!event.getEntity().getType().equals(EntityType.ENDER_CRYSTAL)) return; + if (!(event.getCause().equals(EntityDamageEvent.DamageCause.ENTITY_EXPLOSION) || + event.getCause().equals(EntityDamageEvent.DamageCause.FALLING_BLOCK) || + event.getCause().equals(EntityDamageEvent.DamageCause.LIGHTNING))) return; + if (!event.getEntity().getPersistentDataContainer().has(new NamespacedKey(MetadataHandler.PLUGIN, "eliteCrystal"), PersistentDataType.STRING)) + return; + event.setCancelled(true); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/powerstances/EffectEventHandlers.java b/src/main/java/com/magmaguy/elitemobs/powerstances/EffectEventHandlers.java index 35552855e..948950560 100644 --- a/src/main/java/com/magmaguy/elitemobs/powerstances/EffectEventHandlers.java +++ b/src/main/java/com/magmaguy/elitemobs/powerstances/EffectEventHandlers.java @@ -1,27 +1,12 @@ -/* - * 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 . - */ - package com.magmaguy.elitemobs.powerstances; -import com.magmaguy.elitemobs.EntityTracker; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityPickupItemEvent; import org.bukkit.event.entity.EntityPortalEvent; -import org.bukkit.event.entity.ItemDespawnEvent; import org.bukkit.event.inventory.InventoryPickupItemEvent; -import org.bukkit.event.player.PlayerPickupItemEvent; /** * Created by MagmaGuy on 14/07/2017. @@ -29,29 +14,21 @@ public class EffectEventHandlers implements Listener { @EventHandler - public void playerPickupSafeguard(PlayerPickupItemEvent event) { - if (EntityTracker.isItemVisualEffect(event.getItem())) + public void playerPickupSafeguard(EntityPickupItemEvent event) { + if (EntityTracker.isVisualEffect(event.getItem())) event.setCancelled(true); } - @EventHandler + @EventHandler(priority = EventPriority.LOWEST) public void hopperPickupSafeguard(InventoryPickupItemEvent event) { - if (EntityTracker.isItemVisualEffect(event.getItem())) + if (EntityTracker.isVisualEffect(event.getItem())) event.setCancelled(true); } - //todo: this prevents elite mobs from going through portals, might want to change it at some point @EventHandler public void portalPickupSafeguard(EntityPortalEvent event) { - if (EntityTracker.isItemVisualEffect(event.getEntity()) || EntityTracker.isEliteMob(event.getEntity())) - event.setCancelled(true); - } - - @EventHandler - public void itemDespawnPrevention(ItemDespawnEvent event) { - if (EntityTracker.isItemVisualEffect(event.getEntity())) + if (EntityTracker.isVisualEffect(event.getEntity()) || EntityTracker.isEliteMob(event.getEntity())) event.setCancelled(true); - } } diff --git a/src/main/java/com/magmaguy/elitemobs/powerstances/GenericRotationMatrixMath.java b/src/main/java/com/magmaguy/elitemobs/powerstances/GenericRotationMatrixMath.java index 1db493ff5..07743c356 100644 --- a/src/main/java/com/magmaguy/elitemobs/powerstances/GenericRotationMatrixMath.java +++ b/src/main/java/com/magmaguy/elitemobs/powerstances/GenericRotationMatrixMath.java @@ -1,20 +1,6 @@ -/* - * 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 . - */ - package com.magmaguy.elitemobs.powerstances; +import org.bukkit.Location; import org.bukkit.util.Vector; import static java.lang.Math.*; @@ -60,10 +46,6 @@ previous point and applying the same rotation (using the counter). It doesn't ev it easier to predict where things are supposed to be. */ - //TODO: register points in hashmap > - private static Vector newVector; - private static double newX, newY, newZ; - public static Vector applyRotation(double a, double b, double c, double numberOfPointsPerFullRotation, double x, double y, double z, int counter) { double theta; @@ -73,15 +55,43 @@ public static Vector applyRotation(double a, double b, double c, double numberOf //Get the next rotation theta = theta + theta * counter; - newX = x * (cos(theta) + (1 - cos(theta)) * pow(a, 2)) + y * ((1 - cos(theta)) * a * b + (sin(theta)) * c) + z * ((1 - cos(theta)) * a * c - (sin(theta)) * b); - newY = x * ((1 - cos(theta)) * b * a - (sin(theta)) * c) + y * (cos(theta) + (1 - cos(theta)) * pow(b, 2)) + z * ((1 - cos(theta)) * b * c + (sin(theta)) * a); - newZ = x * ((1 - cos(theta)) * c * a + (sin(theta)) * b) + y * ((1 - cos(theta)) * c * b - (sin(theta)) * a) + z * (cos(theta) + (1 - cos(theta)) * pow(c, 2)); + double newX = x * (cos(theta) + (1 - cos(theta)) * pow(a, 2)) + y * ((1 - cos(theta)) * a * b + (sin(theta)) * c) + z * ((1 - cos(theta)) * a * c - (sin(theta)) * b); + double newY = x * ((1 - cos(theta)) * b * a - (sin(theta)) * c) + y * (cos(theta) + (1 - cos(theta)) * pow(b, 2)) + z * ((1 - cos(theta)) * b * c + (sin(theta)) * a); + double newZ = x * ((1 - cos(theta)) * c * a + (sin(theta)) * b) + y * ((1 - cos(theta)) * c * b - (sin(theta)) * a) + z * (cos(theta) + (1 - cos(theta)) * pow(c, 2)); //adjust rotated point - newVector = new Vector(newX, newY, newZ); + Vector newVector = new Vector(newX, newY, newZ); return newVector; } + private static Vector rotateSpecificLocation(double a, double b, double c, double theta, Vector relativeLocation) { + double x = relativeLocation.getX(); + double y = relativeLocation.getY(); + double z = relativeLocation.getZ(); + //Convert radian to degree + theta *= PI / 180; + + double newX = x * (cos(theta) + (1 - cos(theta)) * pow(a, 2)) + y * ((1 - cos(theta)) * a * b + (sin(theta)) * c) + z * ((1 - cos(theta)) * a * c - (sin(theta)) * b); + double newY = x * ((1 - cos(theta)) * b * a - (sin(theta)) * c) + y * (cos(theta) + (1 - cos(theta)) * pow(b, 2)) + z * ((1 - cos(theta)) * b * c + (sin(theta)) * a); + double newZ = x * ((1 - cos(theta)) * c * a + (sin(theta)) * b) + y * ((1 - cos(theta)) * c * b - (sin(theta)) * a) + z * (cos(theta) + (1 - cos(theta)) * pow(c, 2)); + + return new Vector(newX, newY, newZ); + } + + public static Location rotateLocationYAxis(double rotationAngleInDegrees, Location anchorPoint, Vector relativeLocation) { + //todo: fix this + if (rotationAngleInDegrees == 90) + rotationAngleInDegrees = -90; + else if (rotationAngleInDegrees == -90) + rotationAngleInDegrees = 90; + Vector rotatedVector = relativeLocation.clone().rotateAroundY(Math.toRadians(rotationAngleInDegrees)).add(anchorPoint.toVector()); + return new Location(anchorPoint.getWorld(), rotatedVector.getX(), rotatedVector.getY(), rotatedVector.getZ()); + } + + public static Vector rotateVectorYAxis(double rotationAngleInDegrees, Location anchorPoint, Vector relativeLocation) { + return rotateLocationYAxis(rotationAngleInDegrees, anchorPoint, relativeLocation).toVector(); + } + } diff --git a/src/main/java/com/magmaguy/elitemobs/powerstances/MajorPowerPowerStance.java b/src/main/java/com/magmaguy/elitemobs/powerstances/MajorPowerPowerStance.java index 518e764ab..929d45098 100644 --- a/src/main/java/com/magmaguy/elitemobs/powerstances/MajorPowerPowerStance.java +++ b/src/main/java/com/magmaguy/elitemobs/powerstances/MajorPowerPowerStance.java @@ -1,11 +1,10 @@ package com.magmaguy.elitemobs.powerstances; -import com.magmaguy.elitemobs.EntityTracker; -import com.magmaguy.elitemobs.config.ConfigValues; import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; -import com.magmaguy.elitemobs.mobpowers.ElitePower; -import com.magmaguy.elitemobs.mobpowers.majorpowers.*; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.meta.ElitePower; +import com.magmaguy.elitemobs.powers.meta.MajorPower; import com.magmaguy.elitemobs.utils.VersionChecker; import org.bukkit.Material; import org.bukkit.Particle; @@ -23,29 +22,28 @@ public class MajorPowerPowerStance implements Listener { public static int trackAmount = 2; public static int individualEffectsPerTrack = 2; - private EliteMobEntity eliteMobEntity; + private EliteEntity eliteEntity; - public MajorPowerPowerStance(EliteMobEntity eliteMobEntity) { + public MajorPowerPowerStance(EliteEntity eliteEntity) { - if (!ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.ENABLE_VISUAL_EFFECTS_FOR_NATURAL_MOBS)) + if (!MobCombatSettingsConfig.isEnableVisualEffectsForNaturalMobs()) return; - if (ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.DISABLE_VISUAL_EFFECTS_FOR_SPAWNER_MOBS) - && !eliteMobEntity.isNaturalEntity()) + if (MobCombatSettingsConfig.isDisableVisualEffectsForSpawnerMobs() && !eliteEntity.isNaturalEntity()) return; - this.eliteMobEntity = eliteMobEntity; + this.eliteEntity = eliteEntity; - if (eliteMobEntity.hasMajorVisualEffect()) return; - eliteMobEntity.setHasMajorVisualEffect(true); + if (eliteEntity.isMajorVisualEffect()) return; + eliteEntity.setMajorVisualEffect(true); - if (eliteMobEntity.getMajorPowerCount() < 1) + if (eliteEntity.getMajorPowerCount() < 1) return; /* Obfuscate powers to prevent TPS loss */ - if (ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.OBFUSCATE_MOB_POWERS)) - if (eliteMobEntity.getHasVisualEffectObfuscated()) { + if (MobCombatSettingsConfig.isObfuscateMobPowers()) + if (eliteEntity.isVisualEffectObfuscated()) { Object[][] multiDimensionalTrailTracker = new Object[trackAmount][individualEffectsPerTrack]; for (int i = 0; i < multiDimensionalTrailTracker.length; i++) { @@ -59,13 +57,13 @@ public MajorPowerPowerStance(EliteMobEntity eliteMobEntity) { } VisualItemProcessor visualItemProcessor = new VisualItemProcessor(multiDimensionalTrailTracker, - MajorPowerStanceMath.cachedVectors, eliteMobEntity.hasMajorVisualEffect(), - MajorPowerStanceMath.NUMBER_OF_POINTS_PER_FULL_ROTATION, eliteMobEntity); + MajorPowerStanceMath.cachedVectors, eliteEntity.isMajorVisualEffect(), + MajorPowerStanceMath.NUMBER_OF_POINTS_PER_FULL_ROTATION, eliteEntity); return; } - Object[][] multiDimensionalTrailTracker = new Object[trackAmount][eliteMobEntity.getMajorPowerCount() * individualEffectsPerTrack]; + Object[][] multiDimensionalTrailTracker = new Object[trackAmount][eliteEntity.getMajorPowerCount() * individualEffectsPerTrack]; for (int i = 0; i < multiDimensionalTrailTracker.length; i++) { ArrayList localObjects = new ArrayList<>(); @@ -77,8 +75,8 @@ public MajorPowerPowerStance(EliteMobEntity eliteMobEntity) { } VisualItemProcessor visualItemProcessor = new VisualItemProcessor(multiDimensionalTrailTracker, - MajorPowerStanceMath.cachedVectors, eliteMobEntity.hasMajorVisualEffect(), - MajorPowerStanceMath.NUMBER_OF_POINTS_PER_FULL_ROTATION, eliteMobEntity); + MajorPowerStanceMath.cachedVectors, eliteEntity.isMajorVisualEffect(), + MajorPowerStanceMath.NUMBER_OF_POINTS_PER_FULL_ROTATION, eliteEntity); } @@ -90,52 +88,44 @@ private ArrayList addAllEffects() { ArrayList effects = new ArrayList<>(); - for (ElitePower elitePower : eliteMobEntity.getPowers()) { + for (ElitePower elitePower : eliteEntity.getElitePowers()) + if (elitePower instanceof MajorPower) + if (eliteEntity.getPower(elitePower).getTrail() != null) + effects.add(effectParser(eliteEntity.getPower(elitePower).getTrail())); - if (elitePower instanceof SkeletonPillar) - effects.add(addEffect(Material.BONE)); - - if (elitePower instanceof SkeletonTrackingArrow) - effects.add(addEffect(Material.TIPPED_ARROW)); - - if (elitePower instanceof ZombieBloat) - effects.add(addEffect(Material.RED_MUSHROOM)); - - if (elitePower instanceof ZombieFriends) - effects.add(addEffect(Material.SKULL_ITEM)); - - if (elitePower instanceof ZombieNecronomicon) - effects.add(addEffect(Material.WRITTEN_BOOK)); - - if (elitePower instanceof ZombieParents) - effects.add(addEffect(Material.MONSTER_EGG)); + return effects; - if (elitePower instanceof ZombieTeamRocket) - effects.add(addEffect(Material.FIREWORK)); + } + private Object effectParser(String powerString) { + try { + Material material = Material.valueOf(powerString); + return addEffect(material); + } catch (Exception ex) { } - - return effects; - + try { + Particle particle = Particle.valueOf(powerString); + return addEffect(particle); + } catch (Exception ex) { + } + return null; } private Object addEffect(Material material) { - Item item = eliteMobEntity.getLivingEntity().getWorld().dropItem(eliteMobEntity.getLivingEntity().getLocation(), + Item item = eliteEntity.getLivingEntity().getWorld().dropItem(eliteEntity.getLivingEntity().getLocation(), new ItemStack(material)); item.setPickupDelay(Integer.MAX_VALUE); - if (!VersionChecker.currentVersionIsUnder(1, 11)) + if (!VersionChecker.serverVersionOlderThan(1, 11)) item.setGravity(false); item.setInvulnerable(true); - EntityTracker.registerItemVisualEffects(item); + EntityTracker.registerVisualEffects(item); return item; } private Object addEffect(Particle particle) { - return particle; - } } diff --git a/src/main/java/com/magmaguy/elitemobs/powerstances/MajorPowerStanceMath.java b/src/main/java/com/magmaguy/elitemobs/powerstances/MajorPowerStanceMath.java index d3cb6a6c0..3ea8a17c0 100644 --- a/src/main/java/com/magmaguy/elitemobs/powerstances/MajorPowerStanceMath.java +++ b/src/main/java/com/magmaguy/elitemobs/powerstances/MajorPowerStanceMath.java @@ -14,8 +14,8 @@ public class MajorPowerStanceMath { private final static double X = 0; private final static double Y = 1; private final static double Z = 0; - private static double a, b, c; public static Vector[][] cachedVectors = new Vector[MajorPowerPowerStance.trackAmount][NUMBER_OF_POINTS_PER_FULL_ROTATION]; + private static double a, b, c; public static void initializeVectorCache() { diff --git a/src/main/java/com/magmaguy/elitemobs/powerstances/MinorPowerPowerStance.java b/src/main/java/com/magmaguy/elitemobs/powerstances/MinorPowerPowerStance.java index 8db0d1546..293477e36 100644 --- a/src/main/java/com/magmaguy/elitemobs/powerstances/MinorPowerPowerStance.java +++ b/src/main/java/com/magmaguy/elitemobs/powerstances/MinorPowerPowerStance.java @@ -1,15 +1,10 @@ package com.magmaguy.elitemobs.powerstances; -import com.magmaguy.elitemobs.EntityTracker; -import com.magmaguy.elitemobs.config.ConfigValues; import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; -import com.magmaguy.elitemobs.mobpowers.ElitePower; -import com.magmaguy.elitemobs.mobpowers.defensivepowers.*; -import com.magmaguy.elitemobs.mobpowers.miscellaneouspowers.BonusLoot; -import com.magmaguy.elitemobs.mobpowers.miscellaneouspowers.MovementSpeed; -import com.magmaguy.elitemobs.mobpowers.miscellaneouspowers.Taunt; -import com.magmaguy.elitemobs.mobpowers.offensivepowers.*; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.powers.meta.ElitePower; +import com.magmaguy.elitemobs.powers.meta.MinorPower; import com.magmaguy.elitemobs.utils.VersionChecker; import org.bukkit.Material; import org.bukkit.Particle; @@ -27,29 +22,28 @@ public class MinorPowerPowerStance implements Listener { public static int trackAmount = 2; public static int individualEffectsPerTrack = 2; - private EliteMobEntity eliteMobEntity; + private EliteEntity eliteEntity; //Secondary effect item processing - public MinorPowerPowerStance(EliteMobEntity eliteMobEntity) { + public MinorPowerPowerStance(EliteEntity eliteEntity) { - if (!ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.ENABLE_VISUAL_EFFECTS_FOR_NATURAL_MOBS)) + if (!MobCombatSettingsConfig.isEnableVisualEffectsForNaturalMobs()) return; - if (ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.DISABLE_VISUAL_EFFECTS_FOR_SPAWNER_MOBS) - && !eliteMobEntity.isNaturalEntity()) + if (MobCombatSettingsConfig.isDisableVisualEffectsForSpawnerMobs() && !eliteEntity.isNaturalEntity()) return; - this.eliteMobEntity = eliteMobEntity; - if (eliteMobEntity.hasMinorVisualEffect()) return; - eliteMobEntity.setHasMinorVisualEffect(true); + this.eliteEntity = eliteEntity; + if (eliteEntity.isMinorVisualEffect()) return; + eliteEntity.setMinorVisualEffect(true); - if (eliteMobEntity.getMinorPowerCount() < 1) + if (eliteEntity.getMinorPowerCount() < 1) return; /* Obfuscate powers to prevent TPS loss */ - if (ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.OBFUSCATE_MOB_POWERS)) - if (eliteMobEntity.getHasVisualEffectObfuscated()) { + if (MobCombatSettingsConfig.isObfuscateMobPowers()) + if (eliteEntity.isVisualEffectObfuscated()) { Object[][] multiDimensionalTrailTracker = new Object[trackAmount][individualEffectsPerTrack]; for (int i = 0; i < multiDimensionalTrailTracker.length; i++) { @@ -63,26 +57,26 @@ public MinorPowerPowerStance(EliteMobEntity eliteMobEntity) { } VisualItemProcessor visualItemProcessor = new VisualItemProcessor(multiDimensionalTrailTracker, - MinorPowerStanceMath.cachedVectors, eliteMobEntity.hasMinorVisualEffect(), - MinorPowerStanceMath.NUMBER_OF_POINTS_PER_FULL_ROTATION, eliteMobEntity); + MinorPowerStanceMath.cachedVectors, eliteEntity.isMinorVisualEffect(), + MinorPowerStanceMath.NUMBER_OF_POINTS_PER_FULL_ROTATION, eliteEntity); return; } - Object[][] multiDimensionalTrailTracker = new Object[trackAmount][eliteMobEntity.getMinorPowerCount() * individualEffectsPerTrack]; + Object[][] multiDimensionalTrailTracker = new Object[trackAmount][eliteEntity.getMinorPowerCount() * individualEffectsPerTrack]; for (int i = 0; i < multiDimensionalTrailTracker.length; i++) { ArrayList localObjects = new ArrayList<>(); for (int a = 0; a < multiDimensionalTrailTracker.length; a++) localObjects.addAll(addAllEffects()); - for (int j = 0; j < multiDimensionalTrailTracker[0].length; j++) + for (int j = 0; j < localObjects.size(); j++) if (localObjects.get(j) != null) multiDimensionalTrailTracker[i][j] = localObjects.get(j); } VisualItemProcessor visualItemProcessor = new VisualItemProcessor(multiDimensionalTrailTracker, - MinorPowerStanceMath.cachedVectors, eliteMobEntity.hasMinorVisualEffect(), - MinorPowerStanceMath.NUMBER_OF_POINTS_PER_FULL_ROTATION, eliteMobEntity); + MinorPowerStanceMath.cachedVectors, eliteEntity.isMinorVisualEffect(), + MinorPowerStanceMath.NUMBER_OF_POINTS_PER_FULL_ROTATION, eliteEntity); } @@ -94,84 +88,38 @@ private ArrayList addAllEffects() { ArrayList effects = new ArrayList<>(); - for (ElitePower elitePower : eliteMobEntity.getPowers()) { + for (ElitePower elitePower : eliteEntity.getElitePowers()) + if (elitePower instanceof MinorPower) + if (eliteEntity.getPower(elitePower).getTrail() != null) + effects.add(effectParser(eliteEntity.getPower(elitePower).getTrail())); - if (elitePower instanceof AttackArrow) - effects.add(addEffect(Material.ARROW)); - - if (elitePower instanceof AttackBlinding) - effects.add(addEffect(Material.EYE_OF_ENDER)); - - if (elitePower instanceof AttackConfusing) - effects.add(addEffect(Particle.SPELL_MOB)); - - if (elitePower instanceof AttackFire) - effects.add(addEffect(Material.LAVA_BUCKET)); - - if (elitePower instanceof AttackFireball) - effects.add(addEffect(Material.FIREBALL)); - - if (elitePower instanceof AttackFreeze) - effects.add(addEffect(Material.PACKED_ICE)); - - if (elitePower instanceof AttackGravity) - effects.add(addEffect(Material.ELYTRA)); - - if (elitePower instanceof AttackPoison) - effects.add(addEffect(Material.EMERALD)); - - if (elitePower instanceof AttackPush) - effects.add(addEffect(Material.PISTON_BASE)); - - if (!VersionChecker.currentVersionIsUnder(11, 0)) - if (elitePower instanceof AttackWeakness) - effects.add(addEffect(Material.TOTEM)); - - if (elitePower instanceof AttackWeb) - effects.add(addEffect(Material.WEB)); - - if (elitePower instanceof AttackWither) - effects.add(addEffect(Material.SKULL_ITEM)); - - if (elitePower instanceof BonusLoot) - effects.add(addEffect(Material.CHEST)); - - if (elitePower instanceof MovementSpeed) - effects.add(addEffect(Material.GOLD_BOOTS)); - - if (elitePower instanceof Taunt) - effects.add(addEffect(Material.JUKEBOX)); - - if (elitePower instanceof Invisibility) - effects.add(addEffect(Material.THIN_GLASS)); - - if (elitePower instanceof InvulnerabilityArrow) - effects.add(addEffect(Material.SPECTRAL_ARROW)); - - if (elitePower instanceof InvulnerabilityFallDamage) - effects.add(addEffect(Material.FEATHER)); - - if (elitePower instanceof InvulnerabilityFire) - effects.add(addEffect(Particle.FLAME)); + return effects; - if (elitePower instanceof InvulnerabilityKnockback) - effects.add(addEffect(Material.ANVIL)); + } + private Object effectParser(String powerString) { + try { + Material material = Material.valueOf(powerString); + return addEffect(material); + } catch (Exception ex) { } - - return effects; - + try { + Particle particle = Particle.valueOf(powerString); + return addEffect(particle); + } catch (Exception ex) { + } + return null; } private Object addEffect(Material material) { - Item item = eliteMobEntity.getLivingEntity().getWorld().dropItem(eliteMobEntity.getLivingEntity().getLocation(), + Item item = eliteEntity.getLivingEntity().getWorld().dropItem(eliteEntity.getLivingEntity().getLocation(), new ItemStack(material)); item.setPickupDelay(Integer.MAX_VALUE); - if (!VersionChecker.currentVersionIsUnder(1, 11)) + if (!VersionChecker.serverVersionOlderThan(1, 11)) item.setGravity(false); item.setInvulnerable(true); - EntityTracker.registerItemVisualEffects(item); + EntityTracker.registerVisualEffects(item); return item; } diff --git a/src/main/java/com/magmaguy/elitemobs/powerstances/MinorPowerStanceMath.java b/src/main/java/com/magmaguy/elitemobs/powerstances/MinorPowerStanceMath.java index f24926f4f..4cffd1134 100644 --- a/src/main/java/com/magmaguy/elitemobs/powerstances/MinorPowerStanceMath.java +++ b/src/main/java/com/magmaguy/elitemobs/powerstances/MinorPowerStanceMath.java @@ -10,10 +10,10 @@ public class MinorPowerStanceMath { public final static int NUMBER_OF_POINTS_PER_FULL_ROTATION = 30; private final static double X = 1; - private static double Y = 0; private final static double Z = 0; - private static double a, b, c; public static Vector[][] cachedVectors = new Vector[MinorPowerPowerStance.trackAmount][NUMBER_OF_POINTS_PER_FULL_ROTATION]; + private static double Y = 0; + private static double a, b, c; public static void initializeVectorCache() { diff --git a/src/main/java/com/magmaguy/elitemobs/powerstances/VisualEffectObfuscator.java b/src/main/java/com/magmaguy/elitemobs/powerstances/VisualEffectObfuscator.java index ab2cd40e9..302bc81fe 100644 --- a/src/main/java/com/magmaguy/elitemobs/powerstances/VisualEffectObfuscator.java +++ b/src/main/java/com/magmaguy/elitemobs/powerstances/VisualEffectObfuscator.java @@ -1,7 +1,7 @@ package com.magmaguy.elitemobs.powerstances; -import com.magmaguy.elitemobs.EntityTracker; -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; import com.magmaguy.elitemobs.utils.EntityFinder; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -14,19 +14,19 @@ public class VisualEffectObfuscator implements Listener { @EventHandler public void onTargetPlayer(EntityTargetLivingEntityEvent event) { if (!(event.getTarget() instanceof Player)) return; - EliteMobEntity eliteMobEntity = EntityTracker.getEliteMobEntity(event.getEntity()); - if (eliteMobEntity == null) return; + EliteEntity eliteEntity = EntityTracker.getEliteMobEntity(event.getEntity()); + if (eliteEntity == null) return; - eliteMobEntity.setHasVisualEffectObfuscated(false); + eliteEntity.setVisualEffectObfuscated(false); } @EventHandler public void onDamageByPlayer(EntityDamageByEntityEvent event) { if (!(EntityFinder.getRealDamager(event) instanceof Player)) return; - EliteMobEntity eliteMobEntity = EntityTracker.getEliteMobEntity(event.getEntity()); - if (eliteMobEntity == null) return; + EliteEntity eliteEntity = EntityTracker.getEliteMobEntity(event.getEntity()); + if (eliteEntity == null) return; - eliteMobEntity.setHasVisualEffectObfuscated(false); + eliteEntity.setVisualEffectObfuscated(false); } } diff --git a/src/main/java/com/magmaguy/elitemobs/powerstances/VisualItemInitializer.java b/src/main/java/com/magmaguy/elitemobs/powerstances/VisualItemInitializer.java index a92b36800..815ad6eeb 100644 --- a/src/main/java/com/magmaguy/elitemobs/powerstances/VisualItemInitializer.java +++ b/src/main/java/com/magmaguy/elitemobs/powerstances/VisualItemInitializer.java @@ -1,24 +1,24 @@ package com.magmaguy.elitemobs.powerstances; -import com.magmaguy.elitemobs.EntityTracker; -import com.magmaguy.elitemobs.utils.VersionChecker; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; import org.bukkit.Location; import org.bukkit.entity.Item; import org.bukkit.inventory.ItemStack; +import org.bukkit.metadata.FixedMetadataValue; public class VisualItemInitializer { + private VisualItemInitializer() { + } - public static Item intializeItem(ItemStack itemStack, Location location) { - + public static Item initializeItem(ItemStack itemStack, Location location) { Item item = location.getWorld().dropItem(location, itemStack); item.setPickupDelay(Integer.MAX_VALUE); - EntityTracker.registerItemVisualEffects(item); - if (!VersionChecker.currentVersionIsUnder(1, 11)) - item.setGravity(false); + EntityTracker.registerVisualEffects(item); + item.setGravity(false); item.setInvulnerable(true); - + item.setMetadata(MetadataHandler.BETTERDROPS_COMPATIBILITY_MD, new FixedMetadataValue(MetadataHandler.PLUGIN, true)); return item; - } } diff --git a/src/main/java/com/magmaguy/elitemobs/powerstances/VisualItemProcessor.java b/src/main/java/com/magmaguy/elitemobs/powerstances/VisualItemProcessor.java index 7d2aa4d83..d550056ac 100644 --- a/src/main/java/com/magmaguy/elitemobs/powerstances/VisualItemProcessor.java +++ b/src/main/java/com/magmaguy/elitemobs/powerstances/VisualItemProcessor.java @@ -1,7 +1,7 @@ package com.magmaguy.elitemobs.powerstances; import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; import org.bukkit.Location; import org.bukkit.Particle; import org.bukkit.entity.Item; @@ -15,28 +15,39 @@ public class VisualItemProcessor { private boolean hasValidEffect; public VisualItemProcessor(Object[][] multiDimensionalTrailTracker, Vector[][] cachedVectorPositions, - boolean visualEffectBoolean, int pointsPerRotation, EliteMobEntity eliteMobEntity) { + boolean visualEffectBoolean, int pointsPerRotation, EliteEntity eliteEntity) { this.hasValidEffect = visualEffectBoolean; if (multiDimensionalTrailTracker.length < 1) return; - rotateExistingEffects(multiDimensionalTrailTracker, cachedVectorPositions, pointsPerRotation, eliteMobEntity); + rotateExistingEffects(multiDimensionalTrailTracker, cachedVectorPositions, pointsPerRotation, eliteEntity); } + /* + Adjusts the position in each item track based on the amount of powers currently in that track + */ + public static int adjustTrackPosition(double pointsPerRotation, int totalEffectQuantity, + int sectionCounter, int globalCounter) { + int location = (int) (pointsPerRotation / totalEffectQuantity * sectionCounter + globalCounter); + if (location >= 30) + location -= 30; + return location; + } + private void rotateExistingEffects(Object[][] multiDimensionalTrailTracker, Vector[][] cachedVectorPositions, - int pointsPerRotation, EliteMobEntity eliteMobEntity) { + int pointsPerRotation, EliteEntity eliteEntity) { new BukkitRunnable() { + final boolean isObfuscated = eliteEntity.isVisualEffectObfuscated(); int counter = 0; - boolean isObfuscated = eliteMobEntity.getHasVisualEffectObfuscated(); @Override public void run() { - if (!eliteMobEntity.getLivingEntity().isValid() || !hasValidEffect) { + if (!eliteEntity.isValid() || !hasValidEffect) { VisualItemRemover.removeItems(multiDimensionalTrailTracker); cancel(); return; @@ -55,10 +66,10 @@ public void run() { Vector vector = cachedVectorPositions[i][adjustedEffectPositionInRotation]; if (multiDimensionalTrailTracker[i][j] instanceof Item) - rotateItem(multiDimensionalTrailTracker[i][j], vector, eliteMobEntity); + rotateItem(multiDimensionalTrailTracker[i][j], vector, eliteEntity); if (multiDimensionalTrailTracker[i][j] instanceof Particle) - rotateParticle(multiDimensionalTrailTracker[i][j], vector, eliteMobEntity); + rotateParticle(multiDimensionalTrailTracker[i][j], vector, eliteEntity); sectionCounter++; if (sectionCounter >= pointsPerRotation) @@ -76,20 +87,20 @@ public void run() { /* Check if the effect has ceased being obfuscated */ - if (isObfuscated != eliteMobEntity.getHasVisualEffectObfuscated()){ + if (isObfuscated != eliteEntity.isVisualEffectObfuscated()) { VisualItemRemover.removeItems(multiDimensionalTrailTracker); cancel(); new BukkitRunnable() { @Override public void run() { - eliteMobEntity.setHasVisualEffectObfuscated(false); + eliteEntity.setVisualEffectObfuscated(false); if (Arrays.deepEquals(cachedVectorPositions, MinorPowerStanceMath.cachedVectors)) { - eliteMobEntity.setHasMinorVisualEffect(false); - new MinorPowerPowerStance(eliteMobEntity); + eliteEntity.setMinorVisualEffect(false); + new MinorPowerPowerStance(eliteEntity); } if (Arrays.deepEquals(cachedVectorPositions, MajorPowerStanceMath.cachedVectors)) { - eliteMobEntity.setHasMajorVisualEffect(false); - new MajorPowerPowerStance(eliteMobEntity); + eliteEntity.setMajorVisualEffect(false); + new MajorPowerPowerStance(eliteEntity); } } }.runTask(MetadataHandler.PLUGIN); @@ -102,49 +113,45 @@ public void run() { } - /* - Adjusts the position in each item track based on the amount of powers currently in that track - */ - public static int adjustTrackPosition(double pointsPerRotation, int totalEffectQuantity, - int sectionCounter, int globalCounter) { - int location = (int) (pointsPerRotation / totalEffectQuantity * sectionCounter + globalCounter); - if (location >= 30) - location -= 30; - return location; - } - - private void rotateItem(Object itemObject, Vector vector, EliteMobEntity eliteMobEntity) { + private void rotateItem(Object itemObject, Vector vector, EliteEntity eliteEntity) { Item item = (Item) itemObject; - if (!item.isValid()) - return; +// if (!item.isValid()) +// return; Location currentLocation = item.getLocation().clone(); - Location newLocation = eliteMobEntity.getLivingEntity().getLocation().clone().add(new Vector(0, 1, 0)).add(vector); + Location newLocation = eliteEntity.getLivingEntity().getLocation().clone().add(new Vector(0, 1, 0)).add(vector); + +// if (currentLocation.distanceSquared(newLocation) > Math.pow(3, 2)) { +// item.teleport(newLocation); +// item.setVelocity(new Vector(0.01, 0.01, 0.01)); +// return; +// } - if (currentLocation.distanceSquared(newLocation) > Math.pow(3, 2)) { - item.teleport(newLocation); - item.setVelocity(new Vector(0.01, 0.01, 0.01)); + //this sometimes happens due to other plugins which is really annoying + if (newLocation.getWorld() != currentLocation.getWorld()){ + hasValidEffect = false; return; } Vector movementVector = (newLocation.subtract(currentLocation)).toVector(); movementVector = movementVector.multiply(0.3); - if (Math.abs(movementVector.getX()) > 3 || Math.abs(movementVector.getY()) > 3 || Math.abs(movementVector.getZ()) > 3) { - item.teleport(newLocation); - } else { - item.setVelocity(movementVector); - } +// if (Math.abs(movementVector.getX()) > 3 || Math.abs(movementVector.getY()) > 3 || Math.abs(movementVector.getZ()) > 3) { +// item.teleport(newLocation); +// } else { + item.setVelocity(movementVector); +// } } - private void rotateParticle(Object particleObject, Vector vector, EliteMobEntity eliteMobEntity) { + private void rotateParticle(Object particleObject, Vector vector, EliteEntity eliteEntity) { Particle particle = (Particle) particleObject; - eliteMobEntity.getLivingEntity().getWorld().spawnParticle( - particle, eliteMobEntity.getLivingEntity().getLocation().add(0, 1, 0).add(vector), - 5, 0, 0, 0, 0.01); + if (eliteEntity.isValid()) + eliteEntity.getLivingEntity().getWorld().spawnParticle( + particle, eliteEntity.getLivingEntity().getLocation().add(0, 1, 0).add(vector), + 1, 0, 0, 0, 0.01); } } diff --git a/src/main/java/com/magmaguy/elitemobs/powerstances/VisualItemRemover.java b/src/main/java/com/magmaguy/elitemobs/powerstances/VisualItemRemover.java index 1450cfc74..f205443e0 100644 --- a/src/main/java/com/magmaguy/elitemobs/powerstances/VisualItemRemover.java +++ b/src/main/java/com/magmaguy/elitemobs/powerstances/VisualItemRemover.java @@ -1,22 +1,29 @@ package com.magmaguy.elitemobs.powerstances; -import com.magmaguy.elitemobs.EntityTracker; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.internal.RemovalReason; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; import org.bukkit.entity.Item; +import org.bukkit.scheduler.BukkitRunnable; public class VisualItemRemover { - public static void removeItems(Object[][] multiDimensionalTrailTracker) { - - for (int i = 0; i < multiDimensionalTrailTracker.length; i++) - for (int j = 0; j < multiDimensionalTrailTracker[i].length; j++) { - - if (!(multiDimensionalTrailTracker[i][j] instanceof Item)) continue; - Item item = (Item) multiDimensionalTrailTracker[i][j]; - item.remove(); - EntityTracker.unregisterItemEntity(item); + private VisualItemRemover() { + } + public static void removeItems(Object[][] multiDimensionalTrailTracker) { + for (Object[] objects : multiDimensionalTrailTracker) + for (Object object : objects) { + if (!(object instanceof Item)) continue; + Item item = (Item) object; + new BukkitRunnable() { + @Override + public void run() { + item.remove(); + EntityTracker.unregister(item, RemovalReason.EFFECT_TIMEOUT); + } + }.runTask(MetadataHandler.PLUGIN); } - } } diff --git a/src/main/java/com/magmaguy/elitemobs/quests/CustomQuest.java b/src/main/java/com/magmaguy/elitemobs/quests/CustomQuest.java new file mode 100644 index 000000000..5748fc9d5 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/quests/CustomQuest.java @@ -0,0 +1,133 @@ +package com.magmaguy.elitemobs.quests; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.QuestAcceptEvent; +import com.magmaguy.elitemobs.api.QuestRewardEvent; +import com.magmaguy.elitemobs.config.customquests.CustomQuestsConfig; +import com.magmaguy.elitemobs.config.customquests.CustomQuestsConfigFields; +import com.magmaguy.elitemobs.playerdata.database.PlayerData; +import com.magmaguy.elitemobs.quests.objectives.QuestObjectives; +import com.magmaguy.elitemobs.quests.playercooldowns.PlayerQuestCooldowns; +import com.magmaguy.elitemobs.quests.rewards.QuestReward; +import com.magmaguy.elitemobs.utils.EventCaller; +import com.magmaguy.elitemobs.utils.WarningMessage; +import lombok.Getter; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.permissions.PermissionAttachment; + +import java.util.UUID; + +public class CustomQuest extends Quest { + + @Getter + private final String configurationFilename; + private transient CustomQuestsConfigFields customQuestsConfigFields; + + public CustomQuest(Player player, CustomQuestsConfigFields customQuestsConfigFields) { + super(player, new QuestObjectives(new QuestReward(customQuestsConfigFields, player)), customQuestsConfigFields.getQuestLevel()); + this.customQuestsConfigFields = customQuestsConfigFields; + this.configurationFilename = customQuestsConfigFields.getFilename(); + super.questObjectives.setQuest(this); + super.questName = customQuestsConfigFields.getQuestName(); + super.questTaker = customQuestsConfigFields.getTurnInNPC(); + } + + public static CustomQuest getQuest(String questFilename, Player player) { + if (CustomQuestsConfig.getCustomQuests().get(questFilename) == null) return null; + Quest quest = null; + for (Quest iteratedQuest : PlayerData.getQuests(player.getUniqueId())) + if (iteratedQuest instanceof CustomQuest && ((CustomQuest) iteratedQuest).getConfigurationFilename().equals(questFilename)) { + quest = iteratedQuest; + break; + } + if (quest != null) + return (CustomQuest) quest; + else + return new CustomQuest(player, CustomQuestsConfig.getCustomQuests().get(questFilename)); + } + + public static Quest startQuest(String questID, Player player) { + Quest quest = null; + for (Quest iteratedQuest : pendingPlayerQuests.get(player.getUniqueId())) + if (iteratedQuest.getQuestID().equals(UUID.fromString(questID))) { + quest = iteratedQuest; + break; + } + if (quest == null) { + player.sendMessage(ChatColorConverter.convert("&8[EliteMobs] &cInvalid quest ID for ID " + questID)); + return null; + } + QuestAcceptEvent questAcceptEvent = new QuestAcceptEvent(player, quest); + new EventCaller(questAcceptEvent); + if (questAcceptEvent.isCancelled()) return null; + return quest; + } + + public CustomQuestsConfigFields getCustomQuestsConfigFields() { + if (customQuestsConfigFields == null) + this.customQuestsConfigFields = CustomQuestsConfig.getCustomQuests().get(configurationFilename); + if (customQuestsConfigFields == null) { + new WarningMessage("Detected that Custom Quest " + configurationFilename + " got removed even though player " + + Bukkit.getPlayer(getPlayerUUID()).getName() + " is still trying to complete it. This player's quest will now be wiped."); + PlayerData.removeQuest(getPlayerUUID(), this); + return null; + } + return customQuestsConfigFields; + } + + public void applyTemporaryPermissions(Player player) { + if (!getCustomQuestsConfigFields().getTemporaryPermissions().isEmpty()) { + PermissionAttachment permissionAttachment = player.addAttachment(MetadataHandler.PLUGIN); + for (String permission : getCustomQuestsConfigFields().getTemporaryPermissions()) + permissionAttachment.setPermission(permission, true); + } + } + + public void applyEndPermissions(Player player) { + if (!getCustomQuestsConfigFields().getTemporaryPermissions().isEmpty()) { + PermissionAttachment permissionAttachment = player.addAttachment(MetadataHandler.PLUGIN); + for (String permission : getCustomQuestsConfigFields().getTemporaryPermissions()) + permissionAttachment.unsetPermission(permission); + } + if (!getCustomQuestsConfigFields().getQuestLockoutPermission().isEmpty()) { + PlayerQuestCooldowns.addCooldown(player, + getCustomQuestsConfigFields().getQuestLockoutPermission(), + getCustomQuestsConfigFields().getQuestLockoutMinutes()); + } + } + + public boolean hasPermissionForQuest(Player player) { + if (!customQuestsConfigFields.getQuestAcceptPermission().isEmpty() && + !player.hasMetadata(customQuestsConfigFields.getQuestAcceptPermission())) + return false; + if (!customQuestsConfigFields.getQuestLockoutPermission().isEmpty() && + player.hasMetadata(customQuestsConfigFields.getQuestLockoutPermission())) + return false; + return true; + } + + public static class CustomQuestEvents implements Listener { + @EventHandler + public void onQuestReward(QuestRewardEvent event) { + if (event.getQuest() instanceof CustomQuest) { + CustomQuest customQuest = (CustomQuest) event.getQuest(); + CustomQuestsConfigFields customQuestsConfigFields = customQuest.getCustomQuestsConfigFields(); + customQuest.applyEndPermissions(event.getPlayer()); + if (!customQuest.getCustomQuestsConfigFields().getQuestCompleteDialog().isEmpty()) + for (String dialog : customQuest.getCustomQuestsConfigFields().getQuestCompleteDialog()) + event.getPlayer().sendMessage(dialog); + for (String command : customQuestsConfigFields.getQuestCompleteCommands()) + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), + command.replace("$player", event.getPlayer().getName()) + .replace("$getX", event.getPlayer().getLocation().getX() + "") + .replace("$getY", event.getPlayer().getLocation().getY() + "") + .replace("$getZ", event.getPlayer().getLocation().getZ() + "")); + } + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/quests/DynamicQuest.java b/src/main/java/com/magmaguy/elitemobs/quests/DynamicQuest.java new file mode 100644 index 000000000..dba64236e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/quests/DynamicQuest.java @@ -0,0 +1,72 @@ +package com.magmaguy.elitemobs.quests; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.adventurersguild.GuildRank; +import com.magmaguy.elitemobs.config.menus.premade.DynamicQuestMenuConfig; +import com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs.EliteMobProperties; +import com.magmaguy.elitemobs.playerdata.database.PlayerData; +import com.magmaguy.elitemobs.quests.objectives.DynamicKillObjective; +import com.magmaguy.elitemobs.quests.objectives.QuestObjectives; +import com.magmaguy.elitemobs.quests.rewards.QuestReward; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.UUID; + +public class DynamicQuest extends Quest { + + private static HashMap> dynamicPlayerQuests = new HashMap<>(); + + public DynamicQuest(Player player, int questLevel, QuestObjectives questObjectives) { + super(player, questObjectives, questLevel); + super.questName = DynamicQuestMenuConfig.getQuestName() + .replace("$amount", questObjectives.getObjectives().get(0).getTargetAmount() + "") + .replace("$name", ChatColor.stripColor(EliteMobProperties.getPluginData(((DynamicKillObjective) questObjectives.getObjectives().get(0)).getEntityType()).getName(questLevel * 10))); + questObjectives.setQuest(this); + } + + public static List generateQuests(Player player) { + List dynamicQuests = new ArrayList<>(); + for (int i = 0; i < 3; i++) { + int questLevel = GuildRank.getActiveGuildRank(player); + QuestObjectives questObjectives = new QuestObjectives(questLevel); + QuestReward questReward = new QuestReward(questLevel, questObjectives, player); + questObjectives.setQuestReward(questReward); + dynamicQuests.add(new DynamicQuest(player, questLevel, questObjectives)); + } + dynamicPlayerQuests.put(player.getUniqueId(), dynamicQuests); + new BukkitRunnable() { + @Override + public void run() { + if (!player.isOnline()) { + dynamicPlayerQuests.remove(player.getUniqueId()); + cancel(); + return; + } + generateQuests(player); + } + }.runTaskLater(MetadataHandler.PLUGIN, 20L * 60 * 60); + return dynamicQuests; + } + + public static List getQuests(Player player) { + List dynamicQuests = new ArrayList<>(); + + if (PlayerData.getQuests(player.getUniqueId()) instanceof DynamicQuest) + dynamicQuests.add((DynamicQuest) PlayerData.getQuests(player.getUniqueId())); + + if (dynamicPlayerQuests.get(player.getUniqueId()) == null) + dynamicQuests.addAll(generateQuests(player)); + else + for (DynamicQuest dynamicQuest : dynamicPlayerQuests.get(player.getUniqueId())) + if (!(!dynamicQuests.isEmpty() && dynamicQuests.get(0).getQuestID().equals(dynamicQuest.getQuestID()))) + dynamicQuests.add(dynamicQuest); + + return dynamicQuests; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/quests/DynamicQuestInteractionHandler.java b/src/main/java/com/magmaguy/elitemobs/quests/DynamicQuestInteractionHandler.java new file mode 100644 index 000000000..4143724fb --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/quests/DynamicQuestInteractionHandler.java @@ -0,0 +1,8 @@ +package com.magmaguy.elitemobs.quests; + +public class DynamicQuestInteractionHandler { + private DynamicQuestInteractionHandler() { + } + + +} diff --git a/src/main/java/com/magmaguy/elitemobs/quests/Quest.java b/src/main/java/com/magmaguy/elitemobs/quests/Quest.java new file mode 100644 index 000000000..fac6a0813 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/quests/Quest.java @@ -0,0 +1,87 @@ +package com.magmaguy.elitemobs.quests; + +import com.magmaguy.elitemobs.api.QuestCompleteEvent; +import com.magmaguy.elitemobs.api.QuestLeaveEvent; +import com.magmaguy.elitemobs.config.QuestsConfig; +import com.magmaguy.elitemobs.playerdata.database.PlayerData; +import com.magmaguy.elitemobs.quests.objectives.QuestObjectives; +import com.magmaguy.elitemobs.utils.EventCaller; +import lombok.Getter; +import lombok.Setter; +import org.bukkit.entity.Player; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.UUID; + +public class Quest implements Serializable { + + @Getter + //Player UUID as key + //protected static final HashMap playerQuests = new HashMap<>(); + //Temporarily stores a list of quests a player might be considering joining + protected static final HashMap> pendingPlayerQuests = new HashMap<>(); + @Getter + protected final QuestObjectives questObjectives; + @Getter + private final UUID questID = UUID.randomUUID(); + @Getter + protected String questName; + @Getter + @Setter + //NPC the quest originates from + protected String questGiver = ""; + @Setter + //NPC the quest is turned in to + protected String questTaker = ""; + @Getter + @Setter + private UUID playerUUID; + @Getter + @Setter + private int questLevel; + @Getter + @Setter + private boolean accepted = false; + + public Quest(Player player, QuestObjectives questObjectives, int questLevel) { + this.playerUUID = player.getUniqueId(); + this.questObjectives = questObjectives; + this.questLevel = questLevel; + if (pendingPlayerQuests.get(playerUUID) == null) { + List quests = new ArrayList<>(); + quests.add(this); + pendingPlayerQuests.put(playerUUID, quests); + } else { + List quests = pendingPlayerQuests.get(playerUUID); + quests.add(this); + pendingPlayerQuests.put(playerUUID, quests); + } + } + + public static void stopPlayerQuest(Player player, String questID) { + if (PlayerData.getQuests(player.getUniqueId()) == null) { + player.sendMessage(QuestsConfig.getLeaveWhenNoActiveQuestsExist()); + return; + } + QuestLeaveEvent questLeaveEvent = new QuestLeaveEvent(player, PlayerData.getQuest(player.getUniqueId(), questID)); + new EventCaller(questLeaveEvent); + } + + public static Quest completeQuest(UUID questUUID, Player player) { + Quest quest = PlayerData.getQuest(player.getUniqueId(), questUUID); + if (quest == null) return null; + if (!quest.getQuestID().equals(questUUID)) return null; + if (!quest.getQuestObjectives().isOver()) return null; + QuestCompleteEvent questCompleteEvent = new QuestCompleteEvent(player, quest); + new EventCaller(questCompleteEvent); + return quest; + } + + public String getQuestTaker() { + return questTaker.isEmpty() ? questGiver : questTaker; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/quests/QuestInteractionHandler.java b/src/main/java/com/magmaguy/elitemobs/quests/QuestInteractionHandler.java new file mode 100644 index 000000000..d24dabeb0 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/quests/QuestInteractionHandler.java @@ -0,0 +1,91 @@ +package com.magmaguy.elitemobs.quests; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.config.QuestsConfig; +import com.magmaguy.elitemobs.npcs.NPCEntity; +import com.magmaguy.elitemobs.playerdata.database.PlayerData; +import com.magmaguy.elitemobs.quests.menus.QuestMenu; +import com.magmaguy.elitemobs.quests.objectives.CustomFetchObjective; +import com.magmaguy.elitemobs.quests.objectives.Objective; +import com.magmaguy.elitemobs.utils.WarningMessage; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +import java.util.ArrayList; +import java.util.List; + +public class QuestInteractionHandler { + private QuestInteractionHandler() { + } + + public static void processDynamicQuests(Player player, NPCEntity npcEntity) { + List dynamicQuests = new ArrayList<>(); + DynamicQuest.getQuests(player).forEach(quest -> { + if (!quest.getQuestObjectives().isTurnedIn()) dynamicQuests.add(quest); + }); + if (PlayerData.getQuests(player.getUniqueId()) != null) + for (Quest quest : PlayerData.getQuests(player.getUniqueId())) + if (quest instanceof DynamicQuest && !dynamicQuests.contains(quest)) + dynamicQuests.add((DynamicQuest) quest); + QuestMenu.generateDynamicQuestMenu(dynamicQuests, player, npcEntity); + } + + public static void processNPCQuests(Player player, NPCEntity npcEntity) { + List customQuestList = new ArrayList<>(); + + List quests = PlayerData.getQuests(player.getUniqueId()); + scanQuestTakerNPC(npcEntity, quests, customQuestList); + + boolean anyQuestIsValid = false; + int questCompleteCount = 0; + //This value can be null for NPC entities that have the custom quest interaction but are only used to turn quests in + if (npcEntity.getNPCsConfigFields().getQuestFilenames() != null) + for (String questString : npcEntity.getNPCsConfigFields().getQuestFilenames()) { + CustomQuest customQuest = CustomQuest.getQuest(questString, player); + if (customQuest == null) { + player.sendMessage("[EliteMobs] This NPC's quest is not valid! This might be a configuration error on the NPC or on the quest."); + if (player.hasPermission("elitemobs.*")) + player.sendMessage("Invalid quest: " + questString); + continue; + } + + if (customQuest.hasPermissionForQuest(player)) { + customQuestList.add(customQuest); + customQuest.setQuestGiver(npcEntity.getNPCsConfigFields().getFilename()); + anyQuestIsValid = true; + } else if (!customQuest.getCustomQuestsConfigFields().getQuestLockoutPermission().isEmpty() && + player.hasMetadata(customQuest.getCustomQuestsConfigFields().getQuestLockoutPermission())) + questCompleteCount++; + } + + if (npcEntity.getNPCsConfigFields().getQuestFilenames() == null){ + new WarningMessage("NPC" + npcEntity.getNPCsConfigFields().getFilename() + " is listed a quest NPC but has no valid quest filenames associated to it! Check if the quests are valid and if the filenames in the NPC's config are typed correctly!"); + } + + if (questCompleteCount == npcEntity.getNPCsConfigFields().getQuestFilenames().size()) + player.sendMessage(QuestsConfig.getQuestAlreadyCompletedMessage()); + else if (!anyQuestIsValid) + player.sendMessage(QuestsConfig.getQuestPrerequisitesMissingMessage()); + + if (!customQuestList.isEmpty()) + new BukkitRunnable() { + @Override + public void run() { + QuestMenu.generateCustomQuestMenu(customQuestList, player, npcEntity); + } + }.runTaskLater(MetadataHandler.PLUGIN, 1); + } + + private static void scanQuestTakerNPC(NPCEntity npcEntity, List activeQuests, List npcQuests) { + for (Quest quest : activeQuests) + if (quest instanceof CustomQuest && + !quest.getQuestTaker().equals(quest.getQuestGiver()) && + npcEntity.getNPCsConfigFields().getFilename().equals(quest.getQuestTaker())) { + npcQuests.add((CustomQuest) quest); + for (Objective objective : quest.getQuestObjectives().getObjectives()) + if (objective instanceof CustomFetchObjective) + objective.progressNonlinearObjective(quest.getQuestObjectives()); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/quests/QuestTracking.java b/src/main/java/com/magmaguy/elitemobs/quests/QuestTracking.java new file mode 100644 index 000000000..c7d43cc09 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/quests/QuestTracking.java @@ -0,0 +1,390 @@ +package com.magmaguy.elitemobs.quests; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.QuestAcceptEvent; +import com.magmaguy.elitemobs.api.QuestCompleteEvent; +import com.magmaguy.elitemobs.api.QuestProgressionEvent; +import com.magmaguy.elitemobs.config.QuestsConfig; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.items.customloottable.CustomLootEntry; +import com.magmaguy.elitemobs.items.customloottable.EliteCustomLootEntry; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import com.magmaguy.elitemobs.playerdata.database.PlayerData; +import com.magmaguy.elitemobs.quests.objectives.*; +import com.magmaguy.elitemobs.treasurechest.TreasureChest; +import com.magmaguy.elitemobs.utils.SpigotMessage; +import com.magmaguy.elitemobs.wormhole.Wormhole; +import lombok.Getter; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; +import org.bukkit.boss.BarColor; +import org.bukkit.boss.BarFlag; +import org.bukkit.boss.BarStyle; +import org.bukkit.boss.BossBar; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerQuitEvent; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scheduler.BukkitTask; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class QuestTracking { + + @Getter + private static final HashMap playerTrackingQuests = new HashMap<>(); + private final Player player; + @Getter + private final CustomQuest customQuest; + private List turnInNPCs = new ArrayList<>(); + private List objectiveDestinations = new ArrayList<>(); + private BukkitTask locationRefresher; + private BukkitTask compassTask; + private BossBar compassBar; + private boolean questIsDone = false; + + public QuestTracking(Player player, CustomQuest customQuest) { + this.player = player; + this.customQuest = customQuest; + startLocationGetter(); + startCompass(); + playerTrackingQuests.put(player, this); + customQuest.getQuestObjectives().displayLazyObjectivesScoreboard(player); + } + + public static boolean isTracking(Player player) { + return playerTrackingQuests.containsKey(player); + } + + public static void clear() { + ((HashMap) playerTrackingQuests.clone()).values().forEach(QuestTracking::stop); + } + + public static void toggleTracking(Player player, String questID) { + CustomQuest customQuest = (CustomQuest) PlayerData.getQuest(player.getUniqueId(), questID); + if (customQuest == null) { + player.sendMessage("[EliteMobs] Failed to get a valid quest with that quest ID!"); + return; + } + toggleTracking(player, customQuest); + } + + public static void toggleTracking(Player player, CustomQuest quest) { + if (playerTrackingQuests.containsKey(player)) + playerTrackingQuests.get(player).stop(); + else { + if (quest == null) { + player.sendMessage("[EliteMobs] Failed to get a valid quest with that quest ID!"); + return; + } + if (!quest.getCustomQuestsConfigFields().isTrackable()) return; + new QuestTracking(player, quest); + } + } + + public void refreshScoreboard() { + customQuest.getQuestObjectives().displayLazyObjectivesScoreboard(player); + } + + private void startLocationGetter() { + locationRefresher = new BukkitRunnable() { + @Override + public void run() { + if (!player.isValid()) { + stop(); + return; + } + updateLocations(customQuest); + } + }.runTaskTimerAsynchronously(MetadataHandler.PLUGIN, 0L, 20L * 60L); + } + + public void updateLocations(Quest quest) { + List destinations = new ArrayList<>(); + if (!quest.getQuestObjectives().isOver()) { + questIsDone = false; + for (Objective objective : quest.getQuestObjectives().getObjectives()) + if (!objective.isObjectiveCompleted()) + if (objective instanceof CustomKillObjective) + destinations.addAll(getKillLocations((CustomKillObjective) objective)); + else if (objective instanceof DialogObjective) + destinations.addAll(getDialogLocations((DialogObjective) objective)); + else if (objective instanceof CustomFetchObjective) + destinations.addAll(getFetchLocations((CustomFetchObjective) objective)); + Bukkit.getScheduler().runTask(MetadataHandler.PLUGIN, () -> objectiveDestinations = destinations); + } else { + questIsDone = true; + getTurnInNPC(); + } + } + + private List getKillLocations(CustomKillObjective customKillObjective) { + List destinations = new ArrayList<>(); + List locations = new ArrayList<>(); + EntityTracker.getEliteMobEntities().values().forEach(eliteEntity -> { + if (eliteEntity instanceof CustomBossEntity) + if (((CustomBossEntity) eliteEntity).getPhaseBossEntity() != null && + ((CustomBossEntity) eliteEntity).getPhaseBossEntity().getPhase1Config().getFilename().equals(customKillObjective.getCustomBossFilename())) { + locations.add(eliteEntity.getLocation()); + } else if (((CustomBossEntity) eliteEntity).getCustomBossesConfigFields().getFilename() + .equals(customKillObjective.getCustomBossFilename())) { + locations.add(eliteEntity.getLocation()); + } + }); + destinations.add(new ObjectiveDestinations(customKillObjective, locations)); + return destinations; + } + + private List getDialogLocations(DialogObjective dialogObjective) { + List destinations = new ArrayList<>(); + EntityTracker.getNpcEntities().values().forEach(npcEntity -> { + List locations = new ArrayList<>(); + if (npcEntity.getNPCsConfigFields().getFilename().equals(dialogObjective.getNpcFilename())) + locations.add(npcEntity.getSpawnLocation()); + destinations.add(new ObjectiveDestinations(dialogObjective, locations)); + }); + return destinations; + } + + private List getFetchLocations(CustomFetchObjective customFetchObjective) { + List destinations = new ArrayList<>(); + List locations = new ArrayList<>(); + EntityTracker.getEliteMobEntities().values().forEach(eliteEntity -> { + if (eliteEntity instanceof CustomBossEntity) + for (CustomLootEntry customLootEntry : ((CustomBossEntity) eliteEntity).getCustomBossesConfigFields().getCustomLootTable().getEntries()) + if (customLootEntry instanceof EliteCustomLootEntry && ((EliteCustomLootEntry) customLootEntry).getFilename().equals(customFetchObjective.getKey())) + locations.add(eliteEntity.getLocation()); + }); + TreasureChest.getTreasureChestHashMap().values().forEach((treasureChest -> { + for (CustomLootEntry customLootEntry : treasureChest.getCustomTreasureChestConfigFields().getCustomLootTable().getEntries()) + if (customLootEntry instanceof EliteCustomLootEntry && ((EliteCustomLootEntry) customLootEntry).getFilename().equals(customFetchObjective.getKey())) + locations.add(treasureChest.getLocation()); + })); + destinations.add(new ObjectiveDestinations(customFetchObjective, locations)); + return destinations; + } + + private void getTurnInNPC() { + EntityTracker.getNpcEntities().values().forEach(npcEntity -> { + if (npcEntity.getNPCsConfigFields().getFilename().equals(customQuest.getQuestTaker())) + turnInNPCs.add(npcEntity.getSpawnLocation()); + }); + } + + public void stop() { + playerTrackingQuests.remove(player); + player.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); + locationRefresher.cancel(); + compassTask.cancel(); + compassBar.removeAll(); + } + + private void startCompass() { + compassBar = Bukkit.createBossBar("", BarColor.GREEN, BarStyle.SOLID, BarFlag.PLAY_BOSS_MUSIC); + compassTask = new BukkitRunnable() { + @Override + public void run() { + if (!player.isValid()) { + stop(); + return; + } + updateCompassContents(); + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0L, 10L); + } + + private void updateCompassContents() { + //for reference, character 32 is straight ahead + String compassText = "---------------------------------------------------------------"; + List locationAndSymbols = projectLocations(); + if (!locationAndSymbols.isEmpty()) + for (LocationAndSymbol pair : locationAndSymbols) + compassText = compassText.substring(0, pair.getKey()) + pair.getValue() + compassText.substring(pair.getKey() + 1); + else { + World world = null; + boolean locationsOutOfBounds = false; + for (ObjectiveDestinations destinations : objectiveDestinations) + for (Location location : destinations.getDestinations()) + if (location != null && location.getWorld() != null) { + world = location.getWorld(); + if (world.equals(player.getWorld())) { + locationsOutOfBounds = true; + break; + } + } + + if (!locationsOutOfBounds) { + if (world != null) { + boolean wormholeIsViable = false; + for (Wormhole wormhole : Wormhole.getWormholes()) { + if (wormhole.getWormholeEntry1().getLocation() != null && + wormhole.getWormholeEntry1().getLocation().getWorld() != null && + wormhole.getWormholeEntry1().getLocation().getWorld().equals(player.getWorld())) { + if (wormhole.getWormholeEntry2().getLocation() != null && + wormhole.getWormholeEntry2().getLocation().getWorld() != null && + wormhole.getWormholeEntry2().getLocation().getWorld().equals(world)) { + LocationAndSymbol pair = processLocations(wormhole.getWormholeEntry1().getLocation(), null); + if (pair != null) + compassText = compassText.substring(0, pair.getKey()) + pair.getValue() + compassText.substring(pair.getKey() + 1); + wormholeIsViable = true; + } + + } else if (wormhole.getWormholeEntry2().getLocation() != null && + wormhole.getWormholeEntry2().getLocation().getWorld() != null && + wormhole.getWormholeEntry2().getLocation().getWorld().equals(player.getWorld())) { + if (wormhole.getWormholeEntry1().getLocation() != null && + wormhole.getWormholeEntry1().getLocation().getWorld() != null && + wormhole.getWormholeEntry1().getLocation().getWorld().equals(world)) { + LocationAndSymbol pair = processLocations(wormhole.getWormholeEntry2().getLocation(), null); + if (pair != null) + compassText = compassText.substring(0, pair.getKey()) + pair.getValue() + compassText.substring(pair.getKey() + 1); + wormholeIsViable = true; + } + } + } + if (!wormholeIsViable) + compassText = QuestsConfig.getQuestDestinationInOtherWorld().replace("$world", world.getName()); + } else + compassText = QuestsConfig.getNoQuestDestinationFound(); + } + } + + compassBar.setTitle(compassText); + compassBar.addPlayer(player); + } + + private List projectLocations() { + List parsedVectors = new ArrayList<>(); + if (questIsDone) { + for (Location location : new ArrayList<>(turnInNPCs)) { + LocationAndSymbol locationAndSymbol = processLocations(location, null); + if (locationAndSymbol != null) parsedVectors.add(locationAndSymbol); + } + } else + for (ObjectiveDestinations iteratedObjectiveDestinations : new ArrayList<>(objectiveDestinations)) + for (Location location : iteratedObjectiveDestinations.getDestinations()) { + LocationAndSymbol locationAndSymbol = processLocations(location, iteratedObjectiveDestinations.getObjective()); + if (locationAndSymbol != null) parsedVectors.add(locationAndSymbol); + } + return parsedVectors; + } + + private LocationAndSymbol processLocations(Location location, Objective objective) { + if (player.getWorld().equals(location.getWorld())) { + Vector toTarget = toTargetVector(player, location); + double angle = getAngle(toTarget, player); + if (Math.abs(angle) > Math.PI / 2D) return null; + //Convert to degrees, each character has a resolution of 3 degrees + return new LocationAndSymbol((int) (angle * 57D / 3D), getSymbol(objective)); + } + return null; + } + + private Vector toTargetVector(Player player, Location location) { + return location.clone().add(new Vector(0, 1.85, 0)).subtract(player.getEyeLocation()).toVector().normalize(); + } + + private double getAngle(Vector toTarget, Player player) { + double angle = player.getEyeLocation().getDirection().setY(0).angle(toTarget.clone().setY(0)); + if (toTarget.getX() * player.getEyeLocation().getDirection().getZ() - toTarget.getZ() * player.getEyeLocation().getDirection().getX() > 0) + angle *= -1; + return angle; + } + + private String getSymbol(Objective objective) { + //case for portals + if (objective == null) return "⬯"; + + if (questIsDone) + return "⦿"; + if (objective instanceof KillObjective) + return "☠"; + else if (objective instanceof DialogObjective) + return "⦿"; + else if (objective instanceof CustomFetchObjective) + return "⚔"; + return "⦿"; + } + + public static class QuestTrackingEvents implements Listener { + @EventHandler + public void onPlayerLogout(PlayerQuitEvent event) { + QuestTracking questTracking = getPlayerTrackingQuests().get(event.getPlayer()); + if (questTracking == null) return; + questTracking.stop(); + } + + @EventHandler(ignoreCancelled = true) + public void onQuestProgressEvent(QuestProgressionEvent event) { + if (!event.getObjective().isObjectiveCompleted()) return; + if (!isTracking(event.getPlayer())) return; + if (!getPlayerTrackingQuests().get(event.getPlayer()).getCustomQuest().getQuestID().equals(event.getQuest().getQuestID())) + return; + getPlayerTrackingQuests().get(event.getPlayer()) + .updateLocations(getPlayerTrackingQuests().get(event.getPlayer()).getCustomQuest()); + getPlayerTrackingQuests().get(event.getPlayer()).refreshScoreboard(); + } + + @EventHandler(ignoreCancelled = true) + public void onQuestCompleteEvent(QuestCompleteEvent event) { + if (!isTracking(event.getPlayer())) return; + if (!getPlayerTrackingQuests().get(event.getPlayer()).getCustomQuest().getQuestID().equals(event.getQuest().getQuestID())) + return; + getPlayerTrackingQuests().get(event.getPlayer()).stop(); + } + + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH) + public void onQuestAcceptEvent(QuestAcceptEvent event) { + if (!(event.getQuest() instanceof CustomQuest)) return; + if (!((CustomQuest) event.getQuest()).getCustomQuestsConfigFields().isTrackable()) return; + if (QuestsConfig.isAutoTrackQuestsOnAccept()) { + toggleTracking(event.getPlayer(), (CustomQuest) event.getQuest()); + event.getPlayer().spigot().sendMessage(SpigotMessage.commandHoverMessage( + ChatColorConverter.convert(QuestsConfig.getChatTrackingMessage()), + ChatColorConverter.convert(QuestsConfig.getChatTrackingHover()), + QuestsConfig.getChatTrackingCommand().replace("$questID", event.getQuest().getQuestID().toString()) + )); + } else + event.getPlayer().spigot().sendMessage(SpigotMessage.commandHoverMessage( + ChatColorConverter.convert(QuestsConfig.getChatTrackMessage()), + ChatColorConverter.convert(QuestsConfig.getChatTrackHover()), + QuestsConfig.getChatTrackCommand().replace("$questID", event.getQuest().getQuestID().toString()) + )); + } + + } + + private class ObjectiveDestinations { + @Getter + private final Objective objective; + @Getter + private final List destinations; + + private ObjectiveDestinations(Objective objective, List destinations) { + this.objective = objective; + this.destinations = destinations; + objectiveDestinations.add(this); + } + } + + private class LocationAndSymbol { + @Getter + private final int key; + @Getter + private final String value; + + private LocationAndSymbol(int key, String value) { + //adjust the key to the center of the compass display + this.key = key + 31; + this.value = value; + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/quests/menus/QuestBookMenu.java b/src/main/java/com/magmaguy/elitemobs/quests/menus/QuestBookMenu.java new file mode 100644 index 000000000..610e652e1 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/quests/menus/QuestBookMenu.java @@ -0,0 +1,67 @@ +package com.magmaguy.elitemobs.quests.menus; + +import com.magmaguy.elitemobs.config.DefaultConfig; +import com.magmaguy.elitemobs.npcs.NPCEntity; +import com.magmaguy.elitemobs.quests.CustomQuest; +import com.magmaguy.elitemobs.quests.Quest; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; + +public class QuestBookMenu { + private QuestBookMenu() { + } + + //NPC entity is null when the entry is generated based on a command and not a npc interaction + public static TextComponent[] generateQuestEntry(Quest quest, Player player, NPCEntity npcEntity) { + QuestMenu.QuestText questText = new QuestMenu.QuestText(quest, npcEntity, player); + + //Condense all page elements + List elements = new ArrayList<>(); + elements.add(questText.getHeader()); + if (quest instanceof CustomQuest && !quest.getQuestObjectives().isOver()) + elements.addAll(questText.getBody()); + elements.add(questText.getFixedSummary()); + elements.addAll(questText.getSummary()); + elements.add(questText.getFixedRewards()); + elements.addAll(questText.getRewards()); + elements.add(questText.getAccept()); + if (quest instanceof CustomQuest) + elements.add(questText.getTrack()); + + //Arrange them into pages, taking character count into account + List pagesList = new ArrayList<>(); + int pageIndex = 0; + int characterCount = 0; + int characterLimit = DefaultConfig.getCharacterLimitForBookMenuPages(); + for (TextComponent textComponent : elements) { + characterCount += ChatColor.stripColor(textComponent.getText()).length(); + if (pagesList.isEmpty()) { + textComponent.addExtra("\n"); + pagesList.add(textComponent); + } else if (characterCount > characterLimit) { + characterCount = 0; + characterCount += ChatColor.stripColor(textComponent.getText()).length(); + pageIndex++; + textComponent.addExtra("\n"); + pagesList.add(textComponent); + } else { + textComponent.addExtra("\n"); + pagesList.get(pageIndex).addExtra(textComponent); + } + } + + TextComponent[] pages = new TextComponent[pagesList.size()]; + + int pageCounter = 0; + for (TextComponent textComponent : pagesList) { + pages[pageCounter] = textComponent; + pageCounter++; + } + + return pages; + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/quests/menus/QuestInventoryMenu.java b/src/main/java/com/magmaguy/elitemobs/quests/menus/QuestInventoryMenu.java new file mode 100644 index 000000000..a398db53e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/quests/menus/QuestInventoryMenu.java @@ -0,0 +1,235 @@ +package com.magmaguy.elitemobs.quests.menus; + +import com.magmaguy.elitemobs.commands.quests.QuestCommand; +import com.magmaguy.elitemobs.npcs.NPCEntity; +import com.magmaguy.elitemobs.quests.CustomQuest; +import com.magmaguy.elitemobs.quests.Quest; +import com.magmaguy.elitemobs.utils.ItemStackGenerator; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.inventory.InventoryClickEvent; +import org.bukkit.event.inventory.InventoryCloseEvent; +import org.bukkit.inventory.Inventory; +import org.bukkit.inventory.ItemStack; + +import java.util.*; +import java.util.concurrent.atomic.AtomicInteger; + +public class QuestInventoryMenu { + private static final int trackEntry = 8; + private static final int acceptEntry = 26; + private static HashMap questDirectories = new HashMap<>(); + private static HashMap questInventories = new HashMap<>(); + + private QuestInventoryMenu() { + } + + public static void generateInventoryQuestEntries(List quests, Player player, NPCEntity npcEntity) { + if (quests.size() == 1) + QuestInventoryMenu.generateInventoryQuestEntry(quests.get(0), player, npcEntity); + else + QuestInventoryMenu.generateInventoryQuestDirectory(quests, player, npcEntity); + } + + public static void generateInventoryQuestDirectory(List quests, Player player, NPCEntity npcEntity) { + String menuTitle = "Quests"; + Inventory questInventory = Bukkit.createInventory(player, 27, menuTitle); + List questSlots = new ArrayList<>(Arrays.asList(13, 11, 15, 9, 17, 10, 16, 12, 14)); + Material acceptMaterial = Material.GREEN_STAINED_GLASS_PANE; + Material inProgressMaterial = Material.RED_STAINED_GLASS_PANE; + Material completeMaterial = Material.ORANGE_STAINED_GLASS_PANE; + HashMap questMap = new HashMap<>(); + for (int i = 0; i < quests.size(); i++) { + questMap.put(questSlots.get(i), quests.get(i)); + QuestMenu.QuestText questText = new QuestMenu.QuestText(quests.get(i), npcEntity, player); + if (!quests.get(i).isAccepted()) + questInventory.setItem(questSlots.get(i), ItemStackGenerator.generateItemStack(acceptMaterial, questText.getHeader().getText())); + else if (!quests.get(i).getQuestObjectives().isOver()) + questInventory.setItem(questSlots.get(i), ItemStackGenerator.generateItemStack(inProgressMaterial, questText.getHeader().getText())); + else + questInventory.setItem(questSlots.get(i), ItemStackGenerator.generateItemStack(completeMaterial, questText.getHeader().getText())); + } + + new QuestDirectory(player, questMap, questInventory, npcEntity); + player.openInventory(questInventory); + } + + public static void generateInventoryQuestEntry(Quest quest, Player player, NPCEntity npcEntity) { + QuestMenu.QuestText questText = new QuestMenu.QuestText(quest, npcEntity, player); + String title = ""; + if (questText.getHeader().getText() != null) + title = questText.getHeader().getText(); + Inventory questInventory = Bukkit.createInventory(player, 27, title); + int titleEntry = 4; + List loreEntries = new ArrayList<>(Arrays.asList(13, 14, 12, 15, 11, 16, 10, 17, 9)); + List objectivesEntries = new ArrayList<>(Arrays.asList(21, 20, 19, 18)); + List rewardEntries = new ArrayList<>(Arrays.asList(23, 24, 25)); + + Material titleMaterial = Material.PAINTING; + Material trackingMaterial = Material.TARGET; + Material loreMaterial = Material.BOOK; + Material objectivesMaterial = Material.ITEM_FRAME; + Material rewardsMaterial = Material.GOLD_INGOT; + Material acceptMaterial = Material.EMERALD; + + questInventory.setItem(titleEntry, generateItemStackEntry(questText.getHeader(), new TextComponent(), titleMaterial).get(0)); + if (quest instanceof CustomQuest && quest.isAccepted()) + questInventory.setItem(trackEntry, generateItemStackEntry(questText.getTrack(), new TextComponent(), trackingMaterial).get(0)); + questInventory.setItem(acceptEntry, generateItemStackEntry(questText.getAccept(), new TextComponent(), acceptMaterial).get(0)); + if (quest instanceof CustomQuest) + fillItemSlotLists(questInventory, loreEntries, new TextComponent(" "), questText.getBody(), loreMaterial); + fillItemSlotLists(questInventory, objectivesEntries, questText.getFixedSummary(), questText.getSummary(), objectivesMaterial); + fillItemSlotLists(questInventory, rewardEntries, questText.getFixedRewards(), questText.getRewards(), rewardsMaterial); + + new QuestInventory(player, quest, questInventory, npcEntity); + player.openInventory(questInventory); + } + + public static void fillItemSlotLists(Inventory inventory, List entries, TextComponent title, List textComponents, Material material) { + List loreItems = generateItemStackEntry(title, textComponents, material); + for (int i = 0; i < loreItems.size(); i++) + inventory.setItem(entries.get(i), loreItems.get(i)); + } + + public static List generateItemStackEntry(TextComponent title, List textComponents, Material material) { + List list = new ArrayList<>(); + textComponents.forEach(component -> list.add(component.getText())); + return generateParsedItemStackEntry(title.getText(), list, material); + } + + public static List generateItemStackEntry(TextComponent title, TextComponent textComponent, Material material) { + return generateParsedItemStackEntry(title.getText(), Collections.singletonList(textComponent.getText()), material); + } + + public static List generateParsedItemStackEntry(String title, List rawLore, Material material) { + title = title.replace(ChatColor.BLACK.toString(), ChatColor.WHITE.toString()); + List lore = new ArrayList<>(); + rawLore.forEach(raw -> lore.add(ChatColor.WHITE + raw.replace(ChatColor.BLACK.toString(), ChatColor.WHITE.toString()))); + int characterLimit = 300; + List itemStacks = new ArrayList<>(); + AtomicInteger counter = new AtomicInteger(); + lore.forEach(entry -> counter.addAndGet(entry.length())); + if (counter.get() < characterLimit) { + itemStacks.add(ItemStackGenerator.generateItemStack(material, title, lore)); + return itemStacks; + } + + int maxCharactersPerLine = 30; + List currentList = new ArrayList<>(); + int currentCharacterCount = 0; + for (String entry : lore) { + entry = entry.replace(ChatColor.BLACK.toString(), ChatColor.WHITE.toString()); + if (!currentList.isEmpty() && entry.length() + currentCharacterCount > characterLimit) { + itemStacks.add(ItemStackGenerator.generateItemStack(material, title, currentList)); + currentList.clear(); + currentCharacterCount = 0; + } + if (entry.length() > maxCharactersPerLine) { + int size = 30; + //for languages that have no spaces + if (!entry.contains(" ")) { + List substrings = new ArrayList<>((entry.length() + size - 1) / size); + for (int start = 0; start < entry.length(); start += size) + substrings.add(ChatColor.WHITE.toString() + entry.substring(start, Math.min(entry.length(), start + size))); + currentList.addAll(substrings); + //for other languages + } else { + String[] splitBySpaces = entry.split(" "); + List substrings = new ArrayList<>(); + StringBuilder currentString = new StringBuilder(); + currentString.append(ChatColor.WHITE.toString()); + for (String string : splitBySpaces) { + string += " "; + if (currentString.length() + string.length() > size) { + substrings.add(currentString.toString()); + currentString = new StringBuilder(); + currentString.append(ChatColor.WHITE.toString()); + } + currentString.append(string); + } + substrings.add(currentString.toString()); + currentList.addAll(substrings); + } + } else + currentList.add(entry); + currentCharacterCount += entry.length(); + } + itemStacks.add(ItemStackGenerator.generateItemStack(material, title, currentList)); + return itemStacks; + } + + private static class QuestDirectory { + HashMap questMap; + Inventory inventory; + NPCEntity npcEntity; + Player player; + + private QuestDirectory(Player player, HashMap questMap, Inventory inventory, NPCEntity npcEntity) { + this.questMap = questMap; + this.inventory = inventory; + this.npcEntity = npcEntity; + this.player = player; + questDirectories.put(player, this); + } + } + + private static class QuestInventory { + Quest quest; + Inventory inventory; + NPCEntity npcEntity; + Player player; + + private QuestInventory(Player player, Quest quest, Inventory inventory, NPCEntity npcEntity) { + this.quest = quest; + this.inventory = inventory; + this.npcEntity = npcEntity; + this.player = player; + questInventories.put(player, this); + } + } + + public static class QuestInventoryMenuEvents implements Listener { + @EventHandler + public void onInventoryInteract(InventoryClickEvent event) { + Player player = ((Player) event.getWhoClicked()).getPlayer(); + if (questDirectories.containsKey(player)) { + event.setCancelled(true); + QuestDirectory questDirectory = questDirectories.get(player); + if (questDirectory.questMap.get(event.getSlot()) == null) return; + player.closeInventory(); + generateInventoryQuestEntry(questDirectory.questMap.get(event.getSlot()), questDirectory.player, questDirectory.npcEntity); + } else if (questInventories.containsKey(player)) { + event.setCancelled(true); + switch (event.getSlot()) { + case trackEntry: + QuestCommand.trackQuest(questInventories.get(player).quest.getQuestID().toString(), player); + player.closeInventory(); + break; + case acceptEntry: + Quest quest = questInventories.get(player).quest; + if (!quest.isAccepted()) + QuestCommand.joinQuest(quest.getQuestID().toString(), player); + else if (!quest.getQuestObjectives().isOver()) + QuestCommand.leaveQuest(player, quest.getQuestID().toString()); + else + QuestCommand.completeQuest(quest.getQuestID().toString(), player); + + player.closeInventory(); + break; + } + } + } + + @EventHandler + public void onInventoryClose(InventoryCloseEvent event) { + questInventories.remove(event.getPlayer()); + questDirectories.remove(event.getPlayer()); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/quests/menus/QuestMenu.java b/src/main/java/com/magmaguy/elitemobs/quests/menus/QuestMenu.java new file mode 100644 index 000000000..897ad1354 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/quests/menus/QuestMenu.java @@ -0,0 +1,241 @@ +package com.magmaguy.elitemobs.quests.menus; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.config.DefaultConfig; +import com.magmaguy.elitemobs.config.menus.premade.CustomQuestMenuConfig; +import com.magmaguy.elitemobs.config.menus.premade.DynamicQuestMenuConfig; +import com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs.EliteMobProperties; +import com.magmaguy.elitemobs.npcs.NPCEntity; +import com.magmaguy.elitemobs.playerdata.database.PlayerData; +import com.magmaguy.elitemobs.quests.CustomQuest; +import com.magmaguy.elitemobs.quests.DynamicQuest; +import com.magmaguy.elitemobs.quests.Quest; +import com.magmaguy.elitemobs.quests.QuestTracking; +import com.magmaguy.elitemobs.quests.objectives.DynamicKillObjective; +import com.magmaguy.elitemobs.quests.objectives.KillObjective; +import com.magmaguy.elitemobs.quests.objectives.Objective; +import com.magmaguy.elitemobs.thirdparty.geyser.GeyserDetector; +import com.magmaguy.elitemobs.utils.BookMaker; +import com.magmaguy.elitemobs.utils.SpigotMessage; +import lombok.Getter; +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; + +import static com.magmaguy.elitemobs.quests.menus.QuestInventoryMenu.generateInventoryQuestEntries; + + +public class QuestMenu { + + private QuestMenu() { + } + + public static void generateCustomQuestMenu(List customQuestList, Player player, NPCEntity npcEntity) { + generateQuestMenu(customQuestList, player, npcEntity); + } + + public static void generateDynamicQuestMenu(List dynamicQuests, Player player, NPCEntity npcEntity) { + generateQuestMenu(dynamicQuests, player, npcEntity); + } + + public static void generateQuestMenu(List quests, Player player, NPCEntity npcEntity) { + if (!PlayerData.getUseBookMenus(player.getUniqueId()) || GeyserDetector.bedrockPlayer(player) || DefaultConfig.isOnlyUseBedrockMenus()) { + generateInventoryQuestEntries(quests, player, npcEntity); + } else { + generateBookQuestEntries(quests, player, npcEntity); + } + } + + public static void generateBookQuestEntries(List quests, Player player, NPCEntity npcEntity) { + BookMaker.generateBook(player, generateBookQuestEntriesComponents(quests, player, npcEntity)); + } + + public static TextComponent[] generateBookQuestEntriesComponents(List quests, Player player, NPCEntity npcEntity) { + List textComponents = new ArrayList<>(); + int counter = 0; + for (Quest quest : quests) { + TextComponent[] iteratedTextComponent = QuestBookMenu.generateQuestEntry(quest, player, npcEntity); + counter += iteratedTextComponent.length; + textComponents.add(iteratedTextComponent); + } + + TextComponent[] allQuests = new TextComponent[counter]; + + int counter2 = 0; + for (TextComponent[] textComponentsArray : textComponents) + for (TextComponent textComponent : textComponentsArray) { + allQuests[counter2] = textComponent; + counter2++; + } + + return allQuests; + } + + + private static TextComponent generateHeader(Quest quest) { + if (quest instanceof CustomQuest) + return SpigotMessage.simpleMessage(CustomQuestMenuConfig.getHeaderTextLines().replace("$questName", quest.getQuestName())); + else + return SpigotMessage.simpleMessage(DynamicQuestMenuConfig.getHeaderTextLines().replace("$questName", quest.getQuestName())); + } + + private static List generateBody(Quest quest) { + List body = new ArrayList<>(); + if (quest instanceof CustomQuest) + for (String splitString : ((CustomQuest) quest).getCustomQuestsConfigFields().getQuestLore()) + body.add(new TextComponent(ChatColorConverter.convert(splitString))); + else if (quest instanceof DynamicQuest) + body.add(new TextComponent(DynamicQuestMenuConfig.getDefaultLoreTextLines() + .replace("$amount", quest.getQuestObjectives().getObjectives().get(0).getTargetAmount() + "") + .replace("$name", EliteMobProperties.getPluginData(((DynamicKillObjective) quest.getQuestObjectives().getObjectives().get(0)).getEntityType()).getName(quest.getQuestLevel() * 10)))); + return body; + } + + private static TextComponent generateFixedSummary(Quest quest) { + TextComponent fixedSummary = new TextComponent(); + if (quest instanceof CustomQuest) + fixedSummary.setText(CustomQuestMenuConfig.getObjectivesLine()); + else if (quest instanceof DynamicQuest) + fixedSummary.setText(DynamicQuestMenuConfig.getObjectivesLine()); + return fixedSummary; + } + + private static List generateSummary(Quest quest) { + List textComponents = new ArrayList<>(); + if (quest instanceof CustomQuest) { + for (Objective objective : quest.getQuestObjectives().getObjectives()) + textComponents.add(new TextComponent(SpigotMessage.commandHoverMessage(CustomQuestMenuConfig.getObjectiveLine(objective), "", ""))); + } else if (quest instanceof DynamicQuest) { + for (Objective objective : quest.getQuestObjectives().getObjectives()) + if (objective instanceof KillObjective) { + //todo: hover should show more boss details, command string should allow players to try to track the boss + textComponents.add(new TextComponent(SpigotMessage.commandHoverMessage(DynamicQuestMenuConfig.getKillQuestDefaultSummaryLine(objective), "", ""))); + } + } + return textComponents; + } + + private static TextComponent generateFixedRewards(Quest quest) { + TextComponent questRewards = new TextComponent(); + if (quest instanceof CustomQuest) + questRewards.setText(CustomQuestMenuConfig.getRewardsLine()); + else if (quest instanceof DynamicQuest) + questRewards.setText(DynamicQuestMenuConfig.getRewardsLine()); + return questRewards; + } + + private static List generateRewards(Quest quest) { + if (quest instanceof CustomQuest) + return CustomQuestMenuConfig.getRewardsDefaultSummaryLine(quest.getQuestObjectives().getQuestReward()); + else + return DynamicQuestMenuConfig.getRewardsDefaultSummaryLine(quest.getQuestObjectives().getQuestReward()); + } + + private static TextComponent generateAccept(Quest quest, NPCEntity npcEntity) { + //Before quest was accepted + if (!quest.isAccepted()) + return initialQuestAccept(quest); + + //Quest is complete, turn in placeholder + if (npcEntity != null && + quest.getQuestObjectives().isOver() && + (quest instanceof DynamicQuest || + quest instanceof CustomQuest && + quest.getQuestTaker().equals(npcEntity.getNPCsConfigFields().getFilename()))) + return questAcceptComplete(quest); + + //Quest has begun but is either not over or the player is not talking to the turn in npc + return questAcceptAlreadyAccepted(quest); + } + + //Appears when the player hasn't accepted the quest yet + private static TextComponent initialQuestAccept(Quest quest) { + if (quest instanceof CustomQuest) { + return SpigotMessage.commandHoverMessage(CustomQuestMenuConfig.getAcceptTextLines(), + CustomQuestMenuConfig.getAcceptHoverLines(), + CustomQuestMenuConfig.getAcceptCommandLines().replace("$questID", quest.getQuestID().toString())); + } else { + return SpigotMessage.commandHoverMessage(DynamicQuestMenuConfig.getAcceptTextLines(), + DynamicQuestMenuConfig.getAcceptHoverLines(), + DynamicQuestMenuConfig.getAcceptCommandLines().replace("$questID", quest.getQuestID().toString())); + } + } + + //Appears when the player has accepted the quest but has not completed it yet, so it is not ready for turn in + private static TextComponent questAcceptAlreadyAccepted(Quest quest) { + if (quest instanceof CustomQuest) { + return SpigotMessage.commandHoverMessage(CustomQuestMenuConfig.getAcceptedTextLines(), + CustomQuestMenuConfig.getAcceptedHoverLines(), + CustomQuestMenuConfig.getAcceptedCommandLines().replace("$questID", quest.getQuestID().toString())); + } else { + return SpigotMessage.commandHoverMessage(DynamicQuestMenuConfig.getAcceptedTextLines(), + DynamicQuestMenuConfig.getAcceptedHoverLines(), + DynamicQuestMenuConfig.getAcceptedCommandLines().replace("$questID", quest.getQuestID().toString())); + } + } + + private static TextComponent generateTrack(Player player, Quest quest) { + if (!((CustomQuest) quest).getCustomQuestsConfigFields().isTrackable()) return new TextComponent(); + if (!CustomQuestMenuConfig.isUseQuestTracking()) return new TextComponent(); + if (!quest.isAccepted()) return new TextComponent(); + if (!QuestTracking.isTracking(player)) + return SpigotMessage.commandHoverMessage(CustomQuestMenuConfig.getTrackTextLines(), + CustomQuestMenuConfig.getTrackHoverLines(), CustomQuestMenuConfig.getTrackCommandLines().replace("$questID", quest.getQuestID() + "")); + else + return SpigotMessage.commandHoverMessage(CustomQuestMenuConfig.getUntrackTextLines(), + CustomQuestMenuConfig.getUntrackHoverLines(), CustomQuestMenuConfig.getUntrackCommandLines().replace("$questID", quest.getQuestID() + "")); + } + + //Appears when the player has completed the quest + private static TextComponent questAcceptComplete(Quest quest) { + if (quest instanceof CustomQuest) { + return SpigotMessage.commandHoverMessage(CustomQuestMenuConfig.getCompletedTextLines(), + CustomQuestMenuConfig.getCompletedHoverLines(), + CustomQuestMenuConfig.getCompletedCommandLines().replace("$questID", quest.getQuestID().toString())); + } else { + return SpigotMessage.commandHoverMessage(DynamicQuestMenuConfig.getCompletedTextLines(), + DynamicQuestMenuConfig.getCompletedHoverLines(), + DynamicQuestMenuConfig.getCompletedCommandLines().replace("$questID", quest.getQuestID().toString())); + } + } + + public static TextComponent[] generateQuestEntry(Player player, NPCEntity npcEntity) { + if (PlayerData.getQuests(player.getUniqueId()) == null) return new TextComponent[0]; + return generateBookQuestEntriesComponents(PlayerData.getQuests(player.getUniqueId()), player, npcEntity); + } + + public static class QuestText { + @Getter + private final TextComponent header; + @Getter + private final List body; + @Getter + private final TextComponent fixedSummary; + @Getter + private final List summary; + @Getter + private final TextComponent fixedRewards; + @Getter + private final List rewards; + @Getter + private final TextComponent accept; + @Getter + private TextComponent track; + + public QuestText(Quest quest, NPCEntity npcEntity, Player player) { + header = generateHeader(quest); + body = generateBody(quest); + fixedSummary = generateFixedSummary(quest); + summary = generateSummary(quest); + fixedRewards = generateFixedRewards(quest); + rewards = generateRewards(quest); + accept = generateAccept(quest, npcEntity); + track = null; + if (quest instanceof CustomQuest) + track = generateTrack(player, quest); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/quests/objectives/CustomFetchObjective.java b/src/main/java/com/magmaguy/elitemobs/quests/objectives/CustomFetchObjective.java new file mode 100644 index 000000000..5aa1e6b72 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/quests/objectives/CustomFetchObjective.java @@ -0,0 +1,142 @@ +package com.magmaguy.elitemobs.quests.objectives; + +import com.magmaguy.elitemobs.api.QuestAcceptEvent; +import com.magmaguy.elitemobs.api.QuestCompleteEvent; +import com.magmaguy.elitemobs.api.QuestRewardEvent; +import com.magmaguy.elitemobs.items.ItemTagger; +import com.magmaguy.elitemobs.playerdata.database.PlayerData; +import com.magmaguy.elitemobs.quests.Quest; +import com.magmaguy.elitemobs.utils.WarningMessage; +import lombok.Getter; +import lombok.Setter; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityPickupItemEvent; +import org.bukkit.event.player.PlayerDropItemEvent; +import org.bukkit.inventory.ItemStack; +import org.jetbrains.annotations.NotNull; + +public class CustomFetchObjective extends Objective { + + @Getter + private String key; + @Getter + @Setter + /** + * This sets when a boss has been detected as having dropped the relevant item for the quest after the quest has been slated to begin. + */ + private boolean readyToPickUp = false; + /** + * This sets whether the items are lost upon turning the quest in + */ + @Getter + private boolean requireItemTurnIn; + + public CustomFetchObjective(int targetAmount, String objectiveName, String customItemFilename) { + super(targetAmount, objectiveName); + this.key = customItemFilename; + } + + private static void checkEvent(@NotNull Player player, @NotNull ItemStack itemStack, boolean increment) { + for (Quest quest : PlayerData.getQuests(player.getUniqueId())) + for (Objective objective : quest.getQuestObjectives().getObjectives()) + if (objective instanceof CustomFetchObjective) + ((CustomFetchObjective) objective).checkItem(player, itemStack, increment, quest.getQuestObjectives()); + } + + private void checkItem(Player player, @NotNull ItemStack itemStack, boolean increment, QuestObjectives questObjectives) { + if (ItemTagger.hasKey(itemStack, this.key)) + if (increment) + incrementCount(player, itemStack.getAmount(), questObjectives); + else + decrementCount(player, itemStack.getAmount(), questObjectives); + } + + private void incrementCount(Player player, int amount, QuestObjectives questObjectives) { + super.currentAmount += amount; + checkProgress(player, questObjectives, amount); + } + + private void decrementCount(Player player, int amount, QuestObjectives questObjectives) { + super.currentAmount -= amount; + checkProgress(player, questObjectives, -amount); + } + + public void checkProgress(Player player, QuestObjectives questObjectives, int pendingAmount) { + boolean strictCheck = super.currentAmount < 0 || super.currentAmount >= super.targetAmount; + if (strictCheck) { + if (pendingAmount > 0) strictCheck(player, pendingAmount); + else strictCheck(player, 0); + } + progressNonlinearObjective(questObjectives); + } + + private void strictCheck(Player player, int pendingAmount) { + super.currentAmount = 0; + for (ItemStack itemStack : player.getInventory()) + if (ItemTagger.hasKey(itemStack, this.key)) + super.currentAmount += itemStack.getAmount(); + super.currentAmount += pendingAmount; + } + + private void turnItemsIn(Player player) { + int deletedItems = 0; + for (ItemStack itemStack : player.getInventory()) { + if (ItemTagger.hasKey(itemStack, this.key)) { + int existingAmount = itemStack.getAmount(); + int missingAmount = targetAmount - deletedItems; + if (existingAmount >= missingAmount) { + existingAmount -= missingAmount; + deletedItems += missingAmount; + } else + existingAmount = 0; + itemStack.setAmount(existingAmount); + if (deletedItems == targetAmount) + return; + } + } + new WarningMessage("Player " + player.getName() + " managed to complete objective " + objectiveName + " without turning in the required amount of items! This isn't good, tell the developer!"); + } + + public static class CustomFetchObjectiveEvents implements Listener { + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onItemDrop(PlayerDropItemEvent event) { + checkEvent(event.getPlayer(), event.getItemDrop().getItemStack(), false); + } + + @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) + public void onItemPickup(EntityPickupItemEvent event) { + if (event.getEntity().getType() != EntityType.PLAYER) return; + checkEvent((Player) event.getEntity(), event.getItem().getItemStack(), true); + } + + @EventHandler(ignoreCancelled = true) + public void onQuestAcceptEvent(QuestAcceptEvent event) { + for (Objective objective : event.getQuest().getQuestObjectives().getObjectives()) + if (objective instanceof CustomFetchObjective) + ((CustomFetchObjective) objective).strictCheck(event.getPlayer(), 0); + } + + @EventHandler(ignoreCancelled = true) + public void onQuestCompleteEvent(QuestCompleteEvent event) { + for (Objective objective : event.getQuest().getQuestObjectives().getObjectives()) + if (objective instanceof CustomFetchObjective) { + ((CustomFetchObjective) objective).checkProgress(event.getPlayer(), event.getQuest().getQuestObjectives(), 0); + if (objective.getCurrentAmount() < objective.getTargetAmount()) + event.setCancelled(true); + } + } + + @EventHandler(ignoreCancelled = true) + public void onQuestRewardEvent(QuestRewardEvent event) { + for (Objective objective : event.getQuest().getQuestObjectives().getObjectives()) + if (objective instanceof CustomFetchObjective) + ((CustomFetchObjective) objective).turnItemsIn(event.getPlayer()); + } + } + + +} diff --git a/src/main/java/com/magmaguy/elitemobs/quests/objectives/CustomKillObjective.java b/src/main/java/com/magmaguy/elitemobs/quests/objectives/CustomKillObjective.java new file mode 100644 index 000000000..66fd9c8ff --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/quests/objectives/CustomKillObjective.java @@ -0,0 +1,29 @@ +package com.magmaguy.elitemobs.quests.objectives; + +import com.magmaguy.elitemobs.api.EliteMobDeathEvent; +import com.magmaguy.elitemobs.config.custombosses.CustomBossesConfig; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import lombok.Getter; + +public class CustomKillObjective extends KillObjective { + + @Getter + private final String customBossFilename; + + public CustomKillObjective(String customBossFilename, int targetKillAmount, int questLevel) { + super(targetKillAmount, CustomBossesConfig.getCustomBosses().get(customBossFilename).getCleanName(questLevel * 10)); + this.customBossFilename = customBossFilename; + } + + @Override + public void checkProgress(EliteMobDeathEvent event, QuestObjectives questObjectives) { + if (!(event.getEliteEntity() instanceof CustomBossEntity)) return; + CustomBossEntity customBossEntity = (CustomBossEntity) event.getEliteEntity(); + String filename = customBossEntity.getCustomBossesConfigFields().getFilename(); + if (customBossEntity.getPhaseBossEntity() != null) + filename = customBossEntity.getPhaseBossEntity().getPhase1Config().getFilename(); + if (!filename.equals(customBossFilename)) return; + progressObjective(questObjectives); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/quests/objectives/CustomObjectivesParser.java b/src/main/java/com/magmaguy/elitemobs/quests/objectives/CustomObjectivesParser.java new file mode 100644 index 000000000..01a020d92 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/quests/objectives/CustomObjectivesParser.java @@ -0,0 +1,94 @@ +package com.magmaguy.elitemobs.quests.objectives; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.quests.CustomQuest; +import com.magmaguy.elitemobs.utils.WarningMessage; + +import java.util.ArrayList; +import java.util.List; + +public class CustomObjectivesParser { + /** + * Processes the custom objectives as set in the configuration file. These objectives must follow one or more of these formats: + * KILL_CUSTOM:filename=X.yml:amount=Y + * FETCH_ITEM:filename=X.yml:amount=Y + */ + public static List processCustomObjectives(CustomQuest customQuest) { + List objectives = new ArrayList<>(); + for (String string : customQuest.getCustomQuestsConfigFields().getCustomObjectivesList()) { + String[] rawStrings = string.split(":"); + switch (rawStrings[0]) { + case "KILL_CUSTOM": + objectives.add(processObjectiveType(rawStrings, ObjectiveType.KILL_CUSTOM, customQuest)); + break; + case "FETCH_ITEM": + objectives.add(processObjectiveType(rawStrings, ObjectiveType.FETCH_ITEM, customQuest)); + break; + case "DIALOG": + objectives.add(processObjectiveType(rawStrings, ObjectiveType.DIALOG, customQuest)); + break; + default: + new WarningMessage("Entry " + string + " for quest " + customQuest.getCustomQuestsConfigFields().getFilename() + " is not valid! Check the documentation on how to create valid quest objectives on the wiki!"); + return new ArrayList<>(); + } + } + return objectives; + } + + private static Objective processObjectiveType(String[] rawStrings, ObjectiveType objectiveType, CustomQuest customQuest) { + String filename = null; + String location = null; + String dialog = null; + String name = null; + int amount = 1; + for (String rawString : rawStrings) { + String[] processedStrings = rawString.split("="); + switch (processedStrings[0]) { + case "filename": + filename = processedStrings[1]; + break; + case "amount": + try { + amount = Integer.parseInt(processedStrings[1]); + } catch (Exception ex) { + new WarningMessage("Invalid amount " + amount + " in entry " + rawString + " for Custom Quest " + filename + " . Defaulting to 1."); + } + break; + case "location": + location = ChatColorConverter.convert(processedStrings[1]); + break; + case "dialog": + dialog = ChatColorConverter.convert(processedStrings[1]); + break; + case "npcName": + case "itemName": + case "name": + name = ChatColorConverter.convert(processedStrings[1]); + break; + } + } + if (filename == null) { + new WarningMessage("Invalid filename for entry " + rawStrings.toString() + " in Custom Quest " + customQuest.getCustomQuestsConfigFields().getFilename() + " . This objective will not be registered."); + return null; + } + try { + if (objectiveType.equals(ObjectiveType.KILL_CUSTOM)) + return new CustomKillObjective(filename, amount, customQuest.getQuestLevel()); + else if (objectiveType.equals(ObjectiveType.FETCH_ITEM)) + return new CustomFetchObjective(amount, name, filename); + else if (objectiveType.equals(ObjectiveType.DIALOG)) + return new DialogObjective(filename, name, location, dialog); + } catch (Exception ex) { + new WarningMessage("Failed to register objective type for quest " + customQuest.getCustomQuestsConfigFields().getFilename() + " ! This quest will be skipped"); + } + + return null; + + } + + private enum ObjectiveType { + KILL_CUSTOM, + FETCH_ITEM, + DIALOG + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/quests/objectives/DialogObjective.java b/src/main/java/com/magmaguy/elitemobs/quests/objectives/DialogObjective.java new file mode 100644 index 000000000..5211ab49f --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/quests/objectives/DialogObjective.java @@ -0,0 +1,53 @@ +package com.magmaguy.elitemobs.quests.objectives; + +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.npcs.NPCEntity; +import com.magmaguy.elitemobs.playerdata.database.PlayerData; +import com.magmaguy.elitemobs.quests.Quest; +import lombok.Getter; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerInteractAtEntityEvent; + +public class DialogObjective extends Objective { + + @Getter + private final String targetLocation; + @Getter + private final String npcFilename; + @Getter + private final String dialog; + + public DialogObjective(String npcFilename, String npcName, String targetLocation, String dialog) { + super(1, npcName); + this.targetLocation = targetLocation; + this.npcFilename = npcFilename; + this.dialog = dialog.replace("\\n", System.lineSeparator()); + } + + public boolean checkProgress(Player player, QuestObjectives questObjectives) { + if (super.currentAmount >= super.targetAmount) return false; + progressObjective(questObjectives); + player.sendMessage(dialog); + return true; + } + + public static class DialogObjectiveEvents implements Listener { + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onInteract(PlayerInteractAtEntityEvent event) { + NPCEntity npcEntity = EntityTracker.getNPCEntity(event.getRightClicked()); + if (npcEntity == null) return; + for (Quest quest : PlayerData.getQuests(event.getPlayer().getUniqueId())) + for (Objective objective : quest.getQuestObjectives().getObjectives()) + if (objective instanceof DialogObjective && + ((DialogObjective) objective).getNpcFilename().equals(npcEntity.getNPCsConfigFields().getFilename())) + if (((DialogObjective) objective).checkProgress(event.getPlayer(), quest.getQuestObjectives())) { + event.setCancelled(true); + } + + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/quests/objectives/DynamicKillObjective.java b/src/main/java/com/magmaguy/elitemobs/quests/objectives/DynamicKillObjective.java new file mode 100644 index 000000000..83d44c44a --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/quests/objectives/DynamicKillObjective.java @@ -0,0 +1,27 @@ +package com.magmaguy.elitemobs.quests.objectives; + +import com.magmaguy.elitemobs.api.EliteMobDeathEvent; +import com.magmaguy.elitemobs.mobconstructor.mobdata.aggressivemobs.EliteMobProperties; +import lombok.Getter; +import org.bukkit.entity.EntityType; + +public class DynamicKillObjective extends KillObjective { + + @Getter + private final EntityType entityType; + @Getter + private final int minMobLevel; + + public DynamicKillObjective(int targetAmount, EntityType entityType, int questLevel) { + super(targetAmount, EliteMobProperties.getPluginData(entityType).getName(questLevel * 10)); + this.minMobLevel = questLevel * 10; + this.entityType = entityType; + } + + @Override + public void checkProgress(EliteMobDeathEvent event, QuestObjectives questObjectives) { + if (event.getEliteEntity().getLevel() < minMobLevel) return; + if (event.getEliteEntity().getUnsyncedLivingEntity().getType() != this.entityType) return; + progressObjective(questObjectives); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/quests/objectives/KillObjective.java b/src/main/java/com/magmaguy/elitemobs/quests/objectives/KillObjective.java new file mode 100644 index 000000000..b54c1a804 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/quests/objectives/KillObjective.java @@ -0,0 +1,32 @@ +package com.magmaguy.elitemobs.quests.objectives; + +import com.magmaguy.elitemobs.api.EliteMobDeathEvent; +import com.magmaguy.elitemobs.playerdata.database.PlayerData; +import com.magmaguy.elitemobs.quests.Quest; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; + +public abstract class KillObjective extends Objective { + + protected KillObjective(int targetAmount, String objectiveName) { + super(targetAmount, objectiveName); + } + + public abstract void checkProgress(EliteMobDeathEvent event, QuestObjectives questObjectives); + + public static class KillObjectiveEvents implements Listener { + @EventHandler + public void onEliteDeath(EliteMobDeathEvent event) { + for (Player player : event.getEliteEntity().getDamagers().keySet()) { + if (!player.hasMetadata("NPC") && PlayerData.isInMemory(player.getUniqueId())) + for (Quest quest : PlayerData.getQuests(player.getUniqueId())) + if (quest != null) + for (Objective objective : quest.getQuestObjectives().getObjectives()) + if (objective instanceof KillObjective) + ((KillObjective) objective).checkProgress(event, quest.getQuestObjectives()); + } + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/quests/objectives/Objective.java b/src/main/java/com/magmaguy/elitemobs/quests/objectives/Objective.java new file mode 100644 index 000000000..2f735a5a8 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/quests/objectives/Objective.java @@ -0,0 +1,52 @@ +package com.magmaguy.elitemobs.quests.objectives; + +import com.magmaguy.elitemobs.api.QuestProgressionEvent; +import com.magmaguy.elitemobs.utils.EventCaller; +import lombok.Getter; +import lombok.Setter; +import org.bukkit.Bukkit; + +import java.io.Serializable; + +public abstract class Objective implements Serializable { + //todo: add the ability to have multiple quest objective types in here instead of just the one + //todo: this class should be the one that handles giving out quest rewards + + @Getter + protected boolean objectiveCompleted = false; + + @Getter + @Setter + protected int currentAmount = 0; + @Getter + protected int targetAmount; + + @Getter + protected String objectiveName; + + public Objective(int targetAmount, String objectiveName) { + this.targetAmount = targetAmount; + this.objectiveName = objectiveName; + } + + public void progressObjective(QuestObjectives questObjectives) { + currentAmount++; + if (currentAmount >= targetAmount) + objectiveCompleted = true; + QuestProgressionEvent questProgressionEvent = new QuestProgressionEvent( + Bukkit.getPlayer(questObjectives.getQuest().getPlayerUUID()), + questObjectives.getQuest(), + this); + new EventCaller(questProgressionEvent); + } + + public void progressNonlinearObjective(QuestObjectives questObjectives) { + QuestProgressionEvent questProgressionEvent = new QuestProgressionEvent( + Bukkit.getPlayer(questObjectives.getQuest().getPlayerUUID()), + questObjectives.getQuest(), + this); + new EventCaller(questProgressionEvent); + objectiveCompleted = currentAmount >= targetAmount; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/quests/objectives/QuestObjectives.java b/src/main/java/com/magmaguy/elitemobs/quests/objectives/QuestObjectives.java new file mode 100644 index 000000000..620e9b951 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/quests/objectives/QuestObjectives.java @@ -0,0 +1,119 @@ +package com.magmaguy.elitemobs.quests.objectives; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.api.QuestObjectivesCompletedEvent; +import com.magmaguy.elitemobs.config.QuestsConfig; +import com.magmaguy.elitemobs.quests.CustomQuest; +import com.magmaguy.elitemobs.quests.Quest; +import com.magmaguy.elitemobs.quests.rewards.QuestReward; +import com.magmaguy.elitemobs.utils.EventCaller; +import com.magmaguy.elitemobs.utils.SimpleScoreboard; +import lombok.Getter; +import lombok.Setter; +import org.bukkit.Bukkit; +import org.bukkit.entity.EntityType; +import org.bukkit.entity.Player; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.UUID; +import java.util.concurrent.ThreadLocalRandom; + +public class QuestObjectives implements Serializable { + + @Getter + @Setter + protected QuestReward questReward; + @Getter + @Setter + private List objectives; + //The CustomQuest this objective belongs to + @Getter + private Quest quest; + private boolean over = false; + @Getter + @Setter + private boolean turnedIn = false; + @Setter + private boolean forceOver = false; + + /** + * Used for dynamic quests + */ + public QuestObjectives(int questLevel) { + generateRandomObjective(questLevel); + } + + /** + * Used for custom quests + * + * @param customQuestReward Predetermined Quest Reward + */ + public QuestObjectives(QuestReward customQuestReward) { + this.questReward = customQuestReward; + } + + private void generateRandomObjective(int questLevel) { + int killAmount = ThreadLocalRandom.current().nextInt(1 + questLevel, 1 + questLevel * 10); + EntityType entityType = QuestsConfig.getQuestEntityTypes().get(ThreadLocalRandom.current().nextInt(QuestsConfig.getQuestEntityTypes().size())); + KillObjective killObjective = new DynamicKillObjective(killAmount, entityType, questLevel); + this.objectives = Collections.singletonList(killObjective); + } + + public void setQuest(Quest quest) { + this.quest = quest; + if (quest instanceof CustomQuest) + this.objectives = CustomObjectivesParser.processCustomObjectives((CustomQuest) quest); + } + + /** + * Returns whether all the objectives have been cleared, meaning that the quest is over + * + * @return + */ + public boolean isOver() { + //used by the force bypass + if (forceOver) return true; + boolean checkOver = true; + for (Objective objective : objectives) + if (!objective.isObjectiveCompleted()) { + checkOver = false; + break; + } + return checkOver; + } + + public void updateQuestStatus(UUID playerUUID) { + //This checks if the player managed to try to progress an already over and turned in quest, which would reward them again. + //This would in theory only be possible for quests that display the "completed" status, but should still be inaccessible in theory. + if (turnedIn) return; + if (over) return; + if (!isOver()) return; + over = true; + QuestObjectivesCompletedEvent questObjectivesCompletedEvent = new QuestObjectivesCompletedEvent(Bukkit.getPlayer(playerUUID), quest); + new EventCaller(questObjectivesCompletedEvent); + } + + + public void displayTemporaryObjectivesScoreboard(Player player) { + if (!QuestsConfig.isUseQuestScoreboards()) return; + List strings = new ArrayList<>(); + for (Objective objective : objectives) + strings.add(QuestsConfig.getQuestScoreboardProgressionLine(objective)); + + SimpleScoreboard.temporaryScoreboard(player, ChatColorConverter.convert(getQuest().getQuestName()), strings, 20 * 20); + } + + public void displayLazyObjectivesScoreboard(Player player) { + if (!QuestsConfig.isUseQuestScoreboards()) return; + List strings = new ArrayList<>(); + for (Objective objective : objectives) + strings.add(QuestsConfig.getQuestScoreboardProgressionLine(objective)); + + SimpleScoreboard.lazyScoreboard(player, ChatColorConverter.convert(getQuest().getQuestName()), strings); + } + + +} diff --git a/src/main/java/com/magmaguy/elitemobs/quests/playercooldowns/PlayerQuestCooldowns.java b/src/main/java/com/magmaguy/elitemobs/quests/playercooldowns/PlayerQuestCooldowns.java new file mode 100644 index 000000000..361a2d578 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/quests/playercooldowns/PlayerQuestCooldowns.java @@ -0,0 +1,70 @@ +package com.magmaguy.elitemobs.quests.playercooldowns; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.playerdata.database.PlayerData; +import com.magmaguy.elitemobs.utils.WarningMessage; +import lombok.Getter; +import org.bukkit.entity.Player; +import org.bukkit.permissions.PermissionAttachment; + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.UUID; + +public class PlayerQuestCooldowns implements Serializable { + + @Getter + private final List questCooldowns = new ArrayList<>(); + + /** + * Initializes cooldowns from scratch, assuming no preexisting player data + */ + public PlayerQuestCooldowns() { + //This just initializes the cooldown list + } + + public static PlayerQuestCooldowns initializePlayer() { + return new PlayerQuestCooldowns(); + } + + public static void resetPlayerQuestCooldowns(Player player) { + if (PlayerData.getPlayerQuestCooldowns(player.getUniqueId()) == null) return; + PermissionAttachment permissionAttachment = Objects.requireNonNull(player).addAttachment(MetadataHandler.PLUGIN); + PlayerQuestCooldowns playerQuestCooldowns = PlayerData.getPlayerQuestCooldowns(player.getUniqueId()); + for (QuestCooldown questCooldown : playerQuestCooldowns.getQuestCooldowns()) { + if (questCooldown.getBukkitTask() != null) + questCooldown.getBukkitTask().cancel(); + permissionAttachment.setPermission(questCooldown.getPermission(), false); + player.removeMetadata(questCooldown.getPermission(), MetadataHandler.PLUGIN); + } + playerQuestCooldowns.getQuestCooldowns().clear(); + PlayerData.resetQuests(player.getUniqueId()); + PlayerData.resetPlayerQuestCooldowns(player.getUniqueId()); + } + + public static void addCooldown(Player player, String permission, int delayInMinutes) { + PlayerQuestCooldowns playerQuestCooldowns = PlayerData.getPlayerQuestCooldowns(player.getUniqueId()); + if (playerQuestCooldowns == null) { + playerQuestCooldowns = new PlayerQuestCooldowns(); + new WarningMessage("For some reason the player cooldowns failed to read, warn the dev!", true); + } + playerQuestCooldowns.questCooldowns.add(new QuestCooldown(delayInMinutes, permission, player.getUniqueId())); + PlayerData.updatePlayerQuestCooldowns(player.getUniqueId(), playerQuestCooldowns); + } + + public static void flushPlayer(Player player) { + PlayerQuestCooldowns playerQuestCooldowns = PlayerData.getPlayerQuestCooldowns(player.getUniqueId()); + if (playerQuestCooldowns == null) return; + for (QuestCooldown questCooldown : Objects.requireNonNull(PlayerData.getPlayerQuestCooldowns(player.getUniqueId())).questCooldowns) + if (questCooldown.getBukkitTask() != null) + questCooldown.getBukkitTask().cancel(); + } + + public void startCooldowns(UUID player) { + for (QuestCooldown questCooldown : questCooldowns) + questCooldown.startCooldown(player); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/quests/playercooldowns/PlayerQuestCooldownsLogout.java b/src/main/java/com/magmaguy/elitemobs/quests/playercooldowns/PlayerQuestCooldownsLogout.java new file mode 100644 index 000000000..8df9d1348 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/quests/playercooldowns/PlayerQuestCooldownsLogout.java @@ -0,0 +1,12 @@ +package com.magmaguy.elitemobs.quests.playercooldowns; + +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerQuitEvent; + +public class PlayerQuestCooldownsLogout implements Listener { + @EventHandler + public static void onPlayerLogout(PlayerQuitEvent event) { + PlayerQuestCooldowns.flushPlayer(event.getPlayer()); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/quests/playercooldowns/QuestCooldown.java b/src/main/java/com/magmaguy/elitemobs/quests/playercooldowns/QuestCooldown.java new file mode 100644 index 000000000..922d7452d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/quests/playercooldowns/QuestCooldown.java @@ -0,0 +1,55 @@ +package com.magmaguy.elitemobs.quests.playercooldowns; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.playerdata.database.PlayerData; +import lombok.Getter; +import org.bukkit.Bukkit; +import org.bukkit.metadata.LazyMetadataValue; +import org.bukkit.permissions.PermissionAttachment; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scheduler.BukkitTask; + +import java.io.Serializable; +import java.util.Objects; +import java.util.UUID; + +public class QuestCooldown implements Serializable { + @Getter + private final String permission; + private final boolean permanent; + @Getter + private long targetUnixTime = 0; + @Getter + private transient BukkitTask bukkitTask = null; + + public QuestCooldown(int delayInMinutes, String permission, UUID player) { + this.permanent = delayInMinutes < 1; + if (!permanent) + this.targetUnixTime = System.currentTimeMillis() + 60L * 1000 * delayInMinutes; + this.permission = permission; + startCooldown(player); + } + + public void startCooldown(UUID player) { + long delay = Math.max((targetUnixTime - System.currentTimeMillis()) / 1000L * 20L, 0L); + PermissionAttachment permissionAttachment = Objects.requireNonNull(Bukkit.getPlayer(player)).addAttachment(MetadataHandler.PLUGIN); + if (!permanent && delay < 1) { + permissionAttachment.unsetPermission(permission); + return; + } + permissionAttachment.setPermission(permission, true); + Bukkit.getPlayer(player).setMetadata(permission, new LazyMetadataValue(MetadataHandler.PLUGIN, () -> true)); + if (!permanent) + bukkitTask = new BukkitRunnable() { + @Override + public void run() { + if (Bukkit.getPlayer(player) != null) { + permissionAttachment.unsetPermission(permission); + Bukkit.getPlayer(player).removeMetadata(permission, MetadataHandler.PLUGIN); + PlayerData.updatePlayerQuestCooldowns(player, PlayerData.getPlayerQuestCooldowns(player)); + } + } + }.runTaskLater(MetadataHandler.PLUGIN, delay); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/quests/rewards/QuestReward.java b/src/main/java/com/magmaguy/elitemobs/quests/rewards/QuestReward.java new file mode 100644 index 000000000..15b741ca7 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/quests/rewards/QuestReward.java @@ -0,0 +1,52 @@ +package com.magmaguy.elitemobs.quests.rewards; + +import com.magmaguy.elitemobs.config.customquests.CustomQuestsConfigFields; +import com.magmaguy.elitemobs.items.LootTables; +import com.magmaguy.elitemobs.items.customloottable.CustomLootTable; +import com.magmaguy.elitemobs.playerdata.database.PlayerData; +import com.magmaguy.elitemobs.quests.objectives.Objective; +import com.magmaguy.elitemobs.quests.objectives.QuestObjectives; +import lombok.Getter; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.io.Serializable; +import java.util.UUID; + +public class QuestReward implements Serializable { + + @Getter + private CustomLootTable customLootTable = null; + @Getter + private int rewardLevel; + @Getter + private UUID playerUUID; + + public QuestReward(int questLevel, QuestObjectives questObjectives, Player player) { + this.rewardLevel = questLevel * 10; + this.playerUUID = player.getUniqueId(); + int killAmount = questObjectives.getObjectives().stream().mapToInt(Objective::getTargetAmount).sum(); + int baselineReward = (int) (rewardLevel / 2D * killAmount); + customLootTable = new CustomLootTable(); + customLootTable.generateCurrencyEntry(baselineReward); + ItemStack itemReward = LootTables.generateItemStack(Math.min(rewardLevel, PlayerData.getMaxGuildLevel(player.getUniqueId()) * 10), player, null); + customLootTable.generateEliteEntry(itemReward); + } + + /** + * This generates a list of custom quest rewards based on configuration file entries. It uses the following formats: + * Custom Items: filename=X.yml:amount=Y:chance=Z + * Vanilla Items: material=X:amount=Y:chance=Z + */ + public QuestReward(CustomQuestsConfigFields customQuestsConfigFields, Player player) { + this.rewardLevel = customQuestsConfigFields.getQuestLevel() * 10; + this.playerUUID = player.getUniqueId(); + this.customLootTable = new CustomLootTable(customQuestsConfigFields); + } + + public void doRewards() { + customLootTable.questDrop(Bukkit.getPlayer(playerUUID), rewardLevel); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/quests/rewards/RewardEntry.java b/src/main/java/com/magmaguy/elitemobs/quests/rewards/RewardEntry.java new file mode 100644 index 000000000..583223d69 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/quests/rewards/RewardEntry.java @@ -0,0 +1,80 @@ +package com.magmaguy.elitemobs.quests.rewards; + +import com.magmaguy.elitemobs.adventurersguild.GuildRank; +import com.magmaguy.elitemobs.economy.EconomyHandler; +import com.magmaguy.elitemobs.utils.ObjectSerializer; +import com.magmaguy.elitemobs.utils.WarningMessage; +import lombok.Getter; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; + +import java.io.Serializable; +import java.util.UUID; +import java.util.concurrent.ThreadLocalRandom; + +public class RewardEntry implements Serializable { + @Getter + private final double chance; + @Getter + private final int amount; + @Getter + private byte[] deserializedCustomItem; + @Getter + private transient ItemStack itemStack; + @Getter + private String deserializedItemStack; + @Getter + private String command; + @Getter + private double currencyAmount = 0; + + public RewardEntry(ItemStack itemStack, double chance, int amount) { + this.itemStack = itemStack; + try { + this.deserializedItemStack = ObjectSerializer.itemStackArrayToBase64(itemStack); + } catch (Exception ex) { + ex.printStackTrace(); + } + + this.chance = chance; + this.amount = amount; + } + + public RewardEntry(String command, double chance, int amount) { + this.command = command; + this.chance = chance; + this.amount = amount; + } + + public RewardEntry(double currencyAmount, double chance, int amount, Player player) { + this.currencyAmount = currencyAmount * GuildRank.currencyBonusMultiplier(player.getUniqueId()); + this.chance = chance; + this.amount = amount; + } + + public void serializeReward() { + if (itemStack == null && deserializedItemStack != null) + try { + this.itemStack = ObjectSerializer.itemStackArrayFromBase64(deserializedItemStack); + } catch (Exception ex) { + new WarningMessage("Failed to serialize item stack"); + ex.printStackTrace(); + } + } + + public void doReward(UUID playerUUID) { + //todo: check if quest is limiting loot level as it should + Player player = Bukkit.getPlayer(playerUUID); + if (ThreadLocalRandom.current().nextDouble() < chance) + for (int i = 0; i < amount; i++) + if (itemStack != null) + player.getInventory().addItem(itemStack); + else if (command != null) + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command.replace("$player", player.getName())); + else if (currencyAmount != 0) + EconomyHandler.addCurrency(playerUUID, currencyAmount); + else + new WarningMessage("Quest failed to dispatch reward! Report this to the dev!", true); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/runnables/DynamicLoreUpdater.java b/src/main/java/com/magmaguy/elitemobs/runnables/DynamicLoreUpdater.java deleted file mode 100644 index 12c015100..000000000 --- a/src/main/java/com/magmaguy/elitemobs/runnables/DynamicLoreUpdater.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.magmaguy.elitemobs.runnables; - -import com.magmaguy.elitemobs.items.DynamicLore; -import org.bukkit.scheduler.BukkitRunnable; - -public class DynamicLoreUpdater extends BukkitRunnable { - - @Override - public void run() { - - DynamicLore.refreshDynamicLore(); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/runnables/EntityListUpdater.java b/src/main/java/com/magmaguy/elitemobs/runnables/EntityListUpdater.java deleted file mode 100644 index 0e4a4377b..000000000 --- a/src/main/java/com/magmaguy/elitemobs/runnables/EntityListUpdater.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.magmaguy.elitemobs.runnables; - -public class EntityListUpdater { - -// public static void startUpdating(){ -// -// EntityTracker.checkEntityState(); -// -// } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/runnables/EntityScanner.java b/src/main/java/com/magmaguy/elitemobs/runnables/EntityScanner.java deleted file mode 100644 index 72fec1753..000000000 --- a/src/main/java/com/magmaguy/elitemobs/runnables/EntityScanner.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.magmaguy.elitemobs.runnables; - -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.config.MobCombatSettingsConfig; -import com.magmaguy.elitemobs.config.ValidMobsConfig; -import com.magmaguy.elitemobs.mobscanner.EliteMobScanner; -import com.magmaguy.elitemobs.mobscanner.SuperMobScanner; -import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.scheduler.BukkitTask; - -public class EntityScanner extends BukkitRunnable { - - @Override - public void run() { - if (ConfigValues.mobCombatSettingsConfig.getBoolean(MobCombatSettingsConfig.AGGRESSIVE_MOB_STACKING)) { - BukkitTask scanElites = new BukkitRunnable() { - @Override - public void run() { - EliteMobScanner.scanElites(); - } - }.runTaskTimer(MetadataHandler.PLUGIN, 20 * 5, 20 * 5); - } - - - if (ConfigValues.validMobsConfig.getBoolean(ValidMobsConfig.ALLOW_PASSIVE_SUPERMOBS)) { - BukkitTask scanSuperMobs = new BukkitRunnable() { - @Override - public void run() { - SuperMobScanner.scanSuperMobs(); - } - }.runTaskTimer(MetadataHandler.PLUGIN, 20 * 12, 20 * 12); - } - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/runnables/PotionEffectApplier.java b/src/main/java/com/magmaguy/elitemobs/runnables/PotionEffectApplier.java deleted file mode 100644 index 103ebb329..000000000 --- a/src/main/java/com/magmaguy/elitemobs/runnables/PotionEffectApplier.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.magmaguy.elitemobs.runnables; - -import org.bukkit.scheduler.BukkitRunnable; - -public class PotionEffectApplier extends BukkitRunnable { - - public static com.magmaguy.elitemobs.items.PotionEffectApplier potionEffectApplier = new com.magmaguy.elitemobs.items.PotionEffectApplier(); - - @Override - public void run() { - - potionEffectApplier.potionEffectApplier(); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/runnables/ReapplyDisplayEffects.java b/src/main/java/com/magmaguy/elitemobs/runnables/ReapplyDisplayEffects.java deleted file mode 100644 index 3ea7b0fd4..000000000 --- a/src/main/java/com/magmaguy/elitemobs/runnables/ReapplyDisplayEffects.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.magmaguy.elitemobs.runnables; - -public class ReapplyDisplayEffects { - -// @Override -// public void run() { -// -// if (livingEntityList.isEmpty()) return; -// -// Iterator iterator = livingEntityList.iterator(); -// -// while (iterator.hasNext()) { -// -// Object currentEntity = iterator.next(); -// -// if (currentEntity == null) { -// -// iterator.remove(); -// -// } else { -// -// LivingEntity iteratedEntity = (LivingEntity) currentEntity; -// -// if (iteratedEntity.isDead() || !iteratedEntity.isValid()) { -// -// iterator.remove(); -// -// } -// -// } -// -// } -// -// for (LivingEntity livingEntity : livingEntityList) { -// if (livingEntity.isValid()) { -// MajorPowerPowerStance majorPowerPowerStance = new MajorPowerPowerStance(); -// majorPowerPowerStance.itemEffect(livingEntity); -// MinorPowerPowerStance minorPowerPowerStance = new MinorPowerPowerStance(); -// minorPowerPowerStance.itemEffect(livingEntity); -// } -// } -// -// } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/runnables/ScoreboardUpdater.java b/src/main/java/com/magmaguy/elitemobs/runnables/ScoreboardUpdater.java deleted file mode 100644 index b5793095d..000000000 --- a/src/main/java/com/magmaguy/elitemobs/runnables/ScoreboardUpdater.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.magmaguy.elitemobs.runnables; - -import com.magmaguy.elitemobs.scoreboard.ScoreboardHandler; -import org.bukkit.scheduler.BukkitRunnable; - -public class ScoreboardUpdater extends BukkitRunnable { - - ScoreboardHandler scoreboardHandler = new ScoreboardHandler(); - - @Override - public void run() { - - scoreboardHandler.scanSight(); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/scoreboard/ScoreboardHandler.java b/src/main/java/com/magmaguy/elitemobs/scoreboard/ScoreboardHandler.java deleted file mode 100644 index b7d118889..000000000 --- a/src/main/java/com/magmaguy/elitemobs/scoreboard/ScoreboardHandler.java +++ /dev/null @@ -1,188 +0,0 @@ -/* - * 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 . - */ - -package com.magmaguy.elitemobs.scoreboard; - -import com.magmaguy.elitemobs.EntityTracker; -import com.magmaguy.elitemobs.MetadataHandler; -import com.magmaguy.elitemobs.config.ConfigValues; -import com.magmaguy.elitemobs.mobconstructor.EliteMobEntity; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Location; -import org.bukkit.entity.Entity; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; -import org.bukkit.event.Listener; -import org.bukkit.plugin.Plugin; -import org.bukkit.scoreboard.*; - -import java.util.Collection; -import java.util.HashMap; - -/** - * Created by MagmaGuy on 03/05/2017. - */ -public class ScoreboardHandler implements Listener { - - static HashMap playerHasScoreboard = new HashMap(); - Plugin plugin = Bukkit.getPluginManager().getPlugin(MetadataHandler.ELITE_MOBS); - int processID; - - public void scanSight() { - - for (Player player : Bukkit.getOnlinePlayers()) { - - if (player.hasPermission("elitemobs.scoreboard") && playerHasScoreboard.containsKey(player) && - (Boolean) playerHasScoreboard.get(player) == false || !playerHasScoreboard.containsKey(player) && - player.hasPermission("elitemobs.scoreboard")) { - - Location playerLocation = player.getLocation(); - - Collection nearbyEntities = playerLocation.getWorld().getNearbyEntities(playerLocation, 7, 7, 7); - - for (Entity entity : nearbyEntities) { - - if (EntityTracker.isEliteMob(entity)) { - - aggressiveEliteMobScoreboard(entity, player); - return; - - } else if (EntityTracker.isSuperMob(entity)) { - - aggressiveEliteMobScoreboard(entity, player); - return; - - } - - } - - } - - } - - } - - public void aggressiveEliteMobScoreboard(Entity entity, Player player) { - - EliteMobEntity eliteMobEntity = EntityTracker.getEliteMobEntity(entity); - - processID = Bukkit.getServer().getScheduler().scheduleSyncRepeatingTask(plugin, new Runnable() { - - int iterator = 0; - - public void run() { - - if (!entity.isValid() || player.getWorld() != entity.getWorld() || - player.getLocation().distance(entity.getLocation()) > 7) { - - player.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); - playerHasScoreboard.put(player, false); - Bukkit.getScheduler().cancelTask(processID); - return; - - } - - int powerCounter = eliteMobEntity.getPowers().size(); - - ScoreboardManager scoreboardManager = Bukkit.getScoreboardManager(); - Scoreboard board = scoreboardManager.getNewScoreboard(); - Objective objective = board.registerNewObjective("test", "dummy"); - - objective.setDisplaySlot(DisplaySlot.SIDEBAR); - objective.setDisplayName(entity.getName()); - - - int currentHealth = (int) ((LivingEntity) entity).getHealth(); - int maxHealth = (int) ((LivingEntity) entity).getMaxHealth(); - - int counter = 0; - -// for (String string : MetadataHandler.allPowersList()) { -// -// if (entity.hasMetadata(string)) { -// -// String finalString = MetadataHandler.machineToHumanTranslator(string); -// -// if (powerCounter > 13) { -// -// Score score = null; -// -// if (MetadataHandler.defensivePowerList.contains(string) || MetadataHandler.offensivePowerList.contains(string) || -// MetadataHandler.miscellaneousPowerList.contains(string)) { -// -// score = objective.getScore(ChatColor.AQUA + finalString); -// -// } else if (MetadataHandler.majorPowerList.contains(string)) { -// -// score = objective.getScore(ChatColor.DARK_AQUA + finalString); -// -// } -// -// if (counter + iterator < powerCounter) { -// -// score.setScore(counter + iterator); -// -// } else { -// -// int currentValue = (int) ((counter + iterator) - Math.floor(((counter + iterator) / powerCounter) * powerCounter)); -// -// score.setScore(currentValue); -// -// } -// -// -// } else { -// -// Score score; -// -// if (MetadataHandler.defensivePowerList.contains(string) || MetadataHandler.offensivePowerList.contains(string) || -// MetadataHandler.miscellaneousPowerList.contains(string)) { -// -// score = objective.getScore(ChatColor.AQUA + finalString); -// -// } else { -// -// score = objective.getScore(ChatColor.DARK_AQUA + finalString); -// -// } -// -// score.setScore(counter); -// -// } -// -// counter++; -// -// } -// -// } - - player.setScoreboard(board); - playerHasScoreboard.put(player, true); - - Score healthScore = objective.getScore(String.format("%s%s", ChatColor.DARK_RED, ChatColor.BOLD) + - ConfigValues.translationConfig.getString("ScoreBoard.Health") + ChatColor.RED + currentHealth - + ChatColor.DARK_RED + "/" + ChatColor.RED + maxHealth); - healthScore.setScore(powerCounter); - - iterator++; - - } - - }, 4, 4); - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/tagger/PersistentTagger.java b/src/main/java/com/magmaguy/elitemobs/tagger/PersistentTagger.java new file mode 100644 index 000000000..206c33c50 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/tagger/PersistentTagger.java @@ -0,0 +1,101 @@ +package com.magmaguy.elitemobs.tagger; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.npcs.NPCEntity; +import lombok.Getter; +import org.bukkit.NamespacedKey; +import org.bukkit.entity.Entity; +import org.bukkit.entity.Projectile; +import org.bukkit.persistence.PersistentDataType; +import org.jetbrains.annotations.NotNull; + +import javax.annotation.Nullable; +import java.util.UUID; + +public class PersistentTagger { + @Getter + private static final String ELITE_ENTITY = "EliteEntity"; + @Getter + private static final String NPC_ENTITY = "NPCEntity"; + @Getter + private static final String SUPER_MOB = "SuperMob"; + @Getter + private static final String VISUAL_EFFECT = "VisualEffect"; + @Getter + private static final String ELITE_PROJECTILE = "EliteProjectile"; + + private PersistentTagger() { + } + + public static void tag(@NotNull Entity entity, String key, String value) { + entity.getPersistentDataContainer().set(new NamespacedKey(MetadataHandler.PLUGIN, key), PersistentDataType.STRING, value); + } + + public static void tagElite(Entity entity, @NotNull UUID eliteUUID) { + tag(entity, ELITE_ENTITY, eliteUUID.toString()); + } + + public static boolean isEliteEntity(Entity entity) { + if (entity == null) return false; + return entity.getPersistentDataContainer().has(new NamespacedKey(MetadataHandler.PLUGIN, ELITE_ENTITY), PersistentDataType.STRING); + } + + public static EliteEntity getEliteEntity(Entity entity) { + UUID uuid = getUUID(entity, ELITE_ENTITY); + if (uuid == null) return null; + return EntityTracker.getEliteMobEntities().get(uuid); + } + + public static void tagNPC(Entity entity, @NotNull UUID npcUUID) { + tag(entity, NPC_ENTITY, npcUUID.toString()); + } + + public static boolean isNPC(Entity entity) { + if (entity == null) return false; + return entity.getPersistentDataContainer().has(new NamespacedKey(MetadataHandler.PLUGIN, NPC_ENTITY), PersistentDataType.STRING); + } + + public static NPCEntity getNPC(Entity entity) { + UUID uuid = getUUID(entity, NPC_ENTITY); + if (uuid == null) return null; + return EntityTracker.getNpcEntities().get(uuid); + } + + public static void tagSuperMob(Entity entity) { + tag(entity, SUPER_MOB, entity.getType().toString()); + } + + public static boolean isSuperMob(Entity entity) { + if (entity == null) return false; + return entity.getPersistentDataContainer().has(new NamespacedKey(MetadataHandler.PLUGIN, SUPER_MOB), PersistentDataType.STRING); + } + + public static void tagVisualEffect(Entity entity) { + tag(entity, VISUAL_EFFECT, entity.getType().toString()); + } + + public static boolean isVisualEffect(Entity entity) { + if (entity == null) return false; + return entity.getPersistentDataContainer().has(new NamespacedKey(MetadataHandler.PLUGIN, VISUAL_EFFECT), PersistentDataType.STRING); + } + + public static void tagEliteProjectile(Projectile projectile) { + tag(projectile, ELITE_PROJECTILE, ""); + } + + public static boolean isEliteProjectile(Entity entity) { + if (entity == null) return false; + return entity.getPersistentDataContainer().has(new NamespacedKey(MetadataHandler.PLUGIN, ELITE_PROJECTILE), PersistentDataType.STRING); + } + + @Nullable + public static UUID getUUID(Entity entity, String key) { + if (entity == null) return null; + String uuidString = entity.getPersistentDataContainer().get(new NamespacedKey(MetadataHandler.PLUGIN, key), PersistentDataType.STRING); + if (uuidString == null) return null; + return UUID.fromString(uuidString); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/thirdparty/bstats/CustomCharts.java b/src/main/java/com/magmaguy/elitemobs/thirdparty/bstats/CustomCharts.java new file mode 100644 index 000000000..ea97fdd2c --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/thirdparty/bstats/CustomCharts.java @@ -0,0 +1,25 @@ +package com.magmaguy.elitemobs.thirdparty.bstats; + +import com.magmaguy.elitemobs.EliteMobs; +import com.magmaguy.elitemobs.dungeons.Minidungeon; +import org.bstats.bukkit.Metrics; +import org.bstats.charts.AdvancedPie; +import org.bukkit.ChatColor; + +import java.util.HashMap; +import java.util.Map; + +public class CustomCharts { + public CustomCharts() { + Metrics metrics = EliteMobs.metrics; + metrics.addCustomChart(new AdvancedPie("minidungeons", () -> { + Map valueMap = new HashMap<>(); + for (Minidungeon minidungeon : Minidungeon.getMinidungeons().values()) { + valueMap.put( + ChatColor.stripColor(minidungeon.getDungeonPackagerConfigFields().getFilename()), + minidungeon.isInstalled() ? 1 : 0); + } + return valueMap; + })); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/thirdparty/discordsrv/DiscordSRVAnnouncement.java b/src/main/java/com/magmaguy/elitemobs/thirdparty/discordsrv/DiscordSRVAnnouncement.java new file mode 100644 index 000000000..1359a68b9 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/thirdparty/discordsrv/DiscordSRVAnnouncement.java @@ -0,0 +1,50 @@ +package com.magmaguy.elitemobs.thirdparty.discordsrv; + +import com.magmaguy.elitemobs.config.DiscordSRVConfig; +import com.magmaguy.elitemobs.utils.WarningMessage; +import github.scarsz.discordsrv.DiscordSRV; +import github.scarsz.discordsrv.dependencies.jda.api.entities.TextChannel; +import github.scarsz.discordsrv.util.DiscordUtil; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; + +public class DiscordSRVAnnouncement { + + private static TextChannel textChannel = null; + private static boolean isInitialized = false; + + public DiscordSRVAnnouncement(String announcement) { + + if (Bukkit.getPluginManager().getPlugin("DiscordSRV") == null) return; + if (DiscordSRVConfig.getAnnouncementRoomName().equals("YOU_NEED_TO_PUT_THE_NAME_OF_THE_DISCORD_ROOM_YOU_WANT_ELITEMOBS" + + "_ANNOUNCEMENTS_TO_BE_BROADCASTED_IN_AS_YOU_HAVE_IN_YOUR_DISCORDSRV_CONFIGURATION_FILE_CHECK_ELITEMOBS_WIKI_FOR_DETAILS")) + return; + + try { + //Initialize which room will be used regardless of whether it's using config name, id or discord room name + if (!isInitialized) { + if (textChannel == null) + textChannel = DiscordUtil.getTextChannelById(DiscordSRVConfig.getAnnouncementRoomName()); + + if (textChannel == null) + textChannel = DiscordSRV.getPlugin().getDestinationTextChannelForGameChannelName(DiscordSRVConfig.getAnnouncementRoomName()); + + if (textChannel == null && !DiscordUtil.getJda().getTextChannelsByName(DiscordSRVConfig.getAnnouncementRoomName(), true).isEmpty()) + textChannel = DiscordUtil.getJda().getTextChannelsByName(DiscordSRVConfig.getAnnouncementRoomName(), true).get(0); + + isInitialized = true; + } + + if (textChannel != null) + textChannel.sendMessage(ChatColor.stripColor(announcement)).queue(); + else + new WarningMessage("Channel room " + DiscordSRVConfig.getAnnouncementRoomName() + " is not valid!"); + + } catch (Exception ex) { + new WarningMessage("Failed to send announcement via DiscordsSRV! Is it configured correctly?"); + } + + } + + +} diff --git a/src/main/java/com/magmaguy/elitemobs/thirdparty/geyser/GeyserDetector.java b/src/main/java/com/magmaguy/elitemobs/thirdparty/geyser/GeyserDetector.java new file mode 100644 index 000000000..43292e35e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/thirdparty/geyser/GeyserDetector.java @@ -0,0 +1,12 @@ +package com.magmaguy.elitemobs.thirdparty.geyser; + +import org.bukkit.entity.Player; + +public class GeyserDetector { + + public static boolean bedrockPlayer(Player player) { + //This is where I would detect if this is a bedrock player if Geyser didn't require 1.16 and actually had an all-in-one way of letting me know if it's a bedrock client + //maintained because hope is the last one to die, will be replaced with something that works... some day + return false; + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/thirdparty/libsdisguises/DisguiseEntity.java b/src/main/java/com/magmaguy/elitemobs/thirdparty/libsdisguises/DisguiseEntity.java new file mode 100644 index 000000000..799540c83 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/thirdparty/libsdisguises/DisguiseEntity.java @@ -0,0 +1,110 @@ +package com.magmaguy.elitemobs.thirdparty.libsdisguises; + +import com.magmaguy.elitemobs.utils.WarningMessage; +import me.libraryaddict.disguise.DisguiseAPI; +import me.libraryaddict.disguise.DisguiseConfig; +import me.libraryaddict.disguise.disguisetypes.*; +import me.libraryaddict.disguise.disguisetypes.watchers.PlayerWatcher; +import org.bukkit.Bukkit; +import org.bukkit.entity.Entity; + +public class DisguiseEntity { + + public static void initialize() { + DisguiseConfig.setPlayerNameType(DisguiseConfig.PlayerNameType.ARMORSTANDS); + } + + /** + * This method disguises the entity based on a config entry. It should be invoked after checking if libsdisguises + * is in the server. + * + * @param disguiseName Raw name following config format + */ + public static void disguise(String disguiseName, Entity entity, String customDisguiseData, String filename) { + + if (disguiseName.contains("player:")) { + playerDisguise(disguiseName.replace("player:", ""), entity); + return; + } + + if (disguiseName.contains("custom")) { + try { + customDisguise(disguiseName.replace("custom:", ""), entity, customDisguiseData, filename); + } catch (Exception ex) { + new WarningMessage("Failed to assign custom disguise " + disguiseName + "! Did you configure the disguise correctly?"); + } + return; + } + + DisguiseType disguiseType; + + try { + disguiseType = DisguiseType.valueOf(disguiseName); + } catch (Exception ex) { + new WarningMessage("Disguise " + disguiseName + " is not a valid disguise name! Entity " + entity.getCustomName() + " will not have a disguise."); + return; + } + + if (disguiseType.isMob()) + livingEntityDisguise(disguiseType, entity); + else if (disguiseType.isMisc()) + miscEntityDisguise(disguiseType, entity); + else + new WarningMessage("Disguise " + disguiseName + " is not a valid disguise name! Entity " + entity.getCustomName() + " will not have a disguise."); + } + + private static void playerDisguise(String playerName, Entity entity) { + PlayerDisguise playerDisguise = new PlayerDisguise(playerName); + playerDisguise.setEntity(entity); + playerDisguise.setName(entity.getCustomName()); + playerDisguise.setDynamicName(true); + playerDisguise.startDisguise(); + } + + private static void livingEntityDisguise(DisguiseType disguiseType, Entity entity) { + MobDisguise mobDisguise = new MobDisguise(disguiseType); + mobDisguise.setEntity(entity); + mobDisguise.setDisguiseName(entity.getCustomName()); + mobDisguise.setDynamicName(true); + mobDisguise.startDisguise(); + } + + private static void miscEntityDisguise(DisguiseType disguiseType, Entity entity) { + MiscDisguise miscDisguise = new MiscDisguise(disguiseType); + miscDisguise.setDisguiseName(entity.getCustomName()); + miscDisguise.setDynamicName(true); + miscDisguise.setEntity(entity); + miscDisguise.startDisguise(); + } + + private static void customDisguise(String customDisguise, Entity entity, String customDisguiseData, String filename) { + Disguise disguise = DisguiseAPI.getCustomDisguise(customDisguise); + try { + if (disguise == null) + if (customDisguiseData != null) { + DisguiseAPI.addCustomDisguise(customDisguise, customDisguiseData); + disguise = DisguiseAPI.getCustomDisguise(customDisguise); + } + if (disguise == null) + throw new NullPointerException(); + disguise.setEntity(entity); + disguise.setDisguiseName(entity.getCustomName()); + disguise.setDynamicName(true); + disguise.startDisguise(); + } catch (Exception ex) { + new WarningMessage("Failed to set custom disguise for " + filename + " !"); + new WarningMessage("Does the disguise exist? Is LibsDisguises up-to-date?"); + } + } + + public static void setDisguiseNameVisibility(boolean disguiseNameVisibility, Entity entity) { + if (!Bukkit.getPluginManager().isPluginEnabled("LibsDisguises")) return; + Disguise disguise = DisguiseAPI.getDisguise(entity); + if (disguise == null) return; + if (!(disguise.getWatcher() instanceof PlayerWatcher)) return; + PlayerWatcher playerWatcher = (PlayerWatcher) disguise.getWatcher(); + playerWatcher.setNameVisible(disguiseNameVisibility); + playerWatcher.setCustomNameVisible(disguiseNameVisibility); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/thirdparty/modelengine/CustomModel.java b/src/main/java/com/magmaguy/elitemobs/thirdparty/modelengine/CustomModel.java new file mode 100644 index 000000000..d4e88fd3e --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/thirdparty/modelengine/CustomModel.java @@ -0,0 +1,132 @@ +package com.magmaguy.elitemobs.thirdparty.modelengine; + +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import com.magmaguy.elitemobs.utils.InfoMessage; +import com.magmaguy.elitemobs.utils.WarningMessage; +import com.ticxo.modelengine.api.ModelEngineAPI; +import com.ticxo.modelengine.api.model.ActiveModel; +import com.ticxo.modelengine.api.model.ModeledEntity; +import lombok.Getter; +import org.bukkit.entity.LivingEntity; +import org.bukkit.entity.Projectile; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.EntityDamageByEntityEvent; +import org.bukkit.event.entity.EntitySpawnEvent; + +public class CustomModel { + + ActiveModel activeModel; + ModeledEntity modeledEntity; + @Getter + private boolean success = false; + + + private CustomModel(LivingEntity livingEntity, String modelName, String nametagName) { + + try { + if (ModelEngineAPI.api.getModelManager().getModelRegistry().getModelBlueprint(modelName) == null) + new InfoMessage("Model " + modelName + " was not found! Make sure you install the model correctly if you have it. This entry will be skipped!"); + } catch (NoSuchMethodError ex) { + new WarningMessage("Model Engine API version is not supported. Currently Elitemobs can only support ModelEngine R2.5.0, documentation for other versions doesn't exist."); + } + + activeModel = ModelEngineAPI.api.getModelManager().createActiveModel(modelName); + + if (activeModel == null || activeModel.getModelId() == null) { + new WarningMessage("Failed to load model from " + modelName + " ! Is the model name correct, and has the model been installed correctly?"); + return; + } + + modeledEntity = ModelEngineAPI.api.getModelManager().createModeledEntity(livingEntity); + + if (modeledEntity == null) { + new WarningMessage("Failed to create model entity " + modelName + " ! Is the model name correct, and has the model been installed correctly?"); + return; + } + + try { + modeledEntity.addActiveModel(activeModel); + modeledEntity.detectPlayers(); + modeledEntity.setInvisible(true); + setName(nametagName, true); + success = true; + } catch (Exception exception) { + modeledEntity.removeModel(modelName); + new WarningMessage("Failed to make model entity " + modelName + " ! Is the model name correct, and has the model been installed correctly?"); + exception.printStackTrace(); + } + + } + + public static CustomModel generateCustomModel(LivingEntity livingEntity, String modelName, String nametagName) { + CustomModel customModel = new CustomModel(livingEntity, modelName, nametagName); + return customModel.isSuccess() ? customModel : null; + } + + public static void reloadModels() { + try { + ModelEngineAPI.api.getModelManager().registerModels(); + } catch (Exception ex) { + new WarningMessage("Model Engine API version is not supported. Currently Elitemobs can only support ModelEngine R2.5.0, documentation for other versions doesn't exist."); + } + } + + public void shoot() { + if (activeModel == null) return; + if (activeModel.getState("attack_ranged") != null) + activeModel.addState("attack_ranged", 1, 1, 1); + else + activeModel.addState("attack", 1, 1, 1); + } + + public void melee() { + if (activeModel == null) return; + if (activeModel.getState("attack_melee") != null) + activeModel.addState("attack_melee", 1, 1, 1); + else + activeModel.addState("attack", 1, 1, 1); + } + + public void setName(String nametagName, boolean visible) { + if (modeledEntity == null) return; + /* + modeledEntity.setNametag(nametagName); + modeledEntity.setNametagVisible(visible); + */ + modeledEntity.getNametagHandler().setCustomName("hitbox", nametagName); + modeledEntity.getNametagHandler().setCustomNameVisibility("hitbox", true); + + } + + public void switchPhase() { + activeModel.removeState("death", true); + } + + public void setNameVisible(boolean visible) { + // modeledEntity.setNametagVisible(visible); + modeledEntity.getNametagHandler().setCustomNameVisibility("hitbox", visible); + } + + public static class ModelEntityEvents implements Listener { + @EventHandler + public void onMeleeHit(EntityDamageByEntityEvent event) { + EliteEntity eliteEntity = EntityTracker.getEliteMobEntity(event.getDamager()); + if (!(eliteEntity instanceof CustomBossEntity)) return; + if (((CustomBossEntity) eliteEntity).getCustomModel() == null) return; + ((CustomBossEntity) eliteEntity).getCustomModel().melee(); + } + + @EventHandler + public void onRangedShot(EntitySpawnEvent event) { + if (!(event.getEntity() instanceof Projectile)) return; + if (!(((Projectile) event.getEntity()).getShooter() instanceof LivingEntity)) return; + EliteEntity eliteEntity = EntityTracker.getEliteMobEntity((LivingEntity) ((Projectile) event.getEntity()).getShooter()); + if (!(eliteEntity instanceof CustomBossEntity)) return; + if (((CustomBossEntity) eliteEntity).getCustomModel() == null) return; + ((CustomBossEntity) eliteEntity).getCustomModel().shoot(); + } + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/thirdparty/paper/PaperMC.java b/src/main/java/com/magmaguy/elitemobs/thirdparty/paper/PaperMC.java new file mode 100644 index 000000000..a405581a8 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/thirdparty/paper/PaperMC.java @@ -0,0 +1,23 @@ +package com.magmaguy.elitemobs.thirdparty.paper; + +import lombok.Getter; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +public class PaperMC { + @Getter + private static boolean paperMC = false; + + public static void initialize() { + try { + paperMC = Class.forName("com.destroystokyo.paper.VersionHistoryManager$VersionData") != null; + } catch (ClassNotFoundException e) { + Bukkit.getLogger().info("Not paper"); + } + } + + public static boolean checkClient(Player player) { + + return true; + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/thirdparty/placeholderapi/Placeholders.java b/src/main/java/com/magmaguy/elitemobs/thirdparty/placeholderapi/Placeholders.java new file mode 100644 index 000000000..b076026d2 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/thirdparty/placeholderapi/Placeholders.java @@ -0,0 +1,152 @@ +package com.magmaguy.elitemobs.thirdparty.placeholderapi; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.adventurersguild.GuildRank; +import com.magmaguy.elitemobs.config.AdventurersGuildConfig; +import com.magmaguy.elitemobs.economy.EconomyHandler; +import com.magmaguy.elitemobs.playerdata.ElitePlayerInventory; +import com.magmaguy.elitemobs.playerdata.database.PlayerData; +import com.magmaguy.elitemobs.utils.Round; +import me.clip.placeholderapi.expansion.PlaceholderExpansion; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; + +public class Placeholders extends PlaceholderExpansion { + + /** + * Because this is an internal class, + * you must override this method to let PlaceholderAPI know to not unregister your expansion class when + * PlaceholderAPI is reloaded + * + * @return true to persist through reloads + */ + @Override + public boolean persist() { + return true; + } + + /** + * Because this is a internal class, this check is not needed + * and we can simply return {@code true} + * + * @return Always true since it's an internal class. + */ + @Override + public boolean canRegister() { + return true; + } + + /** + * The name of the person who created this expansion should go here. + *
For convienience do we return the author from the plugin.yml + * + * @return The name of the author as a String. + */ + @Override + public String getAuthor() { + return MetadataHandler.PLUGIN.getDescription().getAuthors().toString(); + } + + /** + * The placeholder identifier should go here. + *
This is what tells PlaceholderAPI to call our onRequest + * method to obtain a value if a placeholder starts with our + * identifier. + *
This must be unique and can not contain % or _ + * + * @return The identifier in {@code %_%} as String. + */ + @Override + public String getIdentifier() { + return "elitemobs"; + } + + /** + * This is the version of the expansion. + *
You don't have to use numbers, since it is set as a String. + *

+ * For convienience do we return the version from the plugin.yml + * + * @return The version as a String. + */ + @Override + public String getVersion() { + return MetadataHandler.PLUGIN.getDescription().getVersion(); + } + + /** + * This is the method called when a placeholder with our identifier + * is found and needs a value. + *
We specify the value identifier in this method. + *
Since version 2.9.1 can you use OfflinePlayers in your requests. + * + * @param player A {@link org.bukkit.OfflinePlayer Player}. + * @param identifier A String containing the identifier/value. + * @return possibly-null String of the requested identifier. + */ + @Override + public String onPlaceholderRequest(Player player, String identifier) { + + if (player == null) + return "Only online players!"; + + /* + There is a weird bug with PAPI where, under certain circumstances, it seems to fail to see cached values and + queries the database. This is usually fine for something like chat, but it quickly becomes a massive issue for + tablists, scoreboards and other places that might display several placeholders simultaneously and update them + every tick, quickly racking up hundreds or thousands of queries per tick, on top of the normal runtime accesses + that EliteMobs does. At scale, this causes large issues. Hence, at least for now, PAPI does not have access to the + databases for safety purposes. All of the queries should be in memory regardless. + */ + + if (!PlayerData.isInMemory(player.getUniqueId())) + return "Uninitialized player data!"; + + switch (identifier) { + case "player_combat_tier": + return "" + ElitePlayerInventory.playerInventories.get(player.getUniqueId()).getFullPlayerTier(true); + case "player_active_guild_rank_numerical": + return "" + GuildRank.getActiveGuildRank(player, false); + case "player_maximum_guild_rank_numerical": + return "" + GuildRank.getMaxGuildRank(player, false); + case "player_active_guild_rank_name": + return GuildRank.getRankName(GuildRank.getGuildPrestigeRank(player, false), GuildRank.getActiveGuildRank(player, false)); + case "player_maximum_guild_rank_name": + return GuildRank.getRankName(GuildRank.getGuildPrestigeRank(player, false), GuildRank.getMaxGuildRank(player, false)); + case "player_prestige_guild_rank_numerical": + return "" + GuildRank.getGuildPrestigeRank(player, false); + case "player_money": + return "" + Round.twoDecimalPlaces(EconomyHandler.checkCurrency(player.getUniqueId())); + case "player_top_tier": + double highestThreat = 0; + for (Player iteratedPlayer : Bukkit.getOnlinePlayers()) { + double currentTier = ElitePlayerInventory.playerInventories.get(iteratedPlayer.getUniqueId()).getFullPlayerTier(true); + if (currentTier > highestThreat) + highestThreat = currentTier; + } + return "" + highestThreat; + case "player_top_guild_rank": + int highestGuildRank = 0; + String highestGuildUser = ""; + for (Player iteratedPlayer : Bukkit.getOnlinePlayers()) { + int currentGuildRank = GuildRank.getMaxGuildRank(iteratedPlayer, false); + if (currentGuildRank > highestGuildRank) { + highestGuildRank = currentGuildRank; + highestGuildUser = iteratedPlayer.getDisplayName(); + } + } + return highestGuildUser; + case "player_shortened_guild_rank": + return AdventurersGuildConfig.getShortenedRankName(GuildRank.getGuildPrestigeRank(player, false), GuildRank.getActiveGuildRank(player, false)); + case "player_kills": + return "" + PlayerData.getKills(player.getUniqueId()); + case "player_deaths": + return "" + PlayerData.getDeaths(player.getUniqueId()); + } + + // We return null if an invalid placeholder (f.e. %someplugin_placeholder3%) + // was provided + return null; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/thirdparty/worldguard/WorldGuardCompatibility.java b/src/main/java/com/magmaguy/elitemobs/thirdparty/worldguard/WorldGuardCompatibility.java new file mode 100644 index 000000000..b84035ba8 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/thirdparty/worldguard/WorldGuardCompatibility.java @@ -0,0 +1,362 @@ +package com.magmaguy.elitemobs.thirdparty.worldguard; + +import com.magmaguy.elitemobs.dungeons.Minidungeon; +import com.magmaguy.elitemobs.utils.WarningMessage; +import com.sk89q.worldedit.bukkit.BukkitAdapter; +import com.sk89q.worldedit.math.BlockVector3; +import com.sk89q.worldguard.WorldGuard; +import com.sk89q.worldguard.domains.DefaultDomain; +import com.sk89q.worldguard.protection.flags.Flags; +import com.sk89q.worldguard.protection.flags.IntegerFlag; +import com.sk89q.worldguard.protection.flags.StateFlag; +import com.sk89q.worldguard.protection.flags.registry.FlagConflictException; +import com.sk89q.worldguard.protection.flags.registry.FlagRegistry; +import com.sk89q.worldguard.protection.managers.RegionManager; +import com.sk89q.worldguard.protection.regions.GlobalProtectedRegion; +import com.sk89q.worldguard.protection.regions.ProtectedCuboidRegion; +import com.sk89q.worldguard.protection.regions.ProtectedRegion; +import com.sk89q.worldguard.protection.regions.RegionContainer; +import org.bukkit.Bukkit; +import org.bukkit.Location; + +import java.util.UUID; + +public class WorldGuardCompatibility { + + private static final StateFlag.State allow = StateFlag.State.ALLOW; + private static final StateFlag.State deny = StateFlag.State.DENY; + private static StateFlag ELITEMOBS_SPAWN_FLAG; + private static StateFlag ELITEMOBS_ONLY_SPAWN_FLAG; + private static StateFlag ELITEMOBS_ANTIEXPLOIT; + private static StateFlag ELITEMOBS_DUNGEON; + private static StateFlag ELITEMOBS_EVENTS; + private static IntegerFlag ELITEMOBS_MINIMUM_LEVEL; + private static IntegerFlag ELITEMOBS_MAXIMUM_LEVEL; + private static StateFlag ELITEMOBS_EXPLOSION_REGEN; + + public static boolean initialize() { + + //Enable WorldGuard + if (Bukkit.getPluginManager().getPlugin("WorldGuard") == null) + return false; + + Bukkit.getLogger().info("[EliteMobs] WorldGuard detected."); + + FlagRegistry registry = null; + + try { + registry = WorldGuard.getInstance().getFlagRegistry(); + } catch (Exception ex) { + new WarningMessage("Something went wrong while loading WorldGuard. Are you using the right WorldGuard version?"); + return false; + } + + Bukkit.getLogger().info("[EliteMobs] Enabling flags:"); + try { + ELITEMOBS_SPAWN_FLAG = new StateFlag("elitemob-spawning", true); + registry.register(ELITEMOBS_SPAWN_FLAG); + Bukkit.getLogger().info("[EliteMobs] - elitemob-spawning"); + } catch (FlagConflictException | IllegalStateException e) { + Bukkit.getLogger().warning("[EliteMobs] Warning: flag elitemob-spawning already exists! This is normal if you've just now reloaded EliteMobs."); + ELITEMOBS_SPAWN_FLAG = (StateFlag) registry.get("elitemob-spawning"); + } + try { + ELITEMOBS_ONLY_SPAWN_FLAG = new StateFlag("elitemob-only-spawning", false); + registry.register(ELITEMOBS_ONLY_SPAWN_FLAG); + Bukkit.getLogger().info("[EliteMobs] - elitemob-only-spawning"); + } catch (FlagConflictException | IllegalStateException e) { + Bukkit.getLogger().warning("[EliteMobs] Warning: flag elitemob-only-spawning already exists! This is normal if you've just now reloaded EliteMobs."); + ELITEMOBS_ONLY_SPAWN_FLAG = (StateFlag) registry.get("elitemob-only-spawning"); + } + try { + ELITEMOBS_ANTIEXPLOIT = new StateFlag("elitemobs-antiexploit", true); + registry.register(ELITEMOBS_ANTIEXPLOIT); + Bukkit.getLogger().info("[EliteMobs] - elitemobs-antiexploit"); + } catch (FlagConflictException | IllegalStateException e) { + Bukkit.getLogger().warning("[EliteMobs] Warning: flag elitemob-antiexploit already exists! This is normal if you've just now reloaded EliteMobs."); + ELITEMOBS_ANTIEXPLOIT = (StateFlag) registry.get("elitemobs-antiexploit"); + } + try { + ELITEMOBS_DUNGEON = new StateFlag("elitemobs-dungeon", false); + registry.register(ELITEMOBS_DUNGEON); + Bukkit.getLogger().info("[EliteMobs] - elitemobs-dungeon"); + } catch (FlagConflictException | IllegalStateException e) { + Bukkit.getLogger().warning("[EliteMobs] Warning: flag elitemob-dungeon already exists! This is normal if you've just now reloaded EliteMobs."); + ELITEMOBS_DUNGEON = (StateFlag) registry.get("elitemobs-dungeon"); + } + try { + ELITEMOBS_EVENTS = new StateFlag("elitemobs-events", true); + registry.register(ELITEMOBS_EVENTS); + Bukkit.getLogger().info("[EliteMobs] - elitemobs-events"); + } catch (FlagConflictException | IllegalStateException e) { + Bukkit.getLogger().warning("[EliteMobs] Warning: flag elitemob-events already exists! This is normal if you've just now reloaded EliteMobs."); + ELITEMOBS_EVENTS = (StateFlag) registry.get("elitemobs-events"); + } + try { + ELITEMOBS_MINIMUM_LEVEL = new IntegerFlag("elitemobs-minimum-level"); + registry.register(ELITEMOBS_MINIMUM_LEVEL); + Bukkit.getLogger().info("[EliteMobs] - elitemobs-minimum-level"); + } catch (FlagConflictException | IllegalStateException e) { + Bukkit.getLogger().warning("[EliteMobs] Warning: flag elitemob-minimum-level already exists! This is normal if you've just now reloaded EliteMobs."); + ELITEMOBS_MINIMUM_LEVEL = (IntegerFlag) registry.get("elitemobs-minimum-level"); + } + try { + ELITEMOBS_MAXIMUM_LEVEL = new IntegerFlag("elitemobs-maximum-level"); + registry.register(ELITEMOBS_MAXIMUM_LEVEL); + Bukkit.getLogger().info("[EliteMobs] - elitemobs-maximum-level"); + } catch (FlagConflictException | IllegalStateException e) { + Bukkit.getLogger().warning("[EliteMobs] Warning: flag elitemob-maximum-level already exists! This is normal if you've just now reloaded EliteMobs."); + ELITEMOBS_MAXIMUM_LEVEL = (IntegerFlag) registry.get("elitemobs-maximum-level"); + } + + try { + ELITEMOBS_EXPLOSION_REGEN = new StateFlag("elitemobs-explosion-regen", true); + registry.register(ELITEMOBS_EXPLOSION_REGEN); + Bukkit.getLogger().info("[EliteMobs] - elitemobs-explosion-regen"); + } catch (FlagConflictException | IllegalStateException e) { + Bukkit.getLogger().warning("[EliteMobs] Warning: flag elitemob-explosion-regen already exists! This is normal if you've just now reloaded EliteMobs."); + ELITEMOBS_EXPLOSION_REGEN = (StateFlag) registry.get("elitemobs-explosion-regen"); + } + + return true; + + } + + public static final StateFlag getEliteMobsSpawnFlag() { + return ELITEMOBS_SPAWN_FLAG; + } + + public static final StateFlag getEliteMobsOnlySpawnFlag() { + return ELITEMOBS_ONLY_SPAWN_FLAG; + } + + public static final StateFlag getEliteMobsAntiExploitFlag() { + return ELITEMOBS_ANTIEXPLOIT; + } + + public static final StateFlag getEliteMobsDungeonFlag() { + return ELITEMOBS_DUNGEON; + } + + public static final StateFlag getEliteMobsEventsFlag() { + return ELITEMOBS_EVENTS; + } + + public static final IntegerFlag getEliteMobsMinimumLevel() { + return ELITEMOBS_MINIMUM_LEVEL; + } + + public static final IntegerFlag getEliteMobsMaximumLevel() { + return ELITEMOBS_MAXIMUM_LEVEL; + } + + public static final StateFlag getEliteMobsExplosionRegen() { + return ELITEMOBS_EXPLOSION_REGEN; + } + + public static void protectWorldMinidugeonArea(Location location, Minidungeon minidungeon) { + try { + RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer(); + RegionManager regions = container.get(BukkitAdapter.adapt(location.getWorld())); + ProtectedRegion global = regions.getRegion("__global__"); + + if (global == null) { + // But we want a __global__, so let's create one + global = new GlobalProtectedRegion("__global__"); + regions.addRegion(global); + } + + protectMinidungeonArea(global, minidungeon); + DefaultDomain members = global.getMembers(); + members.addPlayer(UUID.fromString("198c4123-cafc-45df-ba79-02a421eb8ce7")); + global.setOwners(members); + } catch (Exception ex) { + new WarningMessage("Failed to protect minidungeon world area!"); + } + } + + public static void protectWorldMinidugeonArea(Location location) { + try { + RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer(); + RegionManager regions = container.get(BukkitAdapter.adapt(location.getWorld())); + ProtectedRegion global = regions.getRegion("__global__"); + + if (global == null) { + // But we want a __global__, so let's create one + global = new GlobalProtectedRegion("__global__"); + regions.addRegion(global); + } + + protectMinidungeonArea(global); + DefaultDomain members = global.getMembers(); + members.addPlayer(UUID.fromString("198c4123-cafc-45df-ba79-02a421eb8ce7")); + global.setOwners(members); + } catch (Exception ex) { + new WarningMessage("Failed to protect minidungeon world area!"); + } + } + + public static boolean protectMinidungeonArea(String regionName, Location location, Minidungeon minidungeon) { + try { + RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer(); + RegionManager regions = container.get(BukkitAdapter.adapt(location.getWorld())); + ProtectedRegion protectedRegion = regions.getRegion(regionName); + if (protectedRegion == null) { + new WarningMessage("The region name picked did not exist!"); + return false; + } + protectMinidungeonArea(protectedRegion, minidungeon); + return true; + } catch (Exception ex) { + new WarningMessage("Failed to protect region " + regionName + " !"); + return false; + } + } + + public static void protectMinidungeonArea(ProtectedRegion protectedRegion, Minidungeon minidungeon) { + //elitemobs events + protectedRegion.setFlag(ELITEMOBS_DUNGEON, allow); + protectedRegion.setFlag(ELITEMOBS_ANTIEXPLOIT, deny); + protectedRegion.setFlag(ELITEMOBS_EVENTS, deny); + //WG events + protectedRegion.setFlag(Flags.INTERACT, deny); + protectedRegion.setFlag(Flags.CREEPER_EXPLOSION, deny); + protectedRegion.setFlag(Flags.FIRE_SPREAD, deny); + protectedRegion.setFlag(Flags.LAVA_FIRE, deny); + protectedRegion.setFlag(Flags.LAVA_FLOW, deny); + protectedRegion.setFlag(Flags.SNOW_FALL, deny); + protectedRegion.setFlag(Flags.SNOW_MELT, deny); + protectedRegion.setFlag(Flags.ICE_FORM, deny); + protectedRegion.setFlag(Flags.ICE_MELT, deny); + protectedRegion.setFlag(Flags.FROSTED_ICE_FORM, deny); + protectedRegion.setFlag(Flags.FROSTED_ICE_MELT, deny); + protectedRegion.setFlag(Flags.LEAF_DECAY, deny); + protectedRegion.setFlag(Flags.GRASS_SPREAD, deny); + protectedRegion.setFlag(Flags.MYCELIUM_SPREAD, deny); + protectedRegion.setFlag(Flags.CROP_GROWTH, deny); + protectedRegion.setFlag(Flags.SOIL_DRY, deny); + //missing coral-fade + //missing ravager-grief + protectedRegion.setFlag(Flags.GHAST_FIREBALL, deny); + protectedRegion.setFlag(Flags.WITHER_DAMAGE, deny); + protectedRegion.setFlag(Flags.ENDER_BUILD, deny); + protectedRegion.setFlag(Flags.ITEM_FRAME_ROTATE, deny); + protectedRegion.setFlag(Flags.PLACE_VEHICLE, deny); + protectedRegion.setFlag(Flags.DESTROY_VEHICLE, deny); + protectedRegion.setFlag(Flags.PVP, deny); + protectedRegion.setFlag(Flags.OTHER_EXPLOSION, deny); + protectedRegion.setFlag(Flags.TRAMPLE_BLOCKS, deny); + protectedRegion.setFlag(Flags.VINE_GROWTH, deny); + protectedRegion.setFlag(Flags.MUSHROOMS, deny); + protectedRegion.setFlag(Flags.DAMAGE_ANIMALS, allow); + protectedRegion.setFlag(Flags.SLEEP, deny); + protectedRegion.setFlag(Flags.CHEST_ACCESS, allow); + protectedRegion.setFlag(Flags.ENTITY_ITEM_FRAME_DESTROY, deny); + protectedRegion.setFlag(Flags.ENTITY_PAINTING_DESTROY, deny); + protectedRegion.setFlag(Flags.MOB_SPAWNING, allow); + protectedRegion.setFlag(Flags.TNT, deny); + protectedRegion.setFlag(Flags.ENDERDRAGON_BLOCK_DAMAGE, deny); + protectedRegion.setFlag(Flags.LIGHTER, deny); + protectedRegion.setFlag(Flags.ENDERPEARL, deny); + protectedRegion.setFlag(Flags.GREET_MESSAGE, minidungeon.getDungeonPackagerConfigFields().getRegionEnterMessage()); + protectedRegion.setFlag(Flags.FAREWELL_MESSAGE, minidungeon.getDungeonPackagerConfigFields().getRegionLeaveMessage()); + } + + public static boolean protectMinidungeonArea(String regionName, Location location) { + try { + RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer(); + RegionManager regions = container.get(BukkitAdapter.adapt(location.getWorld())); + ProtectedRegion protectedRegion = regions.getRegion(regionName); + if (protectedRegion == null) { + new WarningMessage("The region name picked did not exist!"); + return false; + } + protectMinidungeonArea(protectedRegion); + return true; + } catch (Exception ex) { + new WarningMessage("Failed to protect region " + regionName + " !"); + return false; + } + } + + public static void protectMinidungeonArea(ProtectedRegion protectedRegion) { + //elitemobs events + protectedRegion.setFlag(ELITEMOBS_DUNGEON, allow); + protectedRegion.setFlag(ELITEMOBS_ANTIEXPLOIT, deny); + protectedRegion.setFlag(ELITEMOBS_EVENTS, deny); + //WG events + protectedRegion.setFlag(Flags.INTERACT, deny); + protectedRegion.setFlag(Flags.CREEPER_EXPLOSION, deny); + protectedRegion.setFlag(Flags.FIRE_SPREAD, deny); + protectedRegion.setFlag(Flags.LAVA_FIRE, deny); + protectedRegion.setFlag(Flags.LAVA_FLOW, deny); + protectedRegion.setFlag(Flags.SNOW_FALL, deny); + protectedRegion.setFlag(Flags.SNOW_MELT, deny); + protectedRegion.setFlag(Flags.ICE_FORM, deny); + protectedRegion.setFlag(Flags.ICE_MELT, deny); + protectedRegion.setFlag(Flags.FROSTED_ICE_FORM, deny); + protectedRegion.setFlag(Flags.FROSTED_ICE_MELT, deny); + protectedRegion.setFlag(Flags.LEAF_DECAY, deny); + protectedRegion.setFlag(Flags.GRASS_SPREAD, deny); + protectedRegion.setFlag(Flags.MYCELIUM_SPREAD, deny); + protectedRegion.setFlag(Flags.CROP_GROWTH, deny); + protectedRegion.setFlag(Flags.SOIL_DRY, deny); + //missing coral-fade + //missing ravager-grief + protectedRegion.setFlag(Flags.GHAST_FIREBALL, deny); + protectedRegion.setFlag(Flags.WITHER_DAMAGE, deny); + protectedRegion.setFlag(Flags.ENDER_BUILD, deny); + protectedRegion.setFlag(Flags.ITEM_FRAME_ROTATE, deny); + protectedRegion.setFlag(Flags.PLACE_VEHICLE, deny); + protectedRegion.setFlag(Flags.DESTROY_VEHICLE, deny); + protectedRegion.setFlag(Flags.PVP, deny); + protectedRegion.setFlag(Flags.OTHER_EXPLOSION, deny); + protectedRegion.setFlag(Flags.TRAMPLE_BLOCKS, deny); + protectedRegion.setFlag(Flags.VINE_GROWTH, deny); + protectedRegion.setFlag(Flags.MUSHROOMS, deny); + protectedRegion.setFlag(Flags.DAMAGE_ANIMALS, allow); + protectedRegion.setFlag(Flags.SLEEP, deny); + protectedRegion.setFlag(Flags.CHEST_ACCESS, allow); + protectedRegion.setFlag(Flags.ENTITY_ITEM_FRAME_DESTROY, deny); + protectedRegion.setFlag(Flags.ENTITY_PAINTING_DESTROY, deny); + protectedRegion.setFlag(Flags.MOB_SPAWNING, allow); + protectedRegion.setFlag(Flags.TNT, deny); + protectedRegion.setFlag(Flags.ENDERDRAGON_BLOCK_DAMAGE, deny); + protectedRegion.setFlag(Flags.LIGHTER, deny); + protectedRegion.setFlag(Flags.ENDERPEARL, deny); + protectedRegion.setFlag(Flags.BLOCK_PLACE, deny); + protectedRegion.setFlag(Flags.BLOCK_BREAK, deny); + } + + /** + * Automatically creates a worldguard region protected as an EliteMobs minidungeon using two x y z vectors for the + * locations of the diagonally opposed locations + * + * @param corner1 + * @param corner2 + */ + public static void defineMinidungeon(Location corner1, Location corner2, Location anchorLocation, String schematicName, Minidungeon minidungeon) { + try { + RegionContainer regionContainer = WorldGuard.getInstance().getPlatform().getRegionContainer(); + RegionManager regionManager = regionContainer.get(BukkitAdapter.adapt(anchorLocation.getWorld())); + BlockVector3 min = BlockVector3.at(corner1.getBlockX(), corner1.getBlockY(), corner1.getBlockZ()); + BlockVector3 max = BlockVector3.at(corner2.getBlockX(), corner2.getBlockY(), corner2.getBlockZ()); + ProtectedRegion region = new ProtectedCuboidRegion(schematicName.replace(".schem", ""), min, max); + protectMinidungeonArea(region, minidungeon); + regionManager.addRegion(region); + } catch (Exception ex) { + new WarningMessage("Failed to add Minidungeon WorldGuard zone!"); + } + } + + public static void removeMinidungeon(String schematicName, Location anchorLocation) { + try { + RegionContainer regionContainer = WorldGuard.getInstance().getPlatform().getRegionContainer(); + RegionManager regionManager = regionContainer.get(BukkitAdapter.adapt(anchorLocation.getWorld())); + regionManager.removeRegion(schematicName.replace(".schem", "")); + } catch (Exception ex) { + new WarningMessage("Failed to remove Minidungeon WorldGuard zone!"); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/thirdparty/worldguard/WorldGuardDungeonFlag.java b/src/main/java/com/magmaguy/elitemobs/thirdparty/worldguard/WorldGuardDungeonFlag.java new file mode 100644 index 000000000..ddda7eb47 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/thirdparty/worldguard/WorldGuardDungeonFlag.java @@ -0,0 +1,29 @@ +package com.magmaguy.elitemobs.thirdparty.worldguard; + +import com.magmaguy.elitemobs.EliteMobs; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.mobconstructor.EliteEntity; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import org.bukkit.entity.EntityType; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.CreatureSpawnEvent; + +public class WorldGuardDungeonFlag implements Listener { + + @EventHandler(ignoreCancelled = true) + public void onSpawn(CreatureSpawnEvent event) { + if (!EliteMobs.worldGuardIsEnabled) return; + if (event.getEntity().getType().equals(EntityType.ARMOR_STAND) || + event.getSpawnReason().equals(CreatureSpawnEvent.SpawnReason.CUSTOM)) + return; + if (WorldGuardFlagChecker.checkFlag(event.getLocation(), WorldGuardCompatibility.getEliteMobsDungeonFlag())) { + EliteEntity eliteEntity = EntityTracker.getEliteMobEntity(event.getEntity()); + if (eliteEntity instanceof CustomBossEntity) + return; + event.setCancelled(true); + event.getEntity().remove(); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/thirdparty/worldguard/WorldGuardEliteMobOnlySpawnFlag.java b/src/main/java/com/magmaguy/elitemobs/thirdparty/worldguard/WorldGuardEliteMobOnlySpawnFlag.java new file mode 100644 index 000000000..eed8485ca --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/thirdparty/worldguard/WorldGuardEliteMobOnlySpawnFlag.java @@ -0,0 +1,26 @@ +package com.magmaguy.elitemobs.thirdparty.worldguard; + +import com.magmaguy.elitemobs.EliteMobs; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import org.bukkit.entity.EntityType; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.CreatureSpawnEvent; + +public class WorldGuardEliteMobOnlySpawnFlag implements Listener { + + @EventHandler(priority = EventPriority.HIGHEST) + public void onSpawn(CreatureSpawnEvent event) { + if (!EliteMobs.worldGuardIsEnabled) return; + if (event.getEntity().getType().equals(EntityType.ARMOR_STAND) || + event.getEntity().getType().equals(EntityType.VILLAGER) && event.getSpawnReason().equals(CreatureSpawnEvent.SpawnReason.CUSTOM)) + return; + if (WorldGuardFlagChecker.checkFlag(event.getLocation(), WorldGuardCompatibility.getEliteMobsOnlySpawnFlag())) { + if (EntityTracker.isEliteMob(event.getEntity())) return; + event.setCancelled(true); + event.getEntity().remove(); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/thirdparty/worldguard/WorldGuardFlagChecker.java b/src/main/java/com/magmaguy/elitemobs/thirdparty/worldguard/WorldGuardFlagChecker.java new file mode 100644 index 000000000..7127c7df9 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/thirdparty/worldguard/WorldGuardFlagChecker.java @@ -0,0 +1,80 @@ +package com.magmaguy.elitemobs.thirdparty.worldguard; + +import com.sk89q.worldedit.bukkit.BukkitAdapter; +import com.sk89q.worldguard.WorldGuard; +import com.sk89q.worldguard.protection.ApplicableRegionSet; +import com.sk89q.worldguard.protection.flags.Flag; +import com.sk89q.worldguard.protection.flags.Flags; +import com.sk89q.worldguard.protection.flags.StateFlag; +import com.sk89q.worldguard.protection.regions.RegionContainer; +import com.sk89q.worldguard.protection.regions.RegionQuery; +import org.bukkit.Location; + +import javax.annotation.Nullable; + +public class WorldGuardFlagChecker { + + private WorldGuardFlagChecker() { + } + + public static boolean checkFlag(Location location, StateFlag stateFlag) { + com.sk89q.worldedit.util.Location wgLocation = BukkitAdapter.adapt(location); + RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer(); + RegionQuery query = container.createQuery(); + ApplicableRegionSet set = query.getApplicableRegions(wgLocation); + return set.testState(null, stateFlag); + } + + @Nullable + public static Integer getIntegerFlagValue(Location location, Flag flag) { + com.sk89q.worldedit.util.Location wgLocation = BukkitAdapter.adapt(location); + RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer(); + RegionQuery query = container.createQuery(); + ApplicableRegionSet set = query.getApplicableRegions(wgLocation); + Object object = set.queryValue(null, flag); + return object == null ? null : (Integer) object; + } + + @Nullable + public static Integer getRegionMinimumLevel(Location location) { + return WorldGuardFlagChecker.getIntegerFlagValue(location, WorldGuardCompatibility.getEliteMobsMinimumLevel()); + } + + @Nullable + public static Integer getRegionMaximumLevel(Location location) { + return WorldGuardFlagChecker.getIntegerFlagValue(location, WorldGuardCompatibility.getEliteMobsMaximumLevel()); + } + + public static boolean doExplosionRegenFlag(Location location) { + com.sk89q.worldedit.util.Location wgLocation = BukkitAdapter.adapt(location); + RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer(); + RegionQuery query = container.createQuery(); + ApplicableRegionSet set = query.getApplicableRegions(wgLocation); + return set.testState(null, WorldGuardCompatibility.getEliteMobsExplosionRegen()); + } + + public static boolean doEventFlag(Location location) { + com.sk89q.worldedit.util.Location wgLocation = BukkitAdapter.adapt(location); + RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer(); + RegionQuery query = container.createQuery(); + ApplicableRegionSet set = query.getApplicableRegions(wgLocation); + return set.testState(null, WorldGuardCompatibility.getEliteMobsEventsFlag()); + } + + public static boolean doEliteMobsSpawnFlag(Location location) { + com.sk89q.worldedit.util.Location wgLocation = BukkitAdapter.adapt(location); + RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer(); + RegionQuery query = container.createQuery(); + ApplicableRegionSet set = query.getApplicableRegions(wgLocation); + return set.testState(null, WorldGuardCompatibility.getEliteMobsSpawnFlag()); + } + + public static boolean doMobSpawnFlag(Location location) { + com.sk89q.worldedit.util.Location wgLocation = BukkitAdapter.adapt(location); + RegionContainer container = WorldGuard.getInstance().getPlatform().getRegionContainer(); + RegionQuery query = container.createQuery(); + ApplicableRegionSet set = query.getApplicableRegions(wgLocation); + return set.testState(null, Flags.MOB_SPAWNING); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/thirdparty/worldguard/WorldGuardSpawnEventBypasser.java b/src/main/java/com/magmaguy/elitemobs/thirdparty/worldguard/WorldGuardSpawnEventBypasser.java new file mode 100644 index 000000000..6db8572fb --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/thirdparty/worldguard/WorldGuardSpawnEventBypasser.java @@ -0,0 +1,27 @@ +package com.magmaguy.elitemobs.thirdparty.worldguard; + +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.entity.CreatureSpawnEvent; + +public class WorldGuardSpawnEventBypasser implements Listener { + + private static boolean force = false; + + public static void forceSpawn() { + force = true; + } + + public static boolean isForcedSpawn() { + return force; + } + + @EventHandler(priority = EventPriority.HIGHEST) + public void onSpawn(CreatureSpawnEvent event) { + if (!force) return; + event.setCancelled(false); + force = false; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/treasurechest/TreasureChest.java b/src/main/java/com/magmaguy/elitemobs/treasurechest/TreasureChest.java new file mode 100644 index 000000000..00d65ced0 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/treasurechest/TreasureChest.java @@ -0,0 +1,267 @@ +package com.magmaguy.elitemobs.treasurechest; + +import com.google.common.collect.ArrayListMultimap; +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.adventurersguild.GuildRank; +import com.magmaguy.elitemobs.config.TranslationConfig; +import com.magmaguy.elitemobs.config.customtreasurechests.CustomTreasureChestConfigFields; +import com.magmaguy.elitemobs.config.customtreasurechests.CustomTreasureChestsConfig; +import com.magmaguy.elitemobs.mobconstructor.custombosses.CustomBossEntity; +import com.magmaguy.elitemobs.utils.InfoMessage; +import com.magmaguy.elitemobs.utils.Round; +import com.magmaguy.elitemobs.utils.WarningMessage; +import com.magmaguy.elitemobs.utils.WeightedProbability; +import lombok.Getter; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Material; +import org.bukkit.block.data.Directional; +import org.bukkit.entity.Player; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.block.BlockBreakEvent; +import org.bukkit.event.player.PlayerInteractEvent; +import org.bukkit.event.world.WorldLoadEvent; +import org.bukkit.event.world.WorldUnloadEvent; +import org.bukkit.scheduler.BukkitRunnable; + +import java.time.Instant; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; +import java.util.concurrent.ThreadLocalRandom; + +public class TreasureChest { + + @Getter + private static ArrayListMultimap unloadedChests = ArrayListMultimap.create(); + private static HashMap treasureChestHashMap = new HashMap<>(); + @Getter + private final CustomTreasureChestConfigFields customTreasureChestConfigFields; + @Getter + private final Location location; + private long restockTime; + + public TreasureChest(CustomTreasureChestConfigFields customTreasureChestConfigFields, Location location, long restockTime) { + this.customTreasureChestConfigFields = customTreasureChestConfigFields; + this.location = location; + this.restockTime = restockTime; + if (!customTreasureChestConfigFields.isEnabled()) + return; + + if (customTreasureChestConfigFields.getChestMaterial() == null) + return; + + if (location == null) + return; + + if (location.getWorld() == null) { + unloadedChests.put(customTreasureChestConfigFields.getWorldName(), this); + return; + } else + try { + location.getChunk().load(); + } catch (Exception ex) { + new InfoMessage("Location for treasure chest " + customTreasureChestConfigFields.getFilename() + " is not loaded, so a treasure chest will not be placed!"); + new WarningMessage(ex.getMessage()); + return; + } + + long time = (restockTime - Instant.now().getEpochSecond()) * 20L; + if (time < 0) + generateChest(); + else + Bukkit.getScheduler().scheduleSyncDelayedTask(MetadataHandler.PLUGIN, this::generateChest, time); + + treasureChestHashMap.put(location, this); + + } + + public static void clearTreasureChests() { + unloadedChests.clear(); + treasureChestHashMap.clear(); + } + + public static HashMap getTreasureChestHashMap() { + return treasureChestHashMap; + } + + public static TreasureChest getTreasureChest(Location location) { + return getTreasureChestHashMap().get(location); + } + + private void generateChest() { + try { + if (!location.getWorld() + .getBlockAt(location).getType().equals(customTreasureChestConfigFields.getChestMaterial())) + location.getWorld().getBlockAt(location).setType(customTreasureChestConfigFields.getChestMaterial()); + } catch (Exception ex) { + new WarningMessage("Custom Treasure Chest " + customTreasureChestConfigFields.getFilename() + " has an invalid location and can not be placed."); + return; + } + if (location.getBlock().getBlockData() instanceof Directional) { + Directional chest = (Directional) location.getBlock().getBlockData(); + chest.setFacing(customTreasureChestConfigFields.getFacing()); + location.getBlock().setBlockData(chest); + } else { + new WarningMessage("Treasure chest " + customTreasureChestConfigFields.getFilename() + + " does not have a directional block for the Treasure Chest material " + + customTreasureChestConfigFields.getChestMaterial() + " ! Chest materials are directional, is your chest a chest?"); + } + location.getBlock().getState().update(); + } + + public void doInteraction(Player player) { + + if (customTreasureChestConfigFields.getDropStyle().equals(DropStyle.GROUP)) + if (playerIsInCooldown(player)) { + groupTimerCooldownMessage(player, getPlayerCooldown(player)); + return; + } + + if (ThreadLocalRandom.current().nextDouble() < customTreasureChestConfigFields.getMimicChance()) + doMimic(); + else + doTreasure(player); + + if (customTreasureChestConfigFields.getDropStyle().equals(DropStyle.GROUP)) { + customTreasureChestConfigFields.getRestockTimers().add(cooldownStringConstructor(player)); + new BukkitRunnable() { + @Override + public void run() { + customTreasureChestConfigFields.getRestockTimers().removeIf(restockTime -> restockTime.split(":")[0].equals(player.getUniqueId().toString())); + } + }.runTaskLater(MetadataHandler.PLUGIN, 20L * 60 * customTreasureChestConfigFields.getRestockTimer()); + return; + } + + location.getBlock().setType(Material.AIR); + + restockTime = cooldownTime(); + customTreasureChestConfigFields.setRestockTime(location, restockTime); + + Bukkit.getScheduler().scheduleSyncDelayedTask(MetadataHandler.PLUGIN, this::generateChest, 20L * 60 * customTreasureChestConfigFields.getRestockTimer()); + + } + + private void doMimic() { + HashMap weighedValues = new HashMap<>(); + for (String string : this.customTreasureChestConfigFields.getMimicCustomBossesList()) { + String filename = string.split(":")[0]; + double weight = 1; + try { + weight = Double.valueOf(string.split(":")[1]); + } catch (Exception ex) { + weight = 1; + } + weighedValues.put(filename, weight); + } + CustomBossEntity customBossEntity = CustomBossEntity.createCustomBossEntity(WeightedProbability.pickWeighedProbability(weighedValues)); + customBossEntity.spawn(location, randomizeTier(), false); + } + + private void doTreasure(Player player) { + this.customTreasureChestConfigFields.getCustomLootTable().treasureChestDrop(player, customTreasureChestConfigFields.getChestTier(), location); + } + + private int randomizeTier() { + return customTreasureChestConfigFields.getChestTier() * 10 + ThreadLocalRandom.current().nextInt(11); + } + + private void lowRankMessage(Player player) { + player.sendMessage(ChatColorConverter.convert(TranslationConfig.getChestLowRankMessage().replace("$rank", GuildRank.getRankName(Math.max(0, customTreasureChestConfigFields.getChestTier() - 10), customTreasureChestConfigFields.getChestTier())))); + } + + private void groupTimerCooldownMessage(Player player, long targetTime) { + player.sendMessage(ChatColorConverter.convert(TranslationConfig.getChestCooldownMessage().replace("$time", timeConverter(targetTime - Instant.now().getEpochSecond())))); + } + + private boolean playerIsInCooldown(Player player) { + for (String string : customTreasureChestConfigFields.getRestockTimers()) + if (string.split(":")[0].equals(player.getUniqueId().toString())) + return true; + return false; + } + + private long getPlayerCooldown(Player player) { + for (String string : customTreasureChestConfigFields.getRestockTimers()) + if (string.split(":")[0].equals(player.getUniqueId().toString())) + return Long.parseLong(string.split(":")[1]); + return 0; + } + + private String cooldownStringConstructor(Player player) { + return player.getUniqueId() + ":" + cooldownTime(); + } + + private long cooldownTime() { + return Instant.now().getEpochSecond() + 60L * this.customTreasureChestConfigFields.getRestockTimer(); + } + + private String timeConverter(long seconds) { + if (seconds < 60 * 2) + return seconds + " seconds"; + if (seconds < 60 * 60 * 2) + return Round.twoDecimalPlaces(seconds / 60D) + "minutes"; + if (seconds < 60 * 60 * 48) + return Round.twoDecimalPlaces(seconds / 60D / 60) + "hours"; + else + return Round.twoDecimalPlaces(seconds / 60D / 60 / 48) + "days"; + } + + public void removeTreasureChest() { + CustomTreasureChestsConfig.removeTreasureChestEntry(location, customTreasureChestConfigFields.getFilename()); + location.getBlock().setBlockData(Material.AIR.createBlockData()); + treasureChestHashMap.remove(location); + } + + public enum DropStyle { + SINGLE, + GROUP + } + + public static class TreasureChestEvents implements Listener { + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onPlayerInteract(PlayerInteractEvent event) { + if (event.getClickedBlock() == null) return; + TreasureChest treasureChest = getTreasureChest(event.getClickedBlock().getLocation()); + if (treasureChest == null) return; + event.setCancelled(true); + if (GuildRank.getMaxGuildRank(event.getPlayer()) < treasureChest.customTreasureChestConfigFields.getChestTier()) + treasureChest.lowRankMessage(event.getPlayer()); + else + treasureChest.doInteraction(event.getPlayer()); + } + + @EventHandler + public void onWorldLoad(WorldLoadEvent event) { + for (TreasureChest treasureChest : getUnloadedChests().get(event.getWorld().getName())) { + treasureChest.location.setWorld(event.getWorld()); + treasureChest.generateChest(); + treasureChestHashMap.put(treasureChest.location, treasureChest); + } + getUnloadedChests().removeAll(event.getWorld().getName()); + } + + @EventHandler + public void onWorldUnload(WorldUnloadEvent event) { + for (Iterator> iterator = getTreasureChestHashMap().entrySet().iterator(); iterator.hasNext(); ) { + Map.Entry entry = iterator.next(); + TreasureChest treasureChest = entry.getValue(); + getUnloadedChests().put(event.getWorld().getName(), treasureChest); + iterator.remove(); + } + } + + @EventHandler + public void onBreak(BlockBreakEvent event) { + for (TreasureChest treasureChest : treasureChestHashMap.values()) + if (event.getBlock().getLocation().equals(treasureChest.location.getBlock().getLocation())) + event.setCancelled(true); + } + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/utils/BookMaker.java b/src/main/java/com/magmaguy/elitemobs/utils/BookMaker.java new file mode 100644 index 000000000..e3dd9f0c7 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/utils/BookMaker.java @@ -0,0 +1,46 @@ +package com.magmaguy.elitemobs.utils; + +import net.md_5.bungee.api.chat.TextComponent; +import org.bukkit.Material; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.BookMeta; + +import java.util.List; + +public class BookMaker { + + private BookMaker() { + } + + public static ItemStack generateBook(Player player, List pages) { + ItemStack writtenBook = new ItemStack(Material.WRITTEN_BOOK); + BookMeta bookMeta = (BookMeta) writtenBook.getItemMeta(); + bookMeta.setTitle("EliteMobs Book"); + bookMeta.setAuthor("MagmaGuy"); + bookMeta.setPages(pages); + writtenBook.setItemMeta(bookMeta); + player.openBook(writtenBook); + return writtenBook; + } + + public static ItemStack generateBook(Player player, TextComponent[] pages) { + ItemStack writtenBook = new ItemStack(Material.WRITTEN_BOOK); + BookMeta bookMeta = (BookMeta) writtenBook.getItemMeta(); + bookMeta.setTitle("EliteMobs Book"); + bookMeta.setAuthor("MagmaGuy"); + + /* + for some reason the spigot api isn't respecting the whole 1 page per array element, so this converts it to a + format that actually works + */ + for (TextComponent textComponent : pages) { + TextComponent[] stupid = new TextComponent[1]; + stupid[0] = textComponent; + bookMeta.spigot().addPage(stupid); + } + writtenBook.setItemMeta(bookMeta); + player.openBook(writtenBook); + return writtenBook; + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/utils/ChunkLocationChecker.java b/src/main/java/com/magmaguy/elitemobs/utils/ChunkLocationChecker.java new file mode 100644 index 000000000..766d94c52 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/utils/ChunkLocationChecker.java @@ -0,0 +1,33 @@ +package com.magmaguy.elitemobs.utils; + +import org.bukkit.Chunk; +import org.bukkit.Location; + +public class ChunkLocationChecker { + private ChunkLocationChecker() { + } + + /* + Checks if a location is in a given chunk + */ + public static boolean chunkLocationCheck(Location location, Chunk chunk) { + if (!chunk.getWorld().equals(location.getWorld())) return false; + double chunkX = chunk.getX() * 16; + double locationX = location.getX(); + double chunkZ = chunk.getZ() * 16; + double locationZ = location.getZ(); + if (!(chunkX <= locationX && chunkX + 16 >= locationX)) + return false; + + return chunkZ <= locationZ && chunkZ + 16 >= locationZ; + } + + /* + Checks if a given location is loaded + */ + public static boolean locationIsLoaded(Location location) { + return location.getWorld() != null && + location.getWorld().isChunkLoaded(location.getBlock().getX() >> 4, location.getBlock().getZ() >> 4); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/utils/ChunkVectorizer.java b/src/main/java/com/magmaguy/elitemobs/utils/ChunkVectorizer.java new file mode 100644 index 000000000..0e8c4dc35 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/utils/ChunkVectorizer.java @@ -0,0 +1,31 @@ +package com.magmaguy.elitemobs.utils; + +import org.bukkit.Chunk; + +import java.util.Objects; +import java.util.UUID; +import java.util.Vector; + +public class ChunkVectorizer { + + public static int hash(Chunk chunk) { + return Objects.hash(chunk.getX(), chunk.getZ(), chunk.getWorld().getUID()); + } + + //pseudo-chunks - prevent it form having to load the chunk + public static int hash(int x, int z, UUID worldUUID) { + return Objects.hash(x, z, worldUUID); + } + + public static Vector hash(double x, double z) { + Vector vector = new Vector(2); + vector.addElement(x); + vector.addElement(z); + return vector; + } + + public static boolean isSameChunk(Chunk chunk, int hashedChunk) { + return hash(chunk) == hashedChunk; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/utils/CommandRunner.java b/src/main/java/com/magmaguy/elitemobs/utils/CommandRunner.java new file mode 100644 index 000000000..255c25d2b --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/utils/CommandRunner.java @@ -0,0 +1,40 @@ +package com.magmaguy.elitemobs.utils; + +import com.magmaguy.elitemobs.ondeathcommands.OnDeathCommands; +import org.bukkit.Bukkit; + +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +public class CommandRunner { + + public static void runCommandFromList(List commands, List placeholders) { + if (commands == null || commands.isEmpty()) return; + for (String string : commands) { + if (string == null || string.isEmpty()) continue; + if (placeholders.isEmpty()) { + OnDeathCommands.RunChance runChance = new OnDeathCommands.RunChance(string); + string = runChance.getString(); + if (ThreadLocalRandom.current().nextDouble() < runChance.getChance()) + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), string); + } else { + for (ConfigPlaceholder configPlaceholder : placeholders) + string = string.replace(configPlaceholder.placeholder, configPlaceholder.value); + OnDeathCommands.RunChance runChance = new OnDeathCommands.RunChance(string); + string = runChance.getString(); + if (ThreadLocalRandom.current().nextDouble() < runChance.getChance()) + Bukkit.dispatchCommand(Bukkit.getConsoleSender(), string); + } + } + } + + public class ConfigPlaceholder { + private final String placeholder; + private final String value; + + public ConfigPlaceholder(String placeholder, String value) { + this.placeholder = placeholder; + this.value = value; + } + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/utils/ConfigurationLocation.java b/src/main/java/com/magmaguy/elitemobs/utils/ConfigurationLocation.java new file mode 100644 index 000000000..2fe800272 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/utils/ConfigurationLocation.java @@ -0,0 +1,72 @@ +package com.magmaguy.elitemobs.utils; + +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.World; + +import java.util.HashSet; +import java.util.Objects; +import java.util.Set; + +public class ConfigurationLocation { + private static final Set notLoadedWorldNames = new HashSet<>(); + + private ConfigurationLocation() { + } + + /* + Location format: worldname,x,y,z,pitch,yaw + */ + public static String deserialize(String worldName, double x, double y, double z, float pitch, float yaw) { + return worldName + "," + x + "," + y + "," + z + "," + pitch + "," + yaw; + } + + public static String deserialize(Location location) { + return deserialize(Objects.requireNonNull(location.getWorld()).getName(), location.getX(), location.getY(), location.getZ(), location.getPitch(), location.getYaw()); + } + + public static Location serialize(String locationString) { + + if (locationString == null) + return null; + + World world = null; + double x = 0; + double y = 0; + double z = 0; + float yaw = 0; + float pitch = 0; + + try { + String locationOnlyString = locationString.split(":")[0]; + String[] slicedString = locationOnlyString.split(","); + + world = Bukkit.getWorld(slicedString[0]); + if (world == null && !notLoadedWorldNames.contains(slicedString[0])) { + if (!notLoadedWorldNames.isEmpty()) + new WarningMessage("Some NPCs/bosses don't their world installed! If you need help setting things up, you can go to " + DiscordLinks.mainLink + " !"); + new InfoMessage("World " + slicedString[0] + " is not yet loaded! Entities that should spawn there have been queued."); + notLoadedWorldNames.add(slicedString[0]); + } + x = Double.parseDouble(slicedString[1]); + y = Double.parseDouble(slicedString[2]); + z = Double.parseDouble(slicedString[3]); + if (slicedString.length > 4) { + yaw = Float.parseFloat(slicedString[4]); + pitch = Float.parseFloat(slicedString[5]); + } else { + yaw = 0; + pitch = 0; + } + } catch (Exception ex) { + if (locationString.equals("null")) + return null; + new WarningMessage("Attempted to deserialize an invalid location!"); + new WarningMessage("Expected location format: worldname,x,y,z,pitch,yaw"); + new WarningMessage("Actual location format: " + locationString); + return null; + } + return new Location(world, x, y, z, yaw, pitch); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/utils/Cooldown.java b/src/main/java/com/magmaguy/elitemobs/utils/CooldownHandler.java similarity index 67% rename from src/main/java/com/magmaguy/elitemobs/utils/Cooldown.java rename to src/main/java/com/magmaguy/elitemobs/utils/CooldownHandler.java index 38d0f121a..3a89b1c06 100644 --- a/src/main/java/com/magmaguy/elitemobs/utils/Cooldown.java +++ b/src/main/java/com/magmaguy/elitemobs/utils/CooldownHandler.java @@ -3,12 +3,13 @@ import com.magmaguy.elitemobs.MetadataHandler; import org.bukkit.scheduler.BukkitRunnable; -import java.util.ArrayList; +import java.util.List; -public class Cooldown { - - public static void initialize(ArrayList list, Object object, int cooldownInTicks) { +public class CooldownHandler { + private CooldownHandler() { + } + public static void initialize(List list, Object object, int cooldownInTicks) { list.add(object); new BukkitRunnable() { diff --git a/src/main/java/com/magmaguy/elitemobs/utils/DebugBlockLocation.java b/src/main/java/com/magmaguy/elitemobs/utils/DebugBlockLocation.java new file mode 100644 index 000000000..1febfc5a0 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/utils/DebugBlockLocation.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.utils; + +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.util.Vector; + +public class DebugBlockLocation { + + public DebugBlockLocation(Location location) { + if (!VersionChecker.serverVersionOlderThan(18, 0)) + //todo: restore barrier blocks here, block data was required for the snapshot version of this + location.getWorld().spawnParticle(Particle.EXPLOSION_LARGE, location.getBlock().getLocation().add(new Vector(0.5, 0.5, 0.5)), 1); + else + location.getWorld().spawnParticle(Particle.EXPLOSION_LARGE, location.getBlock().getLocation().add(new Vector(0.5, 0.5, 0.5)), 1); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/utils/DebugMessage.java b/src/main/java/com/magmaguy/elitemobs/utils/DebugMessage.java new file mode 100644 index 000000000..b9cfd0f24 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/utils/DebugMessage.java @@ -0,0 +1,28 @@ +package com.magmaguy.elitemobs.utils; + +import org.bukkit.Bukkit; +import org.bukkit.command.CommandSender; + +public class DebugMessage { + private static boolean debugMode = false; + + public DebugMessage(Object message) { + if (debugMode) { + Bukkit.getLogger().warning("[EliteMobs] Debug message: " + message); + for (StackTraceElement element : Thread.currentThread().getStackTrace()) + Bukkit.getLogger().info(element.toString()); + } + } + + public static void toggleDebugMode(CommandSender commandSender) { + debugMode = !debugMode; + if (debugMode) + commandSender.sendMessage("[EliteMobs] Debug mode on!"); + else + commandSender.sendMessage("[EliteMobs] Debug mode off!"); + } + + public static boolean isDebugMode() { + return debugMode; + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/utils/DeepCopy.java b/src/main/java/com/magmaguy/elitemobs/utils/DeepCopy.java new file mode 100644 index 000000000..32697b8be --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/utils/DeepCopy.java @@ -0,0 +1,27 @@ +package com.magmaguy.elitemobs.utils; + +import org.apache.commons.lang3.SerializationUtils; + +import java.io.Serializable; + +public class DeepCopy { + + /** + * Makes a deep copy of any Java object that is passed. + */ + public static Object copyObject(Serializable object) { + try { + return SerializationUtils.clone(object); + //ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + //ObjectOutputStream outputStrm = new ObjectOutputStream(outputStream); + //outputStrm.writeObject(object); + //ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); + //ObjectInputStream objInputStream = new ObjectInputStream(inputStream); + //return objInputStream.readObject(); + } catch (Exception e) { + e.printStackTrace(); + return null; + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/utils/Developer.java b/src/main/java/com/magmaguy/elitemobs/utils/Developer.java new file mode 100644 index 000000000..0cfb6b57b --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/utils/Developer.java @@ -0,0 +1,14 @@ +package com.magmaguy.elitemobs.utils; + +import org.bukkit.Bukkit; + +import java.util.logging.Level; + +public class Developer { + private Developer() { + } + + public static void message(String message) { + Bukkit.getLogger().log(Level.SEVERE, () -> "[EliteMobs] Developer message: " + message); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/utils/DialogArmorStand.java b/src/main/java/com/magmaguy/elitemobs/utils/DialogArmorStand.java new file mode 100644 index 000000000..284b2688c --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/utils/DialogArmorStand.java @@ -0,0 +1,71 @@ +package com.magmaguy.elitemobs.utils; + +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.api.internal.RemovalReason; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import org.bukkit.entity.ArmorStand; +import org.bukkit.entity.Entity; +import org.bukkit.entity.LivingEntity; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.util.Vector; + +public class DialogArmorStand { + + public static ArmorStand createDialogArmorStand(Entity sourceEntity, String dialog, Vector offset) { + + offset.add(getDisplacementVector(sourceEntity).subtract(new Vector(0, 1, 0))); + Vector finalOffset = offset; + ArmorStand armorStand = VisualArmorStand.VisualArmorStand(sourceEntity.getLocation().clone().add(finalOffset), dialog); + + //This part is necessary because armorstands are visible on their first tick to players + new BukkitRunnable() { + int taskTimer = 0; + + @Override + public void run() { + taskTimer++; + + if (taskTimer > 15 || !sourceEntity.isValid()) { + EntityTracker.unregister(armorStand, RemovalReason.EFFECT_TIMEOUT); + cancel(); + return; + } + armorStand.teleport(sourceEntity.getLocation().clone().add(finalOffset).add(new Vector(0, taskTimer * 0.05, 0))); + } + + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 2); + + return armorStand; + } + + private static Vector getDisplacementVector(Entity sourceEntity) { + double height = 2.3; + if (sourceEntity instanceof LivingEntity) + height = ((LivingEntity) sourceEntity).getEyeHeight() + 0.4; + return new Vector(0, height, 0); + } + + public static ArmorStand createDialogArmorStand(LivingEntity sourceEntity, String dialog) { + + if (sourceEntity == null) return null; + + ArmorStand armorStand = VisualArmorStand.VisualArmorStand(sourceEntity.getLocation().clone().add(getDisplacementVector(sourceEntity)), dialog); + //This part is necessary because armorstands are visible on their first tick to players + new BukkitRunnable() { + int taskTimer = 0; + + @Override + public void run() { + if (taskTimer > 15 || !sourceEntity.isValid()) { + EntityTracker.unregister(armorStand, RemovalReason.EFFECT_TIMEOUT); + cancel(); + return; + } + armorStand.teleport(sourceEntity.getLocation().clone().add(getDisplacementVector(sourceEntity))); + taskTimer++; + } + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 1); + return armorStand; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/utils/DiscordLinks.java b/src/main/java/com/magmaguy/elitemobs/utils/DiscordLinks.java new file mode 100644 index 000000000..256f05425 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/utils/DiscordLinks.java @@ -0,0 +1,7 @@ +package com.magmaguy.elitemobs.utils; + +public class DiscordLinks { + public static final String freeMinidungeons = "https://discord.gg/9f5QSka"; + public static final String premiumMinidungeons = "https://discord.gg/9f5QSka"; + public static final String mainLink = "https://discord.gg/9f5QSka"; +} diff --git a/src/main/java/com/magmaguy/elitemobs/utils/EnderDragonPhaseSimplifier.java b/src/main/java/com/magmaguy/elitemobs/utils/EnderDragonPhaseSimplifier.java new file mode 100644 index 000000000..4e74ca9a4 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/utils/EnderDragonPhaseSimplifier.java @@ -0,0 +1,51 @@ +package com.magmaguy.elitemobs.utils; + +import org.bukkit.entity.EnderDragon; + +public class EnderDragonPhaseSimplifier { + private EnderDragonPhaseSimplifier() { + } + + /** + * Returns whether the dragon's phase has it flying. Strict considers edge behaviors as true (charging, landing and taking off) + * + * @param phase Phase to evaluate + * @param strict If true, includes all flying phases, including things such as charging players and returning to the portal + * @return Returns whether the dragon is flying + */ + public static boolean isFlying(EnderDragon.Phase phase, boolean strict) { + switch (phase) { + case HOVER: + case CIRCLING: + case STRAFING: + return true; + default: + if (strict) + return phase.equals(EnderDragon.Phase.LAND_ON_PORTAL) || + phase.equals(EnderDragon.Phase.LEAVE_PORTAL) || + phase.equals(EnderDragon.Phase.CHARGE_PLAYER); + return false; + + } + } + + /** + * Returns whether the dragon is currently in a landed phase. This means any phase where the dragon is sitting in the middle of the map. + * + * @param phase Phase to evaluate + * @return Whether the dragon sits in the middle of the map during that phase + */ + public static boolean isLanded(EnderDragon.Phase phase) { + switch (phase) { + case BREATH_ATTACK: + case SEARCH_FOR_BREATH_ATTACK_TARGET: + case ROAR_BEFORE_ATTACK: + return true; + default: + return false; + } + } + + +} + diff --git a/src/main/java/com/magmaguy/elitemobs/utils/EntityFinder.java b/src/main/java/com/magmaguy/elitemobs/utils/EntityFinder.java index 0ee31c877..e96aea4d1 100644 --- a/src/main/java/com/magmaguy/elitemobs/utils/EntityFinder.java +++ b/src/main/java/com/magmaguy/elitemobs/utils/EntityFinder.java @@ -8,16 +8,15 @@ import org.bukkit.event.entity.EntityTargetLivingEntityEvent; public class EntityFinder { + private EntityFinder() { + } public static LivingEntity filterRangedDamagers(Entity entity) { - if (entity instanceof LivingEntity) return (LivingEntity) entity; else if (entity instanceof Projectile && ((Projectile) entity).getShooter() instanceof LivingEntity) return (LivingEntity) ((Projectile) entity).getShooter(); - return null; - } public static LivingEntity getRealDamager(EntityDamageByEntityEvent event) { @@ -37,7 +36,7 @@ public static Player findPlayer(EntityDamageByEntityEvent event) { } public static Player findPlayer(EntityTargetLivingEntityEvent event) { - return playerFilter(event.getEntity()); + return playerFilter(event.getTarget()); } } diff --git a/src/main/java/com/magmaguy/elitemobs/utils/EventCaller.java b/src/main/java/com/magmaguy/elitemobs/utils/EventCaller.java new file mode 100644 index 000000000..864ffb975 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/utils/EventCaller.java @@ -0,0 +1,10 @@ +package com.magmaguy.elitemobs.utils; + +import org.bukkit.Bukkit; +import org.bukkit.event.Event; + +public class EventCaller { + public EventCaller(Event event) { + Bukkit.getPluginManager().callEvent(event); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/utils/InfoMessage.java b/src/main/java/com/magmaguy/elitemobs/utils/InfoMessage.java new file mode 100644 index 000000000..ae714f526 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/utils/InfoMessage.java @@ -0,0 +1,9 @@ +package com.magmaguy.elitemobs.utils; + +import org.bukkit.Bukkit; + +public class InfoMessage { + public InfoMessage(String message) { + Bukkit.getLogger().info("[EliteMobs] " + message); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/utils/ItemStackGenerator.java b/src/main/java/com/magmaguy/elitemobs/utils/ItemStackGenerator.java new file mode 100644 index 000000000..15979105b --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/utils/ItemStackGenerator.java @@ -0,0 +1,57 @@ +package com.magmaguy.elitemobs.utils; + +import com.magmaguy.elitemobs.ChatColorConverter; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.SkullMeta; + +import java.util.List; + +public class ItemStackGenerator { + + public static ItemStack generateSkullItemStack(String owner, String name, List lore) { + ItemStack itemStack = new ItemStack(Material.PLAYER_HEAD); + SkullMeta skullMeta = (SkullMeta) itemStack.getItemMeta(); + skullMeta.setOwner(owner); + skullMeta.setDisplayName(name); + skullMeta.setLore(lore); + itemStack.setItemMeta(skullMeta); + return itemStack; + } + + public static ItemStack generateItemStack(ItemStack itemStack, String name, List lore) { + ItemMeta itemMeta = itemStack.getItemMeta(); + itemMeta.setDisplayName(ChatColorConverter.convert(name)); + itemMeta.setLore(ChatColorConverter.convert(lore)); + itemStack.setItemMeta(itemMeta); + return itemStack; + } + + public static ItemStack generateItemStack(Material material, String name, List lore) { + ItemStack itemStack = generateItemStack(material, ChatColorConverter.convert(name)); + ItemMeta itemMeta = itemStack.getItemMeta(); + itemMeta.setLore(ChatColorConverter.convert(lore)); + itemStack.setItemMeta(itemMeta); + return itemStack; + } + + public static ItemStack generateItemStack(Material material, String name) { + ItemStack itemStack = generateItemStack(material); + ItemMeta itemMeta = itemStack.getItemMeta(); + itemMeta.setDisplayName(name); + itemStack.setItemMeta(itemMeta); + return itemStack; + } + + public static ItemStack generateItemStack(Material material) { + if (material == null) material = Material.AIR; + ItemStack itemStack = new ItemStack(material); + if (material.equals(Material.AIR)) return itemStack; + ItemMeta itemMeta = itemStack.getItemMeta(); + itemMeta.setDisplayName(""); + itemStack.setItemMeta(itemMeta); + return itemStack; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/utils/ItemStackSerializer.java b/src/main/java/com/magmaguy/elitemobs/utils/ItemStackSerializer.java new file mode 100644 index 000000000..51d651528 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/utils/ItemStackSerializer.java @@ -0,0 +1,91 @@ +package com.magmaguy.elitemobs.utils; + +import com.magmaguy.elitemobs.ChatColorConverter; +import org.bukkit.Material; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.inventory.meta.SkullMeta; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class ItemStackSerializer { + + public static FileConfiguration serialize(String identifier, ItemStack itemStack, FileConfiguration fileConfiguration) { + fileConfiguration.addDefault(identifier + ".material", itemStack.getType().toString()); + if (itemStack.hasItemMeta() && itemStack.getItemMeta().hasDisplayName()) + fileConfiguration.addDefault(identifier + ".name", itemStack.getItemMeta().getDisplayName()); + if (itemStack.hasItemMeta() && itemStack.getItemMeta().hasLore()) + fileConfiguration.addDefault(identifier + ".lore", itemStack.getItemMeta().getLore()); + if (itemStack.getType().equals(Material.PLAYER_HEAD)) + fileConfiguration.addDefault(identifier + ".owner", ((SkullMeta) itemStack.getItemMeta()).getOwner()); + + return fileConfiguration; + } + + public static ItemStack deserialize(String identifier, FileConfiguration fileConfiguration) { + Material material; + identifier += "."; + try { + material = Material.valueOf(fileConfiguration.getString(identifier + "material")); + } catch (Exception ex) { + new WarningMessage("Attempted to add material name " + fileConfiguration.getString("material") + " to a menu. This is not a valid material. Item will default to glass."); + material = Material.RED_STAINED_GLASS_PANE; + } + + String name = ""; + if (fileConfiguration.contains(identifier + "name")) + name = ChatColorConverter.convert(fileConfiguration.getString(identifier + "name")); + + List lore = new ArrayList<>(); + if (fileConfiguration.contains(identifier + "lore")) + lore = ChatColorConverter.convert(fileConfiguration.getStringList(identifier + "lore")); + + if (material.equals(Material.PLAYER_HEAD)) { + String owner = fileConfiguration.getString(identifier + "owner"); + return ItemStackGenerator.generateSkullItemStack(owner, name, lore); + } + + return ItemStackGenerator.generateItemStack(material, name, lore); + } + + /** + * Used to generate itemstacks from configuration files when they contain placeholders + * + * @param itemStack + * @param placeholderReplacementPairs List of placeholders / replacements. Each placeholder is a key, each key has 1 replacement value. + * @return + */ + public static ItemStack itemStackPlaceholderReplacer(ItemStack itemStack, HashMap placeholderReplacementPairs) { + ItemStack cloneItemStack = itemStack.clone(); + ItemMeta newMeta = itemStack.getItemMeta(); + + + //Replace placeholders in name + if (newMeta.hasDisplayName()) { + String newName = newMeta.getDisplayName(); + for (String placeholder : placeholderReplacementPairs.keySet()) + if (newMeta.getDisplayName().contains(placeholder)) + newName = newName.replace(placeholder, placeholderReplacementPairs.get(placeholder)); + newMeta.setDisplayName(newName); + } + + List newLore = new ArrayList<>(); + if (newMeta.hasLore()) { + for (String loreString : newMeta.getLore()) { + String newLoreString = loreString; + for (String placeholder : placeholderReplacementPairs.keySet()) + if (loreString.contains(placeholder)) + newLoreString = newLoreString.replace(placeholder, placeholderReplacementPairs.get(placeholder)); + newLore.add(newLoreString); + } + newMeta.setLore(newLore); + } + + cloneItemStack.setItemMeta(newMeta); + return cloneItemStack; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/utils/NonSolidBlockTypes.java b/src/main/java/com/magmaguy/elitemobs/utils/NonSolidBlockTypes.java new file mode 100644 index 000000000..0044aa314 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/utils/NonSolidBlockTypes.java @@ -0,0 +1,15 @@ +package com.magmaguy.elitemobs.utils; + +import org.bukkit.Material; + +import java.util.ArrayList; + +public class NonSolidBlockTypes { + + private static final ArrayList nonSolidBlocks = new ArrayList<>(); + + public static boolean isPassthrough(Material material) { + return !material.isSolid(); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/utils/ObfuscatedStringHandler.java b/src/main/java/com/magmaguy/elitemobs/utils/ObfuscatedStringHandler.java new file mode 100644 index 000000000..15fba2c32 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/utils/ObfuscatedStringHandler.java @@ -0,0 +1,42 @@ +package com.magmaguy.elitemobs.utils; + +public class ObfuscatedStringHandler { + private ObfuscatedStringHandler() { + } + + public static String obfuscateString(String originalString) { + + String insert = "§"; + int period = 1; + + StringBuilder stringBuilder = new StringBuilder(originalString.length() + insert.length() * (originalString.length() / period)); + + int index = 0; + String prefix = ""; + + while (index < originalString.length()) { + + stringBuilder.append(prefix); + prefix = insert; + stringBuilder.append(originalString, index, Math.min(index + period, originalString.length())); + index += period; + + } + + String finalString = stringBuilder.toString(); + + finalString = "§" + finalString; + + return finalString; + + } + + public static boolean checkString(String obfuscatedString, String targetString) { + return deobfuscateString(obfuscatedString).contains(targetString); + } + + public static String deobfuscateString(String obfuscatedString) { + return obfuscatedString.replace("§", ""); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/utils/ObjectSerializer.java b/src/main/java/com/magmaguy/elitemobs/utils/ObjectSerializer.java new file mode 100644 index 000000000..ffa0f816d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/utils/ObjectSerializer.java @@ -0,0 +1,88 @@ +package com.magmaguy.elitemobs.utils; + + +import org.bukkit.inventory.ItemStack; +import org.bukkit.util.io.BukkitObjectInputStream; +import org.bukkit.util.io.BukkitObjectOutputStream; +import org.yaml.snakeyaml.external.biz.base64Coder.Base64Coder; + +import java.io.*; +import java.util.Base64; + +public class ObjectSerializer { + + private ObjectSerializer() { + } + + /** + * Read the object from Base64 string. + */ + public static Object fromString(String s) throws IOException, + ClassNotFoundException { + byte[] data = Base64.getDecoder().decode(s); + ObjectInputStream ois = new ObjectInputStream( + new ByteArrayInputStream(data)); + Object o = ois.readObject(); + ois.close(); + return o; + } + + /** + * Write the object to a Base64 string. + */ + public static String toString(Serializable o) throws IOException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos); + oos.writeObject(o); + oos.close(); + return Base64.getEncoder().encodeToString(baos.toByteArray()); + } + + /** + * A method to serialize an {@link ItemStack} array to Base64 String. + *

+ *

+ * + * @param itemStack to turn into a Base64 String. + * @return Base64 string of the items. + * @throws IllegalStateException + */ + public static String itemStackArrayToBase64(ItemStack itemStack) throws IllegalStateException { + try { + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + BukkitObjectOutputStream dataOutput = new BukkitObjectOutputStream(outputStream); + + // Write the size of the inventory + //dataOutput.writeInt(1); + dataOutput.writeObject(itemStack); + + // Serialize that array + dataOutput.close(); + return Base64Coder.encodeLines(outputStream.toByteArray()); + } catch (Exception e) { + throw new IllegalStateException("Unable to save item stacks.", e); + } + } + + /** + * Gets an array of ItemStacks from Base64 string. + *

+ *

+ * + * @param data Base64 string to convert to ItemStack array. + * @return ItemStack array created from the Base64 string. + * @throws IOException + */ + public static ItemStack itemStackArrayFromBase64(String data) throws IOException { + try { + ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data)); + BukkitObjectInputStream dataInput = new BukkitObjectInputStream(inputStream); + ItemStack itemStack = (ItemStack) dataInput.readObject(); + dataInput.close(); + return itemStack; + } catch (ClassNotFoundException e) { + throw new IOException("Unable to decode class type.", e); + } + } + +} \ No newline at end of file diff --git a/src/main/java/com/magmaguy/elitemobs/utils/PersistentVanillaData.java b/src/main/java/com/magmaguy/elitemobs/utils/PersistentVanillaData.java new file mode 100644 index 000000000..fbc13a7f1 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/utils/PersistentVanillaData.java @@ -0,0 +1,44 @@ +package com.magmaguy.elitemobs.utils; + +import com.magmaguy.elitemobs.MetadataHandler; +import org.bukkit.NamespacedKey; +import org.bukkit.entity.Entity; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; +import org.bukkit.persistence.PersistentDataType; + +public class PersistentVanillaData { + private PersistentVanillaData() { + } + + public static void write(Entity entity, String key, String value) { + entity.getPersistentDataContainer().set(getKey(key), PersistentDataType.STRING, value); + } + + public static void write(ItemStack itemStack, String key, double value) { + ItemMeta itemMeta = itemStack.getItemMeta(); + itemMeta.getPersistentDataContainer().set(getKey(key), PersistentDataType.DOUBLE, value); + itemStack.setItemMeta(itemMeta); + } + + public static boolean hasString(Entity entity, String key) { + return entity.getPersistentDataContainer().has(getKey(key), PersistentDataType.STRING); + } + + public static String getString(Entity entity, String key) { + return entity.getPersistentDataContainer().get(getKey(key), PersistentDataType.STRING); + } + + public static double getDouble(ItemStack itemStack, String key) { + if (itemStack == null || itemStack.getItemMeta() == null) return -1; + if (!itemStack.getItemMeta().getPersistentDataContainer().has(getKey(key), PersistentDataType.DOUBLE)) + return -1; + Double d = itemStack.getItemMeta().getPersistentDataContainer().get(getKey(key), PersistentDataType.DOUBLE); + return d == null ? -1 : d; + } + + private static NamespacedKey getKey(String key) { + return new NamespacedKey(MetadataHandler.PLUGIN, key); + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/utils/PlayerHeads.java b/src/main/java/com/magmaguy/elitemobs/utils/PlayerHeads.java new file mode 100644 index 000000000..da6657cd9 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/utils/PlayerHeads.java @@ -0,0 +1,20 @@ +package com.magmaguy.elitemobs.utils; + +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.SkullMeta; + +public class PlayerHeads { + + public static ItemStack exclamation() { + ItemStack exclamation; + exclamation = new ItemStack(Material.PLAYER_HEAD); + SkullMeta exclamationMeta = (SkullMeta) exclamation.getItemMeta(); + exclamationMeta.setOwner("MHF_Exclamation"); + exclamation.setItemMeta(exclamationMeta); + + return exclamation; + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/utils/PlayerScanner.java b/src/main/java/com/magmaguy/elitemobs/utils/PlayerScanner.java new file mode 100644 index 000000000..8616b26a5 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/utils/PlayerScanner.java @@ -0,0 +1,23 @@ +package com.magmaguy.elitemobs.utils; + +import com.magmaguy.elitemobs.playerdata.ElitePlayerInventory; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.List; + +public class PlayerScanner { + private static final int range = Math.max(Bukkit.getServer().getViewDistance() * 16, 5 * 16); + + public static List getNearbyPlayers(Location location) { + List nearbyPlayers = new ArrayList<>(); + for (Player player : Bukkit.getOnlinePlayers()) + if (player.getWorld().equals(location.getWorld()) && + player.getLocation().distanceSquared(location) <= range * range && + ElitePlayerInventory.playerInventories.get(player.getUniqueId()) != null) + nearbyPlayers.add(player); + return nearbyPlayers; + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/utils/RawEnchantmentGetters.java b/src/main/java/com/magmaguy/elitemobs/utils/RawEnchantmentGetters.java new file mode 100644 index 000000000..93eb7fd3a --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/utils/RawEnchantmentGetters.java @@ -0,0 +1,52 @@ +package com.magmaguy.elitemobs.utils; + +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.ItemStack; + +import java.util.HashMap; +import java.util.Map; + +public class RawEnchantmentGetters { + + /** + * Catches the obfuscated levels which are the values EliteMobs works with. Should only get called if the item + * has the signature obfuscated lore. + * + * @param itemStack ItemStack to get analysed + * @return HashMap of all obfuscated enchantments + */ + public static Map vanillaEnchantmentsList(ItemStack itemStack) { + + return vanillaEnchantmentsList(itemStack.getEnchantments(), itemStack.getItemMeta().getLore().get(0)); + + } + + public static Map vanillaEnchantmentsList(Map actualEnchantmentsList, String obfuscatedLore) { + + Map enchantmentsMap = new HashMap(); + + if (actualEnchantmentsList.isEmpty()) + return enchantmentsMap; + + for (Enchantment enchantment : actualEnchantmentsList.keySet()) + enchantmentsMap.put(enchantment, getDeobfuscatedLevel(obfuscatedLore, enchantment.getName())); + + return enchantmentsMap; + + } + + private static int getDeobfuscatedLevel(String obfuscatedLore, String enchantmentName) { + + String deobfuscatedLore = obfuscatedLore.replace("§", ""); + + for (String stringPairs : deobfuscatedLore.split(",")) { + String[] stringList = stringPairs.split(":"); + if (stringList[0].equalsIgnoreCase(enchantmentName)) + return Integer.parseInt(stringList[1]); + } + + return 0; + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/utils/Round.java b/src/main/java/com/magmaguy/elitemobs/utils/Round.java new file mode 100644 index 000000000..75d534cb9 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/utils/Round.java @@ -0,0 +1,12 @@ +package com.magmaguy.elitemobs.utils; + +public class Round { + + private Round() { + } + + public static double twoDecimalPlaces(double value) { + return Math.round(value * 100.0) / 100.0; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/utils/ServerTime.java b/src/main/java/com/magmaguy/elitemobs/utils/ServerTime.java new file mode 100644 index 000000000..6a9fe24d6 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/utils/ServerTime.java @@ -0,0 +1,17 @@ +package com.magmaguy.elitemobs.utils; + +import com.magmaguy.elitemobs.MetadataHandler; +import lombok.Getter; +import org.bukkit.Bukkit; + +public class ServerTime { + @Getter + private static double time = 0; + + private ServerTime() { + } + + public static void startTickCounter() { + Bukkit.getScheduler().scheduleSyncRepeatingTask(MetadataHandler.PLUGIN, () -> time++, 0, 1); + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/utils/SimpleScoreboard.java b/src/main/java/com/magmaguy/elitemobs/utils/SimpleScoreboard.java new file mode 100644 index 000000000..6aa39bc81 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/utils/SimpleScoreboard.java @@ -0,0 +1,46 @@ +package com.magmaguy.elitemobs.utils; + +import com.magmaguy.elitemobs.MetadataHandler; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scoreboard.DisplaySlot; +import org.bukkit.scoreboard.Objective; +import org.bukkit.scoreboard.Score; +import org.bukkit.scoreboard.Scoreboard; + +import java.util.List; + +public class SimpleScoreboard { + + public static Scoreboard lazyScoreboard(Player player, String displayName, List scoreboardContents) { + Scoreboard scoreboard = Bukkit.getScoreboardManager().getNewScoreboard(); + int lineCount = Math.min(scoreboardContents.size(), 15); + + Objective objective = scoreboard.registerNewObjective("test", "dummy", displayName); + objective.setDisplaySlot(DisplaySlot.SIDEBAR); + for (int i = 0; i < lineCount; i++) { + String scoreString = scoreboardContents.get(i); + if (scoreString.length() > 40) scoreString = scoreString.substring(0, 39); + Score score = objective.getScore(scoreString); + score.setScore(i); + } + + player.setScoreboard(scoreboard); + + return scoreboard; + } + + public static Scoreboard temporaryScoreboard(Player player, String displayName, List scoreboardContents, int ticksTimeout) { + Scoreboard scoreboard = lazyScoreboard(player, displayName, scoreboardContents); + new BukkitRunnable() { + @Override + public void run() { + if (player.getScoreboard().equals(scoreboard)) + player.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); + } + }.runTaskLater(MetadataHandler.PLUGIN, ticksTimeout); + + return scoreboard; + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/utils/SpigotMessage.java b/src/main/java/com/magmaguy/elitemobs/utils/SpigotMessage.java new file mode 100644 index 000000000..ec205ea4b --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/utils/SpigotMessage.java @@ -0,0 +1,32 @@ +package com.magmaguy.elitemobs.utils; + +import com.magmaguy.elitemobs.ChatColorConverter; +import net.md_5.bungee.api.chat.ClickEvent; +import net.md_5.bungee.api.chat.HoverEvent; +import net.md_5.bungee.api.chat.TextComponent; +import net.md_5.bungee.api.chat.hover.content.Text; + +public final class SpigotMessage { + public static TextComponent simpleMessage(String message) { + return new TextComponent(ChatColorConverter.convert(message)); + } + + public static TextComponent hoverMessage(String message, String hoverMessage) { + TextComponent textComponent = simpleMessage(message); + textComponent.setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new Text(hoverMessage))); + return textComponent; + } + + public static TextComponent commandHoverMessage(String message, String hoverMessage, String commandString) { + TextComponent textComponent = hoverMessage(message, hoverMessage); + if (!commandString.isEmpty()) + textComponent.setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, commandString)); + return textComponent; + } + + public static TextComponent hoverLinkMessage(String message, String hoverMessage, String link) { + TextComponent textComponent = hoverMessage(message, hoverMessage); + textComponent.setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, link)); + return textComponent; + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/utils/StringColorAnimator.java b/src/main/java/com/magmaguy/elitemobs/utils/StringColorAnimator.java new file mode 100644 index 000000000..6b8278463 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/utils/StringColorAnimator.java @@ -0,0 +1,58 @@ +package com.magmaguy.elitemobs.utils; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.MetadataHandler; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; + +public class StringColorAnimator { + private StringColorAnimator() { + } + + public static void startTitleAnimation(Player player, String title, String subtitle, ChatColor primaryColor, ChatColor secondaryColor) { + + subtitle = ChatColor.stripColor(subtitle); + + String finalSubtitle = subtitle; + new BukkitRunnable() { + final int titleSize = title.length(); + final int subtitleSize = finalSubtitle.length(); + int counter = 0; + int titleIndex = 0; + int subtitleIndex = 0; + + @Override + public void run() { + + counter++; + + if (titleIndex <= titleSize) { + StringBuilder newTitle = new StringBuilder(title).insert(titleIndex, primaryColor); + if (titleIndex > 1) + newTitle.insert(titleIndex - 2, secondaryColor); + titleIndex++; + player.sendTitle(primaryColor + ChatColorConverter.convert(newTitle.toString()), + secondaryColor + ChatColorConverter.convert(finalSubtitle), 0, 5, 0); + return; + } + + if (subtitleIndex > subtitleSize) { + cancel(); + return; + } + + StringBuilder newSubtitle = new StringBuilder(finalSubtitle).insert(subtitleIndex, secondaryColor); + if (subtitleIndex > 1) + newSubtitle.insert(subtitleIndex - 2, primaryColor); + subtitleIndex++; + player.sendTitle("", + secondaryColor + ChatColorConverter.convert(newSubtitle.toString()), 0, 5, 0); + + } + + }.runTaskTimer(MetadataHandler.PLUGIN, 0, 2); + + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/utils/VersionChecker.java b/src/main/java/com/magmaguy/elitemobs/utils/VersionChecker.java index 35b7d70e6..15bd21d85 100644 --- a/src/main/java/com/magmaguy/elitemobs/utils/VersionChecker.java +++ b/src/main/java/com/magmaguy/elitemobs/utils/VersionChecker.java @@ -4,42 +4,31 @@ public class VersionChecker { - public static boolean currentVersionIsUnder(int version, int subVersion) { - - if (Bukkit.getBukkitVersion().split("[.]").length < 4) { - - try { - return Integer.parseInt(Bukkit.getBukkitVersion().split("[.]")[1].substring(0, 2)) < version; - } catch (Exception ex) { - return Integer.parseInt(Bukkit.getBukkitVersion().split("[.]")[1].substring(0, 1)) < version; - } - - } - - if (Integer.parseInt(Bukkit.getBukkitVersion().split("[.]")[1]) < version) return true; - - if (Integer.parseInt(Bukkit.getBukkitVersion().split("[.]")[1]) == version) { - try { - - byte actualSubversion = Byte.parseByte(Bukkit.getBukkitVersion().split("[.]")[2].substring(0, 1)); - return actualSubversion < subVersion; - - } catch (Exception e) { + private VersionChecker() { + } - try { + /** + * Compares a Minecraft version with the current version on the server. Returns true if the version on the server is older. + * + * @param majorVersion Target major version to compare (i.e. 1.>>>17<<<.0) + * @param minorVersion Target minor version to compare (i.e. 1.17.>>>0<<<) + * @return Whether the version is under the value to be compared + */ + public static boolean serverVersionOlderThan(int majorVersion, int minorVersion) { - byte actualSubversion = Byte.parseByte(Bukkit.getBukkitVersion().split("[.]")[2].substring(0, 0)); - return actualSubversion < subVersion; + String[] splitVersion = Bukkit.getBukkitVersion().split("[.]"); - } catch (Exception ex) { + int actualMajorVersion = Integer.parseInt(splitVersion[1].split("-")[0]); - Bukkit.getLogger().warning("[EliteMobs] Couldn't read version properly, report this to the developer!"); - return false; + int actualMinorVersion = 0; + if (splitVersion.length > 2) + actualMinorVersion = Integer.parseInt(splitVersion[2].split("-")[0]); - } - } + if (actualMajorVersion < majorVersion) + return true; - } + if (splitVersion.length > 2) + return actualMajorVersion == majorVersion && actualMinorVersion < minorVersion; return false; diff --git a/src/main/java/com/magmaguy/elitemobs/utils/VisualArmorStand.java b/src/main/java/com/magmaguy/elitemobs/utils/VisualArmorStand.java new file mode 100644 index 000000000..e33d6df0d --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/utils/VisualArmorStand.java @@ -0,0 +1,29 @@ +package com.magmaguy.elitemobs.utils; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import org.bukkit.Location; +import org.bukkit.entity.ArmorStand; +import org.bukkit.util.Consumer; + + +public class VisualArmorStand { + + public static ArmorStand VisualArmorStand(Location location, String customName) { + ArmorStand visualArmorStand = location.getWorld().spawn(location, ArmorStand.class, new Consumer() { + @Override + public void accept(ArmorStand armorStand) { + armorStand.setVisible(false); + armorStand.setMarker(true); + armorStand.setCustomName(ChatColorConverter.convert(customName)); + armorStand.setCustomNameVisible(true); + armorStand.setGravity(false); + armorStand.setRemoveWhenFarAway(true); + armorStand.setPersistent(false); + } + }); + EntityTracker.registerVisualEffects(visualArmorStand); + return visualArmorStand; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/utils/WarningMessage.java b/src/main/java/com/magmaguy/elitemobs/utils/WarningMessage.java new file mode 100644 index 000000000..360be4eb6 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/utils/WarningMessage.java @@ -0,0 +1,21 @@ +package com.magmaguy.elitemobs.utils; + +import com.magmaguy.elitemobs.MetadataHandler; +import org.bukkit.Bukkit; + +public class WarningMessage { + + public WarningMessage(String message) { + Bukkit.getLogger().warning("[EliteMobs] " + message); + } + + public WarningMessage(String message, boolean stackTrace) { + Bukkit.getLogger().warning("[EliteMobs] " + message); + if (stackTrace) { + Bukkit.getLogger().warning("[EliteMobs] Report the following to the developer at " + DiscordLinks.mainLink); + Bukkit.getLogger().info("EliteMobs version: " + MetadataHandler.PLUGIN.getDescription().getVersion() + " | Server version: " + Bukkit.getServer().getVersion()); + for (StackTraceElement element : Thread.currentThread().getStackTrace()) + Bukkit.getLogger().info(element.toString()); + } + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/utils/WeightedProbablity.java b/src/main/java/com/magmaguy/elitemobs/utils/WeightedProbability.java similarity index 84% rename from src/main/java/com/magmaguy/elitemobs/utils/WeightedProbablity.java rename to src/main/java/com/magmaguy/elitemobs/utils/WeightedProbability.java index c5fc32c7c..c8fe5f873 100644 --- a/src/main/java/com/magmaguy/elitemobs/utils/WeightedProbablity.java +++ b/src/main/java/com/magmaguy/elitemobs/utils/WeightedProbability.java @@ -2,37 +2,28 @@ import java.util.HashMap; -public class WeightedProbablity { +public class WeightedProbability { public static String pickWeighedProbability(HashMap weighedValues) { double totalWeight = 0; - for (String string : weighedValues.keySet()) { - + for (String string : weighedValues.keySet()) totalWeight += weighedValues.get(string); - } - String selectedString = null; double random = Math.random() * totalWeight; for (String string : weighedValues.keySet()) { - random -= weighedValues.get(string); - if (random <= 0) { - selectedString = string; break; - } - } return selectedString; } - } diff --git a/src/main/java/com/magmaguy/elitemobs/utils/ZipFile.java b/src/main/java/com/magmaguy/elitemobs/utils/ZipFile.java new file mode 100644 index 000000000..3013a89d0 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/utils/ZipFile.java @@ -0,0 +1,161 @@ +package com.magmaguy.elitemobs.utils; + +import com.magmaguy.elitemobs.MetadataHandler; + +import java.io.*; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; +import java.util.zip.ZipOutputStream; + +public class ZipFile { + private ZipFile() { + } + + public static boolean zip(File directory, String targetZipPath) { + if (!directory.exists()) { + new WarningMessage("Failed to zip directory " + directory.getPath() + " because it does not exist!"); + return false; + } + + try { + ZipUtility.zip(directory, targetZipPath); + return true; + } catch (IOException e) { + e.printStackTrace(); + return false; + } + } + + public static File unzip(String zippedFileName) throws IOException { + String mainDirectory = MetadataHandler.PLUGIN.getDataFolder().getAbsolutePath() + "/imports/"; + String fileZip = mainDirectory + zippedFileName; + File finalDirectory = new File(mainDirectory + zippedFileName.replace(".zip", "")); + byte[] buffer = new byte[1024]; + ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(fileZip)); + ZipEntry zipEntry = zipInputStream.getNextEntry(); + while (zipEntry != null) { + File newFile = newFile(finalDirectory, zipEntry); + if (zipEntry.isDirectory()) { + if (!newFile.isDirectory() && !newFile.mkdirs()) { + throw new IOException("Failed to create directory " + newFile); + } + } else { + // fix for Windows-created archives + File parent = newFile.getParentFile(); + if (!parent.isDirectory() && !parent.mkdirs()) { + throw new IOException("Failed to create directory " + parent); + } + + // write file content + FileOutputStream fileOutputStream = new FileOutputStream(newFile); + int len; + while ((len = zipInputStream.read(buffer)) > 0) { + fileOutputStream.write(buffer, 0, len); + } + fileOutputStream.close(); + } + zipEntry = zipInputStream.getNextEntry(); + } + zipInputStream.closeEntry(); + zipInputStream.close(); + return finalDirectory; + } + + private static File newFile(File destinationDir, ZipEntry zipEntry) throws IOException { + File destFile = new File(destinationDir, zipEntry.getName()); + + String destDirPath = destinationDir.getCanonicalPath(); + String destFilePath = destFile.getCanonicalPath(); + + if (!destFilePath.startsWith(destDirPath + File.separatorChar)) { + throw new IOException("Entry is outside of the target dir: " + zipEntry.getName()); + } + + return destFile; + } + + public static class ZipUtility { + /** + * A constants for buffer size used to read/write data + */ + private static final int BUFFER_SIZE = 4096; + + /** + * Compresses a list of files to a destination zip file + * + * @param file File to zip + * @param destZipFile The path of the destination zip file + * @throws FileNotFoundException + * @throws IOException + */ + public static void zip(File file, String destZipFile) throws FileNotFoundException, IOException { + ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(destZipFile)); + //This slight tweak avoids making the directory zipped be in the zipped file when what we are looking for is to + //zip the contents of the directory, outside of the directory itself + if (file.isDirectory()) { + for (File file1 : file.listFiles()) { + if (file1.isDirectory()) + zipDirectory(file1, file1.getName(), zos); + else + zipFile(file1, zos); + } + } else { + zipFile(file, zos); + } + zos.flush(); + zos.close(); + } + + /** + * Adds a directory to the current zip output stream + * + * @param folder the directory to be added + * @param parentFolder the path of parent directory + * @param zos the current zip output stream + * @throws FileNotFoundException + * @throws IOException + */ + private static void zipDirectory(File folder, String parentFolder, + ZipOutputStream zos) throws FileNotFoundException, IOException { + for (File file : folder.listFiles()) { + if (file.isDirectory()) { + zipDirectory(file, parentFolder + "/" + file.getName(), zos); + continue; + } + zos.putNextEntry(new ZipEntry(parentFolder + "/" + file.getName())); + BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file)); + long bytesRead = 0; + byte[] bytesIn = new byte[BUFFER_SIZE]; + int read = 0; + while ((read = bis.read(bytesIn)) != -1) { + zos.write(bytesIn, 0, read); + bytesRead += read; + } + zos.closeEntry(); + } + } + + /** + * Adds a file to the current zip output stream + * + * @param file the file to be added + * @param zos the current zip output stream + * @throws FileNotFoundException + * @throws IOException + */ + private static void zipFile(File file, ZipOutputStream zos) + throws FileNotFoundException, IOException { + zos.putNextEntry(new ZipEntry(file.getName())); + BufferedInputStream bis = new BufferedInputStream(new FileInputStream( + file)); + long bytesRead = 0; + byte[] bytesIn = new byte[BUFFER_SIZE]; + int read = 0; + while ((read = bis.read(bytesIn)) != -1) { + zos.write(bytesIn, 0, read); + bytesRead += read; + } + zos.closeEntry(); + } + } +} diff --git a/src/main/java/com/magmaguy/elitemobs/versionnotifier/VersionChecker.java b/src/main/java/com/magmaguy/elitemobs/versionnotifier/VersionChecker.java index d0ecc3471..788a73623 100644 --- a/src/main/java/com/magmaguy/elitemobs/versionnotifier/VersionChecker.java +++ b/src/main/java/com/magmaguy/elitemobs/versionnotifier/VersionChecker.java @@ -1,53 +1,112 @@ package com.magmaguy.elitemobs.versionnotifier; +import com.magmaguy.elitemobs.ChatColorConverter; import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.dungeons.Minidungeon; +import com.magmaguy.elitemobs.utils.DiscordLinks; +import com.magmaguy.elitemobs.utils.InfoMessage; +import com.magmaguy.elitemobs.utils.SpigotMessage; +import com.magmaguy.elitemobs.utils.WarningMessage; import org.bukkit.Bukkit; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.player.PlayerJoinEvent; +import org.bukkit.scheduler.BukkitRunnable; import java.io.IOException; import java.net.URL; import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; import java.util.Scanner; public class VersionChecker { + private static final List outdatedDungeons = new ArrayList<>(); + private static boolean pluginIsUpToDate = true; - public static boolean pluginIsUpToDate = true; - - public static void updateComparer(){ - - String currentVersion = MetadataHandler.PLUGIN.getDescription().getVersion(); - String publicVersion = ""; - - try { - Bukkit.getLogger().info("[EliteMobs] Latest public release is " + VersionChecker.readStringFromURL()); - Bukkit.getLogger().info("[EliteMobs] Your version is " + currentVersion); - publicVersion = VersionChecker.readStringFromURL(); - } catch (IOException e) { - Bukkit.getLogger().warning("[EliteMobs] Couldn't check latest version"); - return; - } - - if (Double.parseDouble(currentVersion.split("\\.")[0]) < Double.parseDouble(publicVersion.split("\\.")[0])) { - outOfDateHandler(); - return; - } - if (Double.parseDouble(currentVersion.split("\\.")[1]) < Double.parseDouble(publicVersion.split("\\.")[1])){ - outOfDateHandler(); - return; - } - if (Double.parseDouble(currentVersion.split("\\.")[2]) < Double.parseDouble(publicVersion.split("\\.")[2])){ - outOfDateHandler(); - return; - } + private VersionChecker() { + } - Bukkit.getLogger().warning("[EliteMobs] You are running the latest version!"); + public static void check() { + checkPluginVersion(); + checkDungeonVersions(); + } - pluginIsUpToDate = true; + private static void checkPluginVersion() { + new BukkitRunnable() { + @Override + public void run() { + String currentVersion = MetadataHandler.PLUGIN.getDescription().getVersion(); + boolean snapshot = false; + if (currentVersion.contains("SNAPSHOT")) { + snapshot = true; + currentVersion = currentVersion.split("-")[0]; + } + String publicVersion = ""; + + try { + Bukkit.getLogger().info("[EliteMobs] Latest public release is " + VersionChecker.readStringFromURL("https://api.spigotmc.org/legacy/update.php?resource=40090")); + Bukkit.getLogger().info("[EliteMobs] Your version is " + MetadataHandler.PLUGIN.getDescription().getVersion()); + publicVersion = VersionChecker.readStringFromURL("https://api.spigotmc.org/legacy/update.php?resource=40090"); + } catch (IOException e) { + Bukkit.getLogger().warning("[EliteMobs] Couldn't check latest version"); + return; + } + + if (Double.parseDouble(currentVersion.split("\\.")[0]) < Double.parseDouble(publicVersion.split("\\.")[0])) { + outOfDateHandler(); + return; + } + + if (Double.parseDouble(currentVersion.split("\\.")[0]) == Double.parseDouble(publicVersion.split("\\.")[0])) { + + if (Double.parseDouble(currentVersion.split("\\.")[1]) < Double.parseDouble(publicVersion.split("\\.")[1])) { + outOfDateHandler(); + return; + } + + if (Double.parseDouble(currentVersion.split("\\.")[1]) == Double.parseDouble(publicVersion.split("\\.")[1])) { + if (Double.parseDouble(currentVersion.split("\\.")[2]) < Double.parseDouble(publicVersion.split("\\.")[2])) { + outOfDateHandler(); + return; + } + } + } + + if (!snapshot) + Bukkit.getLogger().info("[EliteMobs] You are running the latest version!"); + else + new InfoMessage("You are running a snapshot version! You can check for updates in the #releases channel on the EliteMobs Discord!"); + + pluginIsUpToDate = true; + } + }.runTaskAsynchronously(MetadataHandler.PLUGIN); + } + private static void checkDungeonVersions() { + Bukkit.getScheduler().runTaskAsynchronously(MetadataHandler.PLUGIN, () -> { + outdatedDungeons.clear(); + for (Minidungeon minidungeon : Minidungeon.getMinidungeons().values()) + if (minidungeon.isInstalled()) { + if (!minidungeon.getDungeonPackagerConfigFields().isDefaultDungeon()) continue; + try { + String versionString = readStringFromURL("https://www.magmaguy.com/api/" + minidungeon.getDungeonPackagerConfigFields().getFilename().replace(".yml", "")); + int releaseVersion = Integer.parseInt(versionString); + if (minidungeon.getDungeonPackagerConfigFields().getDungeonVersion() < releaseVersion) { + minidungeon.setOutOfDate(true); + outdatedDungeons.add(minidungeon); + new WarningMessage("Dungeon " + minidungeon.getDungeonPackagerConfigFields().getName() + " is outdated! You should go download the updated version! Link: " + minidungeon.getDungeonPackagerConfigFields().getDownloadLink()); + } + } catch (Exception exception) { + new WarningMessage("Failed to get version for minidungeon " + minidungeon.getDungeonPackagerConfigFields().getFilename() + "! The URL " + "https://www.magmaguy.com/api/" + minidungeon.getDungeonPackagerConfigFields().getFilename().replace(".yml", "") + " could not be reached!"); + } + } + }); } - private static String readStringFromURL() throws IOException { + private static String readStringFromURL(String url) throws IOException { - try (Scanner scanner = new Scanner(new URL("https://api.spigotmc.org/legacy/update.php?resource=40090").openStream(), + try (Scanner scanner = new Scanner(new URL(url).openStream(), StandardCharsets.UTF_8.toString())) { scanner.useDelimiter("\\A"); return scanner.hasNext() ? scanner.next() : ""; @@ -55,11 +114,51 @@ private static String readStringFromURL() throws IOException { } - private static void outOfDateHandler(){ + private static void outOfDateHandler() { - Bukkit.getLogger().warning("[EliteMobs] A newer version of this plugin is available for download!"); + new WarningMessage("[EliteMobs] A newer version of this plugin is available for download!"); pluginIsUpToDate = false; } + public static class VersionCheckerEvents implements Listener { + @EventHandler + public void onPlayerLogin(PlayerJoinEvent event) { + + if (!event.getPlayer().hasPermission("elitemobs.versionnotification")) return; + + new BukkitRunnable() { + @Override + public void run() { + if (!event.getPlayer().isOnline()) return; + if (!pluginIsUpToDate) + event.getPlayer().sendMessage(ChatColorConverter.convert("&a[EliteMobs] &cYour version of EliteMobs is outdated." + + " &aYou can download the latest version from &3&n&ohttps://www.spigotmc.org/resources/%E2%9A%94elitemobs%E2%9A%94.40090/")); + if (!outdatedDungeons.isEmpty()) { + event.getPlayer().sendMessage(ChatColorConverter.convert("&a[EliteMobs] &cThe following dungeons are outdated:")); + for (Minidungeon minidungeon : outdatedDungeons) + event.getPlayer().sendMessage(ChatColorConverter.convert( + "&c- " + minidungeon.getDungeonPackagerConfigFields().getName())); + event.getPlayer().spigot().sendMessage( + SpigotMessage.simpleMessage("&8[EliteMobs]&f You can download the update on "), + SpigotMessage.hoverLinkMessage( + "&9&npatreon.com/magmaguy", "Click for Patreon link", "https://www.patreon.com/magmaguy" + ), + SpigotMessage.simpleMessage(" &for "), + SpigotMessage.hoverLinkMessage("&9&nmagmaguy.itch.io", "Click for itch.io link", "https://magmaguy.itch.io/"), + SpigotMessage.simpleMessage(" !")); + event.getPlayer().spigot().sendMessage( + SpigotMessage.simpleMessage("&2Updating is quick & easy! "), + SpigotMessage.hoverLinkMessage("&9&nClick here", "Click for wiki link", "https://github.com/MagmaGuy/EliteMobs/wiki/%5BGuide%5D-Quick-Setup#updating-dungeon-content"), + SpigotMessage.simpleMessage(" &2for info on how to install updates and "), + SpigotMessage.hoverLinkMessage("&9&nhere", "Discord support link", DiscordLinks.mainLink), + SpigotMessage.simpleMessage(" &2for the support room.") + ); + } + } + }.runTaskLater(MetadataHandler.PLUGIN, 20L * 3); + + } + } + } diff --git a/src/main/java/com/magmaguy/elitemobs/versionnotifier/VersionWarner.java b/src/main/java/com/magmaguy/elitemobs/versionnotifier/VersionWarner.java deleted file mode 100644 index 84eb73a95..000000000 --- a/src/main/java/com/magmaguy/elitemobs/versionnotifier/VersionWarner.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.magmaguy.elitemobs.versionnotifier; - -import com.magmaguy.elitemobs.ChatColorConverter; -import com.magmaguy.elitemobs.MetadataHandler; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerLoginEvent; -import org.bukkit.scheduler.BukkitRunnable; - -public class VersionWarner implements Listener { - - @EventHandler - public void onPlayerLogin(PlayerLoginEvent event) { - - if (!event.getPlayer().hasPermission("elitemobs.versionnotification")) return; - - new BukkitRunnable() { - @Override - public void run() { - event.getPlayer().sendMessage(ChatColorConverter.convert("&a[EliteMobs] &cYour version of EliteMobs is outdated." + - " &aYou can download the latest version from &3&n&ohttps://www.spigotmc.org/resources/%E2%9A%94elitemobs%E2%9A%94.40090/")); - } - }.runTaskLater(MetadataHandler.PLUGIN, 20*3); - - - } - -} diff --git a/src/main/java/com/magmaguy/elitemobs/worlds/CustomWorldLoading.java b/src/main/java/com/magmaguy/elitemobs/worlds/CustomWorldLoading.java new file mode 100644 index 000000000..2330372ab --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/worlds/CustomWorldLoading.java @@ -0,0 +1,52 @@ +package com.magmaguy.elitemobs.worlds; + +import com.magmaguy.elitemobs.config.AdventurersGuildConfig; +import com.magmaguy.elitemobs.utils.InfoMessage; +import com.magmaguy.elitemobs.utils.WarningMessage; +import org.bukkit.Bukkit; +import org.bukkit.WorldCreator; + +import java.io.File; +import java.util.Objects; + +public class CustomWorldLoading { + + private CustomWorldLoading() { + } + + public static void startupWorldInitialization() { + File folder = new File(Bukkit.getWorldContainer().getAbsolutePath()); + File[] listOfFiles = folder.listFiles(); + + assert listOfFiles != null; + for (File listOfFile : listOfFiles) { + if (listOfFile.isDirectory() && listOfFile.getName().equals(AdventurersGuildConfig.getGuildWorldName())) { + new InfoMessage("[EliteMobs] World " + AdventurersGuildConfig.getGuildWorldName() + " found! Loading it in..."); + try { + WorldCreator worldCreator = new WorldCreator(AdventurersGuildConfig.getGuildWorldName()); + Objects.requireNonNull(Bukkit.createWorld(worldCreator)).setKeepSpawnInMemory(false); + new InfoMessage("[EliteMobs] World " + AdventurersGuildConfig.getGuildWorldName() + + " has been successfully loaded! It can be accessed through the '/ag' command, unless you changed that config option!"); + } catch (Exception ex) { + new WarningMessage("Failed to generate Adventurer's Guild World!"); + ex.printStackTrace(); + } + break; + } + } + + } + + public static boolean adventurersGuildWorldExists() { + File folder = new File(Bukkit.getWorldContainer().getAbsolutePath()); + File[] listOfFiles = folder.listFiles(); + + assert listOfFiles != null; + for (File listOfFile : listOfFiles) + if (listOfFile.isDirectory() && + listOfFile.getName().equals(AdventurersGuildConfig.getGuildWorldName())) + return true; + return false; + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/wormhole/VisualEffects.java b/src/main/java/com/magmaguy/elitemobs/wormhole/VisualEffects.java new file mode 100644 index 000000000..64e323301 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/wormhole/VisualEffects.java @@ -0,0 +1,159 @@ +package com.magmaguy.elitemobs.wormhole; + +import com.magmaguy.elitemobs.config.WormholesConfig; +import com.magmaguy.elitemobs.config.wormholes.WormholeConfigFields; +import com.magmaguy.elitemobs.utils.WarningMessage; +import lombok.Getter; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.List; + +public class VisualEffects { + private final WormholeConfigFields wormholeConfigFields; + private final List cachedLocations = new ArrayList<>(); + @Getter + private final List> cachedRotations = new ArrayList<>(); + + public VisualEffects(WormholeConfigFields wormholeConfigFields) { + this.wormholeConfigFields = wormholeConfigFields; + initializeVisualEffect(); + } + + private void initializeVisualEffect() { + switch (wormholeConfigFields.getStyle()) { + case CUBE: + generateCube(); + break; + case CRYSTAL: + generateCrystal(); + break; + case ICOSAHEDRON: + generateIcosahedron(); + break; + default: + new WarningMessage("Missing com.magmaguy.elitemobs.wormhole style for " + wormholeConfigFields.getStyle()); + } + } + + private void generateCrystal() { + //top + Vector top = new Vector(0, 1, 0).multiply(wormholeConfigFields.getSizeMultiplier()); + cachedLocations.add(top); + //bottom + Vector bottom = new Vector(0, -1, 0).multiply(wormholeConfigFields.getSizeMultiplier()); + cachedLocations.add(bottom); + //front + Vector front = new Vector(.5, 0, 0).multiply(wormholeConfigFields.getSizeMultiplier()); + cachedLocations.add(front); + //side + Vector side = new Vector(0, 0, .5).multiply(wormholeConfigFields.getSizeMultiplier()); + cachedLocations.add(side); + + finishCuboidInitialization(top, bottom, front, side); + + } + + private void generateCube() { + //top + Vector top = new Vector(0, 1, 0).multiply(wormholeConfigFields.getSizeMultiplier()); + cachedLocations.add(top); + //bottom + Vector bottom = new Vector(0, -1, 0).multiply(wormholeConfigFields.getSizeMultiplier()); + cachedLocations.add(bottom); + //front + Vector front = new Vector(1, 0, 0).multiply(wormholeConfigFields.getSizeMultiplier()); + cachedLocations.add(front); + //side + Vector side = new Vector(0, 0, 1).multiply(wormholeConfigFields.getSizeMultiplier()); + cachedLocations.add(side); + + finishCuboidInitialization(top, bottom, front, side); + + } + + private void generateIcosahedron() { + Vector top = new Vector(0, 1, 0).multiply(wormholeConfigFields.getSizeMultiplier()); + cachedLocations.add(top); + Vector offsetTopPoint = new Vector(1, .5, 0).multiply(wormholeConfigFields.getSizeMultiplier()); + List topPentagon = getPentagonVectors(top, offsetTopPoint); + + Vector bottom = new Vector(0, -1, 0).multiply(wormholeConfigFields.getSizeMultiplier()); + Vector offsetBottomPoint = new Vector(1, -.5, 0).multiply(wormholeConfigFields.getSizeMultiplier()); + offsetBottomPoint.rotateAroundY(2 * Math.PI / 5D / 2D); + List bottomPentagon = getPentagonVectors(bottom, offsetBottomPoint); + + for (int i = 0; i < topPentagon.size(); i++) { + trace(topPentagon.get(i), bottomPentagon.get(i)); + if (i + 1 < topPentagon.size() - 1) + trace(topPentagon.get(i + 1), bottomPentagon.get(i)); + } + trace(topPentagon.get(0), bottomPentagon.get(4)); + cacheRotations(); + } + + private List getPentagonVectors(Vector centerPosition, Vector offsetPosition) { + List pentagonVectors = new ArrayList<>(); + for (int i = 0; i < 6; i++) { + Vector rotatedVector = offsetPosition.clone().rotateAroundY(2 * Math.PI / 5D * i).clone(); + if (i > 0) + trace(pentagonVectors.get(i - 1), rotatedVector); + trace(centerPosition, rotatedVector); + pentagonVectors.add(rotatedVector); + } + trace(pentagonVectors.get(0), pentagonVectors.get(pentagonVectors.size() - 1)); + return pentagonVectors; + } + + private void finishCuboidInitialization(Vector top, Vector bottom, Vector front, Vector side) { + trace(top, front); + trace(bottom, front); + trace(front, side); + + List otherSidesList = new ArrayList<>(); + + for (int i = 1; i < 4; i++) { + double rotation = Math.PI / 2 * i; + for (Vector vector : cachedLocations) { + Vector rotatedVector = vector.clone().rotateAroundY(rotation); + if (rotatedVector.getX() != vector.getX() || rotatedVector.getZ() != vector.getZ()) + otherSidesList.add(rotatedVector); + } + } + + cachedLocations.addAll(otherSidesList); + + cacheRotations(); + } + + private void cacheRotations() { + double rotationPointCount = 100; + for (int i = 0; i < rotationPointCount; i++) { + double rotation = (Math.PI * 2) / rotationPointCount * i; + List vectors = new ArrayList<>(); + for (Vector vector : cachedLocations) { + vectors.add(vector.clone().rotateAroundY(rotation)); + } + cachedRotations.add(vectors); + } + } + + private void trace(Vector source, Vector target) { + Vector ray = target.clone().subtract(source).normalize().multiply(.2); + Vector clonedSource = source.clone(); + int counter = 0; + while (clonedSource.distance(target) > 0.1 && counter < 20) { + if (WormholesConfig.isReducedParticlesMode()) { + if (counter % 2 == 0) { + clonedSource = clonedSource.add(ray); + cachedLocations.add(clonedSource.clone()); + } + } else { + clonedSource = clonedSource.add(ray); + cachedLocations.add(clonedSource.clone()); + } + counter++; + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/wormhole/Wormhole.java b/src/main/java/com/magmaguy/elitemobs/wormhole/Wormhole.java new file mode 100644 index 000000000..b49ac7241 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/wormhole/Wormhole.java @@ -0,0 +1,107 @@ +package com.magmaguy.elitemobs.wormhole; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.config.WormholesConfig; +import com.magmaguy.elitemobs.config.wormholes.WormholeConfigFields; +import com.magmaguy.elitemobs.dungeons.Minidungeon; +import com.magmaguy.elitemobs.utils.ConfigurationLocation; +import com.magmaguy.elitemobs.utils.DiscordLinks; +import com.magmaguy.elitemobs.utils.InfoMessage; +import com.magmaguy.elitemobs.utils.WarningMessage; +import lombok.Getter; +import lombok.Setter; +import org.bukkit.Color; +import org.bukkit.Location; +import org.bukkit.entity.Player; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; + +public class Wormhole { + @Getter + private static final HashSet wormholes = new HashSet<>(); + @Getter + private static final HashSet playerCooldowns = new HashSet<>(); + @Getter + private final WormholeConfigFields wormholeConfigFields; + @Getter + private final WormholeEntry wormholeEntry1; + @Getter + private final WormholeEntry wormholeEntry2; + @Getter + private final Color particleColor; + @Getter + @Setter + private String portalMissingMessage = null; + @Getter + @Setter + private String opMessage = null; + @Getter + private List> cachedRotations = new ArrayList<>(); + + public Wormhole(WormholeConfigFields wormholeConfigFields) { + this.wormholeConfigFields = wormholeConfigFields; + this.particleColor = Color.fromRGB(wormholeConfigFields.getParticleColor()); + if (!wormholeConfigFields.getStyle().equals(WormholeStyle.NONE)) { + this.cachedRotations = new VisualEffects(wormholeConfigFields).getCachedRotations(); + } + if (wormholeConfigFields.getLocation1().contains(",")) { + wormholeEntry1 = new WormholeEntry(ConfigurationLocation.serialize(wormholeConfigFields.getLocation1()), this, getWormholeConfigFields().getLocation1Text()); + } else { + wormholeEntry1 = new WormholeEntry(getDungeonLocation(wormholeConfigFields.getLocation1()), this, getWormholeConfigFields().getLocation1Text()); + } + if (wormholeConfigFields.getLocation2().contains(",")) { + wormholeEntry2 = new WormholeEntry(ConfigurationLocation.serialize(wormholeConfigFields.getLocation2()), this, getWormholeConfigFields().getLocation2Text()); + } else { + wormholeEntry2 = new WormholeEntry(getDungeonLocation(wormholeConfigFields.getLocation2()), this, getWormholeConfigFields().getLocation2Text()); + } + wormholes.add(this); + } + + public static void shutdown() { + for (Wormhole wormhole : wormholes) + wormhole.stop(); + wormholes.clear(); + WormholeEntry.getWormholeEntries().clear(); + } + + private Location getDungeonLocation(String dungeonFilename) { + Minidungeon minidungeon = Minidungeon.getMinidungeons().get(dungeonFilename); + if (minidungeon == null) { + new WarningMessage("Dungeon " + dungeonFilename + " is not a valid dungeon packager name! Wormhole " + getWormholeConfigFields().getFilename() + " will not lead anywhere."); + setPortalMissingMessage(WormholesConfig.getDefaultPortalMissingMessage()); + return null; + } + if (!minidungeon.isDownloaded() || !minidungeon.isInstalled()) { + new InfoMessage("Wormhole " + getWormholeConfigFields().getFilename() + " will not lead anywhere because the dungeon " + dungeonFilename + " is not installed!"); + setPortalMissingMessage(WormholesConfig.getDungeonNotInstalledMessage().replace("$dungeonID", minidungeon.getDungeonPackagerConfigFields().getName())); + + this.opMessage = ChatColorConverter.convert( + "&8[EliteMobs - OP-only message] &fDownload links are available on &9https://magmaguy.itch.io/ &f" + + "(free and premium) and &9https://www.patreon.com/magmaguy &f(premium). You can check the difference " + + "between the two and get support here: " + DiscordLinks.mainLink); + + return null; + } + Vector offsetVector = minidungeon.getTeleportLocation().getDirection().clone().setY(0).normalize() + .multiply(1.5 * getWormholeConfigFields().getSizeMultiplier()) + .setY(-1 * getWormholeConfigFields().getSizeMultiplier()); + + return minidungeon.getTeleportLocation().clone().subtract(offsetVector); + } + + private void stop() { + wormholeEntry1.stop(); + wormholeEntry2.stop(); + } + + public enum WormholeStyle { + NONE, + CRYSTAL, + ICOSAHEDRON, + CUBE + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/wormhole/WormholeEntry.java b/src/main/java/com/magmaguy/elitemobs/wormhole/WormholeEntry.java new file mode 100644 index 000000000..b458e55f3 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/wormhole/WormholeEntry.java @@ -0,0 +1,103 @@ +package com.magmaguy.elitemobs.wormhole; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.entitytracker.EntityTracker; +import com.magmaguy.elitemobs.utils.ChunkLocationChecker; +import com.magmaguy.elitemobs.utils.ChunkVectorizer; +import lombok.Getter; +import lombok.Setter; +import org.bukkit.Location; +import org.bukkit.entity.ArmorStand; +import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; +import org.bukkit.event.Listener; +import org.bukkit.event.world.ChunkLoadEvent; +import org.bukkit.scheduler.BukkitTask; +import org.bukkit.util.Consumer; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; + +public class WormholeEntry { + @Getter + private static final HashMap> wormholeEntries = new HashMap<>(); + + @Getter + private final Location location; + @Getter + private final Wormhole wormhole; + @Getter + private final String locationText; + @Getter + @Setter + private BukkitTask wormholeTask; + @Getter + @Setter + private ArmorStand text; + + public WormholeEntry(Location location, Wormhole wormhole, String locationText) { + this.location = location; + this.wormhole = wormhole; + this.locationText = locationText; + if (location == null || location.getWorld() == null) return; + int chunkInt = ChunkVectorizer.hash(location.getChunk()); + if (wormholeEntries.get(chunkInt) == null) + wormholeEntries.put(chunkInt, new ArrayList<>(Arrays.asList(this))); + else { + List wEs = wormholeEntries.get(chunkInt); + wEs.add(this); + wormholeEntries.put(chunkInt, wEs); + } + if (ChunkLocationChecker.locationIsLoaded(location)) + chunkLoad(); + } + + public void chunkLoad() { + initializeTextDisplay(); + if (wormholeTask != null && !wormholeTask.isCancelled()) wormholeTask.cancel(); + wormholeTask = WormholeTask.startWormholeTask(this); + } + + public void chunkUnload() { + stop(); + } + + public void stop() { + if (wormholeTask != null) + wormholeTask.cancel(); + } + + private void initializeTextDisplay() { + if (text != null && text.isValid() && !text.isEmpty()) return; + if (locationText == null) return; + if (location == null || location.getWorld() == null) return; + text = location.getWorld().spawn( + location.clone().add(new Vector(0, 1.2, 0).multiply(wormhole.getWormholeConfigFields().getSizeMultiplier())), + ArmorStand.class, new Consumer() { + @Override + public void accept(ArmorStand armorStand) { + armorStand.setCustomName(ChatColorConverter.convert(locationText)); + armorStand.setCustomNameVisible(true); + armorStand.setMarker(true); + armorStand.setVisible(false); + armorStand.setGravity(false); + armorStand.setPersistent(false); + } + }); + EntityTracker.registerVisualEffects(text); + } + + public static class WormholeEntryEvent implements Listener { + @EventHandler(ignoreCancelled = true, priority = EventPriority.HIGH) + public void chunkLoadEvent(ChunkLoadEvent event) { + int chunk = ChunkVectorizer.hash(event.getChunk()); + if (!wormholeEntries.containsKey(chunk)) return; + for (WormholeEntry wormholeEntry : wormholeEntries.get(chunk)) + wormholeEntry.chunkLoad(); + } + } + +} diff --git a/src/main/java/com/magmaguy/elitemobs/wormhole/WormholeTask.java b/src/main/java/com/magmaguy/elitemobs/wormhole/WormholeTask.java new file mode 100644 index 000000000..e53661702 --- /dev/null +++ b/src/main/java/com/magmaguy/elitemobs/wormhole/WormholeTask.java @@ -0,0 +1,118 @@ +package com.magmaguy.elitemobs.wormhole; + +import com.magmaguy.elitemobs.ChatColorConverter; +import com.magmaguy.elitemobs.MetadataHandler; +import com.magmaguy.elitemobs.adventurersguild.GuildRank; +import com.magmaguy.elitemobs.config.TranslationConfig; +import com.magmaguy.elitemobs.config.WormholesConfig; +import com.magmaguy.elitemobs.economy.EconomyHandler; +import com.magmaguy.elitemobs.utils.ChunkLocationChecker; +import org.bukkit.Bukkit; +import org.bukkit.Location; +import org.bukkit.Particle; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.potion.PotionEffect; +import org.bukkit.potion.PotionEffectType; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scheduler.BukkitTask; +import org.bukkit.util.Vector; + +import java.util.ArrayList; +import java.util.Objects; + +public class WormholeTask { + private WormholeTask() { + } + + public static BukkitTask startWormholeTask(WormholeEntry wormholeEntry) { + return new BukkitRunnable() { + int counter = 0; + + @Override + public void run() { + if (!ChunkLocationChecker.locationIsLoaded(wormholeEntry.getLocation())) { + cancel(); + wormholeEntry.chunkUnload(); + return; + } + + for (Player player : Bukkit.getServer().getOnlinePlayers()) + checkPoint(wormholeEntry, player.getLocation(), player); + + if (!WormholesConfig.isNoParticlesMode() && + !wormholeEntry.getWormhole().getWormholeConfigFields().getStyle().equals(Wormhole.WormholeStyle.NONE)) { + if (counter >= wormholeEntry.getWormhole().getCachedRotations().size()) + counter = 0; + if (WormholesConfig.isReducedParticlesMode()) { + if (counter % 2 == 0) + visualEffect(counter, wormholeEntry); + } else + visualEffect(counter, wormholeEntry); + if (counter + 1 >= Integer.MAX_VALUE) + counter = 0; + counter++; + } + } + }.runTaskTimerAsynchronously(MetadataHandler.PLUGIN, 0, 5); + } + + private static void checkPoint(WormholeEntry wormholeEntry, Location playerLocation, Player player) { + if (wormholeEntry.getLocation() == null) return; + if (Wormhole.getPlayerCooldowns().contains(player)) return; + if (wormholeEntry.getWormhole().getWormholeConfigFields().getPermission() != null && + !wormholeEntry.getWormhole().getWormholeConfigFields().getPermission().isEmpty() && + !player.hasPermission(wormholeEntry.getWormhole().getWormholeConfigFields().getPermission())) + return; + if (!Objects.equals(wormholeEntry.getLocation().getWorld(), playerLocation.getWorld())) return; + if (wormholeEntry.getLocation().distance(playerLocation) > 1.5 * wormholeEntry.getWormhole().getWormholeConfigFields().getSizeMultiplier()) + return; + if (wormholeEntry.getWormhole().getWormholeConfigFields().getCoinCost() > 0) { + double coinCost = wormholeEntry.getWormhole().getWormholeConfigFields().getCoinCost() + + wormholeEntry.getWormhole().getWormholeConfigFields().getCoinCost() * GuildRank.currencyBonusMultiplier(player.getUniqueId()); + if (EconomyHandler.checkCurrency(player.getUniqueId()) < coinCost) { + player.sendMessage(ChatColorConverter.convert(TranslationConfig.getInsufficientCurrencyForWormholeMessage()).replace("$amount", "" + coinCost)); + return; + } else + EconomyHandler.subtractCurrency(player.getUniqueId(), coinCost); + } + + teleport(wormholeEntry, player); + } + + private static void teleport(WormholeEntry wormholeEntry, Player player) { + Location destination; + if (wormholeEntry == wormholeEntry.getWormhole().getWormholeEntry1()) + destination = wormholeEntry.getWormhole().getWormholeEntry2().getLocation(); + else destination = wormholeEntry.getWormhole().getWormholeEntry1().getLocation(); + if (destination == null || destination.getWorld() == null) { + if (wormholeEntry.getWormhole().getPortalMissingMessage() == null) + player.sendMessage(ChatColorConverter.convert(WormholesConfig.getDefaultPortalMissingMessage())); + else { + player.sendMessage(wormholeEntry.getWormhole().getPortalMissingMessage()); + if (player.isOp() || player.hasPermission("elitemobs.*")) + player.sendMessage(wormholeEntry.getWormhole().getOpMessage()); + } + return; + } + Bukkit.getScheduler().runTask(MetadataHandler.PLUGIN, () -> { + if (wormholeEntry.getWormhole().getWormholeConfigFields().isBlindPlayer()) + player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 20 * 2, 0)); + player.teleport(destination); + player.playSound(player.getLocation(), Sound.BLOCK_RESPAWN_ANCHOR_CHARGE, 1f, 1f); + player.setVelocity(destination.getDirection().normalize()); + Wormhole.getPlayerCooldowns().add(player); + Bukkit.getScheduler().scheduleSyncDelayedTask(MetadataHandler.PLUGIN, () -> Wormhole.getPlayerCooldowns().remove(player), 20 * 5L); + }); + + } + + private static void visualEffect(int counter, WormholeEntry wormholeEntry) { + for (Vector vector : new ArrayList(wormholeEntry.getWormhole().getCachedRotations().get(counter))) { + Location particleLocation = wormholeEntry.getLocation().clone().add(vector); + wormholeEntry.getLocation().getWorld().spawnParticle(Particle.REDSTONE, particleLocation.getX(), particleLocation.getY(), particleLocation.getZ(), + 1, 0, 0, 0, + 1, new Particle.DustOptions(wormholeEntry.getWormhole().getParticleColor(), 1)); + } + } +} diff --git a/src/main/resources/CustomEnchantments.yml b/src/main/resources/CustomEnchantments.yml deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/main/resources/EconomySettings.yml b/src/main/resources/EconomySettings.yml deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/main/resources/ItemsCustomLootList.yml b/src/main/resources/ItemsCustomLootList.yml deleted file mode 100644 index 59bb657b9..000000000 --- a/src/main/resources/ItemsCustomLootList.yml +++ /dev/null @@ -1,187 +0,0 @@ -Loot: - Magmaguy's Toothpick: - Item Type: WOOD_SWORD - Item Name: "&4Magmaguy&c's &aToothpick" - Item Lore: - - "&l&5Nearly mint condition!" - Enchantments: - - DAMAGE_ALL,1 - Potion Effects: - Drop Weight: dynamic - Scalability: dynamic - Rabbit Charm: - Item Type: RABBIT_FOOT - Item Name: "Rabbit Charm" - Item Lore: - - "With this charm, just about" - - "any destination is only a hop," - - "skip and a jump away!" - Enchantments: - - VANISHING_CURSE,1 - Potion Effects: - - JUMP,3,self,continuous - Drop Weight: 1 - Vampiric Charm: - Item Type: STICK - Item Name: "Vampiric Charm" - Item Lore: - - "No one can remember where this" - - "came from, and no one can" - - "forget how dangerous it is..." - Enchantments: - - VANISHING_CURSE,1 - Potion Effects: - - HEAL,1,self,onHit - - BLINDNESS,1,self,onHit - - SLOW,1,self,onHit - Drop Weight: 1 - Scorpion Charm: - Item Type: POISONOUS_POTATO - Item Name: "Scorpion Charm" - Item Lore: - - "Float like a butterfly," - - "sting like a bee," - - "poison like a potato!" - Enchantments: - - VANISHING_CURSE,1 - Potion Effects: - - POISON,1,target,onHit - Drop Weight: 1 - Chameleon Charm: - Item Type: LEATHER - Item Name: "Chameleon Charm" - Item Lore: - - "The colorful Chameleon can" - - "blend in just about anywhere, " - - "slowly creeping around..." - Enchantments: - - VANISHING_CURSE,1 - Potion Effects: - - INVISIBILITY,1,self,onHit - - SLOW,2,self,onHit - - BLINDNESS,1,self,onHit - Drop Weight: 1 - Shulker Charm: - Item Type: FEATHER - Item Name: "Shulker Charm" - Item Lore: - - "I believe I can fly" - - "I believe I can touch the sky" - - "And you're coming with me!" - Enchantments: - - VANISHING_CURSE,1 - Potion Effects: - - LEVITATION,1,self,onHit - - LEVITATION,2,target,onHit - Drop Weight: 1 - Elephant Charm: - Item Type: ANVIL - Item Name: "Elephant Charm" - Item Lore: - - "Gain the power of an elephant" - - "stampede, for the cost of the" - - "speed of an elephant stampede!" - Enchantments: - - VANISHING_CURSE,1 - Potion Effects: - - INCREASE_DAMAGE,2,self,onHit - - SLOW,4,self,onHit - Drop Weight: 1 - Cheetah Charm: - Item Type: GOLD_BOOTS - Item Name: "Cheetah Charm" - Item Lore: - - "Cheetahs can reach speeds of" - - "120 km/h... for about 60" - - "seconds. Make them count." - Enchantments: - - VANISHING_CURSE,1 - Potion Effects: - - SPEED,3,self,continuous - - HUNGER,1,self,continuous - Drop Weight: 1 - Lucky Charms: - Item Type: COOKIE - Item Name: "Lucky Charms" - Item Lore: - - "Part of a complete breakfast!" - - "Note: Absolutely not a part of" - - "a complete breakfast." - Enchantments: - - VANISHING_CURSE,1 - Potion Effects: - - LUCK,1,self,continuous - Drop Weight: 1 - Salamander Charm: - Item Type: BLAZE_POWDER - Item Name: "Salamander Charm" - Item Lore: - - "Almost as hot as MagmaGuy's" - - "new mixtape, coming out soon" - - "to an alleyway near you!" - Enchantments: - - VANISHING_CURSE,1 - Potion Effects: - - FIRE_RESISTANCE,1,self,continuous - Drop Weight: 1 - Berserker Charm: - Item Type: TOTEM - Item Name: "Berserker Charm" - Item Lore: - - "Lose yourself in the face of" - - "overwhelming adversity in more" - - "ways than one..." - Enchantments: - - VANISHING_CURSE,1 - Potion Effects: - - BLINDNESS,1,self,onHit - - FAST_DIGGING,1,self,onHit - Drop Weight: 1 - Firefly Charm: - Item Type: GLASS_BOTTLE - Item Name: "Firefly Charm" - Item Lore: - - "Light up the night!" - Enchantments: - - VANISHING_CURSE,1 - Potion Effects: - - NIGHT_VISION,1,self,continuous - - GLOWING,1,target,onHit - Drop Weight: 1 - Slowpoke Charm: - Item Type: CARROT_STICK - Item Name: "Slowpoke Charm" - Item Lore: - - "Let's just hope it doesn't hit" - - "itself in its confusion..." - Enchantments: - - VANISHING_CURSE,1 - Potion Effects: - - SLOW,1,self,onHit - - CONFUSION,1,target,onHit - Drop Weight: 1 - Fishy Charm: - Item Type: RAW_FISH - Item Name: "Fishy Charm" - Item Lore: - - "There's just something not" - - "quite right with this one..." - Enchantments: - - VANISHING_CURSE,1 - Potion Effects: - - WATER_BREATHING,1,self,continuous - Drop Weight: 1 - Owl Charm: - Item Type: ELYTRA - Item Name: "Owl Charm" - Item Lore: - - "Become the ultimate nocturnal" - - "predator!" - Enchantments: - - VANISHING_CURSE,1 - Potion Effects: - - GLOWING,1,target,onHit - - JUMP,3,self,continuous - - NIGHT_VISION,1,self,continuous - - WEAKNESS,1,self,continuous - Drop Weight: 0.1 \ No newline at end of file diff --git a/src/main/resources/ItemsUnique.yml b/src/main/resources/ItemsUnique.yml deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/main/resources/MobPowers.yml b/src/main/resources/MobPowers.yml deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/main/resources/README.md b/src/main/resources/README.md index ec9d876e1..5350f3be7 100644 --- a/src/main/resources/README.md +++ b/src/main/resources/README.md @@ -1,3 +1,7 @@ +[![Crowdin](https://badges.crowdin.net/elitemobs/localized.svg)](https://crowdin.com/project/elitemobs) + +[![BStats](https://bstats.org/signatures/bukkit/EliteMobs.svg)](https://bstats.org/plugin/bukkit/EliteMobs/1081) + Thank you for using EliteMobs! This plugin is made to both work from the very start with no additional config work and to be highly customizable. @@ -8,4 +12,119 @@ If you need support with this plugin, you can reach me at my discord support cha For all things EliteMobs related, you can go to my website to find all resources I've made available, such as the github page, the wiki, the custom loot maker, so on. -Hope you enjoy! If you do, leave rating on the resource page and / or buy me a coffee ! (paypal links can be found in the spigot resource page) \ No newline at end of file +Hope you enjoy! If you do, leave rating on the resource page and / or buy me a coffee ! (paypal links can be found in the spigot resource page) + + +# Dev notes: + +## API + +EliteMobs has a few basic APIs to interface with in the `com.magmaguy.elitemobs.api` package. Here's the breakdown: + +### DamageEliteMob + +Used for applying custom damage to Elite Mobs. Uses: +- Bypass EliteMobs' custom damage system for a specific damage event +- Apply an automatically recommended custom amount of damage which varies based on the tier of the boss. + +*Note:* the variable damage takes the elite's tier into account and deals more damage to higher tiers. It does not take the health multiplier into account for custom bosses for balance reasons. + +### EliteMobDamagedByEliteMobEvent + +Used for listening to moments when one Elite damages another Elite. Uses: +- Same as Bukkit's EntityDamagedByEntity event but for elites specifically +- Cancelling it might not work. Report if it doesn't. + +### EliteMobDamagedByPlayerAntiExploit +Used for listening to events which trigger an antiexploit **check** - doesn't necessarily mean that it detected an exploit. Uses: +- Same as Bukkit's EntityDamagedByEntity event but for elites specifically +- Can be cancelled + +### EliteMobDamagedByPlayerEvent: +Used for listening to moments when a player damages an Elite. Uses: + +- Same as Bukkit's EntityDamagedByEntity event but for players damaging elites specifically +- ***Important:*** can't be cancelled as it only fires after applying the damage + +### EliteMobDamagedEvent: +Used for listening to moments when an elite is damaged in general. Uses: + +- Same as Bukkit's EntityDamageEvent +- ***Important*** Cancelling this event might not 100% work, report if it doesn't + +### EliteMobDeathEvent: +Used to listening to moments when an elite is killed. Uses: + +- Same as Bukkit's EntityDeathEvent. + +### EliteMobEnterCombatEvent: +Used for listening to moments when an elite enters combat against a player. Uses: + +- Get the target (player only) of the Elite +- Get the elite which entered in combat + +#### EliteMobExitCombatEvent: +Used for listening to moments when an elite leaves combat against a player. Uses: + +- Get the elite which just let combat. + +### EliteMobsItemDetector: +Used for detecting whether an ItemStack is an EliteMobs ItemStack (like a custom item or a procedurally generated item). Uses: + +- Detect if an ItemStack is an EliteMobs custom or dynamic item. + +### EliteMobSpawnEvent: +Used for detecting when an Elite spawns. USes: + +- Detect when an Elite spawns +- Detect which Elite spawned + +### EliteMobTargetPlayerEvent: +Used for detecting when an Elite has targetted a player. Uses: + +- Detect when an Elite targets a player. +- Cancel an Elite's detection of a player. + +### GenericAntiExploitEvent + +Used for listening to moments when the antiexploit runs a check but no players damaged it. Uses: + +- Detect when the antiexploit is doing a non-player based exploit check +- Cancel an antiexploit check + +### PlayerDamagedByEliteMobEvent + +Used for listening to moments when players are damaged by an Elite. Uses: + +- Same as Bukkit's EntityDamageEvent + +--- + + +## To add new item enchantments: +1) Add new enchantment class to the `com.magmaguy.elitemobs.config.enchantments.premade` **extending** `EnchantmentsConfigFields` to initialize create its config file (naming convention: [EnchantmentName]Config) +2) Initialize enchantment in `CustomEnchantment` to initialize the config file +3) Add enchantment class to `com.magmaguy.elitemobs.items.customenchantments` **extending** `CustomEnchantment` to write the logic for the enchantment (naming convention [EnchantmentName]Enchantment) +4) Add a public static String called "key" to register using the ItemTagger class for persistent enchantment tracking +5) Add an entry to the parseEnchantments() method in `CustomItem` so custom items detect it correctly +6) (Alternative) Add an entry to `generateCustomEnchantments()` method in `EnchantmentGenerator` if the enchantment should appear in procedurally generated items + +Note: +- Don't forget to register events in `EventsRegistrer` if the part with logic in it requires events. +- Don't forget to use the damage bypass if the power is supposed to deal custom damage. Damage dealt by the player to an elite can be overwritten in `CombatSystem` through the static "bypass" boolean field - it makes the next damage dealt to the elite use the raw damage value. For correctly assigning damage, use Bukkit's `Damageable#damage(double amount, Entity source)` and assign the source to your player. + +## To add new powers to elites: + +to be documented + +## To add new events: + +to be documented + +## To add new default NPCs: + +to be documented + +## To add new mob types: + +to be documented \ No newline at end of file diff --git a/src/main/resources/READ_ME_FOR_TRANSLATIONS.yml b/src/main/resources/READ_ME_FOR_TRANSLATIONS.yml new file mode 100644 index 000000000..28db0e283 --- /dev/null +++ b/src/main/resources/READ_ME_FOR_TRANSLATIONS.yml @@ -0,0 +1 @@ +EliteMobs translations: https://crowdin.com/project/elitemobs \ No newline at end of file diff --git a/src/main/resources/ValidMobs.yml b/src/main/resources/ValidMobs.yml deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/main/resources/economySettings.yml b/src/main/resources/economySettings.yml deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/main/resources/mobPowers.yml b/src/main/resources/mobPowers.yml deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/main/resources/playerCache.yml b/src/main/resources/playerCache.yml deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/main/resources/playerMaxGuildRank.yml b/src/main/resources/playerMaxGuildRank.yml deleted file mode 100644 index e69de29bb..000000000 diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 4716e9dda..e7b9e6f7d 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,161 +1,127 @@ name: EliteMobs -version: 6.6.5 +version: 7.3.15-SNAPSHOT-5 author: MagmaGuy main: com.magmaguy.elitemobs.EliteMobs -softdepend: [Multiverse-Core] +api-version: 1.14 +softdepend: [ Multiverse-Core, WorldGuard, Vault, PlaceholderAPI, HolographicDisplays, DiscordSRV, LibsDisguises, WorldEdit, ModelEngine, Geyser-Spigot ] -commands: - elitemobs: - description: Catch-all command - usage: /elitemobs - aliases: [em, adventurerguild, adventurersguild, ag] permissions: elitemobs.*: description: Gives access to all elitemobs commands children: elitemobs.stats: true - elitemobs.shop: true - elitemobs.getloot: true - elitemobs.simloot: true - elitemobs.reload.configs: true - elitemobs.reload.loot: true - elitemobs.giveloot: true - elitemobs.spawnmob: true - elitemobs.killall.aggressiveelites: true - elitemobs.killall.passiveelites: true - elitemobs.killall.specificentity: true - elitemobs.currency.user: true - elitemobs.currency.subtract: true - elitemobs.currency.set: true - elitemobs.currency.check: true - elitemobs.currency.add: true - elitemobs.currency.cointop: true - elitemobs.scoreboard: false - elitemobs.events.*: true + elitemobs.checktier.others: true + elitemobs.versionnotification: true + elitemobs.currency.check.others: true default: op - elitemobs.currency.user: - description: Gives access to the commands users need to use the economy features (shops, paying other players) - children: - elitemobs.shop: true - elitemobs.customshop: true - elitemobs.currency.pay: true - elitemobs.currency.wallet: true - elitemobs.currency.cointop: true - elitemobs.killall.*: - description: Allows players to run all /elitemobs kill variations - children: - elitemobs.killall.aggressiveelites: true - elitemobs.killall.passiveelites: true - elitemobs.killall.specificentity: true - elitemobs.user: - description: Gives access to all recommended user commands - children: - elitemobs.stats: true - elitemobs.events.kraken: true - elitemobs.events.balrog: true - elitemobs.events.fae: true - elitemobs.checktier: true - elitemobs.adventurersguild: true - elitemobs.currency.user: true elitemobs.stats: description: Allows players to run /elitemobs stats default: op elitemobs.version: description: Allows players to run /elitemobs version default: true - elitemobs.getloot: - description: Allow players to run /elitemobs getloot - default: op - elitemobs.simloot: - description: Allow players to run /elitemobs simloot - default: op - elitemobs.reload: - decription: Allow players to run /elitemobs reload config - default: op - elitemobs.giveloot: - description: Allow players to run /elitemobs giveloot [playername] random/[loot name] - default: op - elitemobs.spawnmob: - description: Allow players to run /elitemobs SpawnMob [mobType] [mobLevel] [mobPower] [mobPower(just keep adding until done)] - default: op - elitemobs.spawnbossmob: - description: Allows players to run /elitemobs spawnbossmob [bossmob] - default: op - elitemobs.scoreboard: - description: Shows a scoreboard with info about the elite mob a player might be standing next to - default: false - elitemobs.killall.aggressiveelites: - description: Allows players to run /elitemobs kill aggressive - default: op - elitemobs.killall.passiveelites: - description: Allows players to run /elitemobs kill passive - default: op - elitemobs.killall.specificentity: - description: Allows players to run /elitemobs kill [entityType] - default: op - elitemobs.shop: - description: Allows players to run /elitemobs shop - default: op - elitemobs.customshop: - decription: Allows players to run /elitemobs customshop - default: op + elitemobs.shop.npc: + description: Allows players to interact with NPCs for dynamic shops + default: true + elitemobs.shop.command: + description: Allows players to open the dynamic shop menu through commands + default: true + elitemobs.customshop.npc: + description: Allows players to interact with NPCs for dynamic shops + default: true + elitemobs.customshop.command: + description: Allows players to open the dynamic shop menu through commands + default: true elitemobs.currency.pay: description: Allows players to run /elitemobs pay [username] [amount] - default: op - elitemobs.currency.add: - description: Allows players to run /elitemobs add [username] [amount] - default: op - elitemobs.currency.subtract: - description: Allows players to run /elitemobs subtract [username] [amount] - default: op - elitemobs.currency.set: - description: Allows players to run /elitemobs set [username] [amount] - default: op + default: true elitemobs.currency.check: - description: Allows players to run /elitemobs check [username] - default: op - elitemobs.currency.wallet: description: Allows players to run /elitemobs wallet + default: true + elitemobs.currency.check.others: + description: Allows players to run /elitemobs check [username] default: op - elitemobs.currency.cointop: - description: Allows players to run /elitemobs highscore - default: op - elitemobs.events.*: + elitemobs.events: description: Allows players to launch all events - children: - elitemobs.events.smalltreasuregoblin: true - elitemobs.events.deadmoon: true - default: op - elitemobs.events.smalltreasuregoblin: - description: Allows players to run /elitemobs event smalltreasuregoblin - default: op - elitemobs.events.deadmoon: - description: Allows players to run /elitemobs event deadmoon - default: op - elitemobs.events.kraken: - description: Allows players to randomly trigger the Kraken event when fishing; - defaut: true - elitemobs.events.balrog: - description: Allows players to randomly trigger the Balrog event when mining ore veins default: true - elitemobs.events.fae: - description: Allows players to randomly trigger the Fae event when chopping down trees - default: true - elitemobs.config.setmaxtier: - description: Allows players to run /elitemobs setmaxtier [tier] - default: op - elitemobs.checktier: - description: Allows players to run /elitemobs checktier - default: op - elitemobs.checkmaxtier: - description: Allows players to run /elitemobs checkmaxtier + elitemobs.checktier.others: + description: Allows players to run /elitemobs checktier [player] default: op elitemobs.gettier: - description: Allows players tu run /elitemobs gettier [tier] + description: Allows players to run /elitemobs gettier [tier] default: op elitemobs.versionnotification: description: Allows players to get notified about plugin updates default: op - elitemobs.adventurersguild: - description: Allows players to use the /ag command to set their difficulty level and get quests - default: true \ No newline at end of file + elitemobs.adventurersguild.teleport: + description: Allows players to teleport to the adventurer's guild hub using /ag + default: true + elitemobs.adventurersguild.command: + description: Allows players to rank menu using the /em adventurersguild command + default: true + elitemobs.rank.command: + description: Allows players to open the rank menu through /em rank + default: true + elitemobs.rank.npc: + description: Allows players to access the /em rank menu through NPCs + default: true + elitemobs.quest.command: + description: Allows players to take on quests via command + default: true + elitemobs.quest.npc: + description: Allows players to take on quests via EliteMobs NPC + default: true + elitemobs.dungeontp: + description: Allows players to teleport to an elitemobs-set location + default: true + elitemobs.spawntp: + description: Allows players to teleport to the default spawn location of the server. + default: true + elitemobs.back.npc: + description: Allows players to interact with an npc to go back to a previous location. + default: true + elitemobs.shareitem: + description: Shares a held Elite Item on chat. + default: true + elitemobs.scrap.npc: + description: Allows players to scrap items at an npc + default: true + elitemobs.scrap.command: + description: Allows players to scrap items using a command + default: true + elitemobs.smelt.command: + description: Allows players to smelt items using a command + default: true + elitemobs.smelt.npc: + description: Allows players to smelt items using an npc + default: true + elitemobs.repair.command: + description: Allows players to use the repair command to open the menu for repairing elite items + default: true + elitemobs.repair.npc: + description: Allows players to interact with the NPC for repairing items + default: true + elitemobs.refiner.command: + description: Allows players to use the refiner command to open the menu for upgrading Elite Scrap + default: true + elitemobs.refiner.npc: + description: Allows players to interact with the NPC for upgrading Elite Scrap + default: true + elitemobs.enhancer.command: + description: Allows players to use the enhancer command to open the menu for upgrading Elite Items + default: true + elitemobs.enhancer.npc: + description: Allows players to interact with the NPC for upgrading Elite Items + default: true + elitemobs.unbind.command: + description: Allows players to use the unbind command to open the menu for unbinding Elite Items + default: true + elitemobs.unbind.npc: + description: Allows players to interact with the unbinder NPC for unbind Elite Items + default: true + elitemobs.soulbind.bypass: + description: Allows users to bypass the soulbind restrictions. Only recommended for admins! + default: false + elitequest.*: + description: Used for quest-related permissions + default: not op \ No newline at end of file