From 5e0d4aa187e313fd9d75b0d94e943bb90196dc75 Mon Sep 17 00:00:00 2001 From: VQ9 <60553050+VQ9@users.noreply.github.com> Date: Sun, 17 Jan 2021 16:45:24 +0000 Subject: [PATCH 1/7] Create maven.yml no idea, probably something to do with actions --- .github/workflows/maven.yml | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) create mode 100644 .github/workflows/maven.yml diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml new file mode 100644 index 0000000..c8aeb3a --- /dev/null +++ b/.github/workflows/maven.yml @@ -0,0 +1,24 @@ +# This workflow will build a Java project with Maven +# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven + +name: Java CI with Maven + +on: + push: + branches: [ master ] + pull_request: + branches: [ master ] + +jobs: + build: + + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v2 + - name: Set up JDK 1.8 + uses: actions/setup-java@v1 + with: + java-version: 1.8 + - name: Build with Maven + run: mvn -B package --file pom.xml From d646e8a3b827e5290a98da16098d0e1c740634bb Mon Sep 17 00:00:00 2001 From: Noah <60553050+VQ9@users.noreply.github.com> Date: Tue, 6 Jul 2021 22:29:59 +0100 Subject: [PATCH 2/7] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index c0a8b94..936ed6a 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,6 @@ # Please visit (and fork from) the new repository that's actually being maintained: ## https://github.com/ThePM2/Specialized-Crates +**Correction, this is no longer open-source as the new maintainer has decided to close-source the source-code.** + This repository (https://github.com/ztowne13/Specialized-Crates) will no longer be updated or maintained: PM2 has taken over the project and will be updating it there! So please go check out the work that he's done and if you'd like to view the source code / fork it, do that from PM2's repository and not this one. From ecd557e645dfdabc651f49aa3b4444f0f5f712ab Mon Sep 17 00:00:00 2001 From: Noah <60553050+VQ9@users.noreply.github.com> Date: Tue, 6 Jul 2021 22:30:23 +0100 Subject: [PATCH 3/7] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 936ed6a..6756d8c 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,5 @@ # Please visit (and fork from) the new repository that's actually being maintained: -## https://github.com/ThePM2/Specialized-Crates +## ~https://github.com/ThePM2/Specialized-Crates~ **Correction, this is no longer open-source as the new maintainer has decided to close-source the source-code.** From 2965d3070461c5bfe20bc6bbd04319379659fff5 Mon Sep 17 00:00:00 2001 From: Noah <60553050+VQ9@users.noreply.github.com> Date: Tue, 6 Jul 2021 22:30:38 +0100 Subject: [PATCH 4/7] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 6756d8c..1d428d9 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Please visit (and fork from) the new repository that's actually being maintained: ## ~https://github.com/ThePM2/Specialized-Crates~ -**Correction, this is no longer open-source as the new maintainer has decided to close-source the source-code.** +##**Correction, this is no longer open-source as the new maintainer has decided to close-source the source-code.** This repository (https://github.com/ztowne13/Specialized-Crates) will no longer be updated or maintained: PM2 has taken over the project and will be updating it there! So please go check out the work that he's done and if you'd like to view the source code / fork it, do that from PM2's repository and not this one. From 39415d63a4dd9f8b52a9c6db521931c5b56cffe6 Mon Sep 17 00:00:00 2001 From: Noah <60553050+VQ9@users.noreply.github.com> Date: Tue, 6 Jul 2021 22:30:48 +0100 Subject: [PATCH 5/7] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 1d428d9..5b6db65 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # Please visit (and fork from) the new repository that's actually being maintained: ## ~https://github.com/ThePM2/Specialized-Crates~ -##**Correction, this is no longer open-source as the new maintainer has decided to close-source the source-code.** +## **Correction, this is no longer open-source as the new maintainer has decided to close-source the source-code.** This repository (https://github.com/ztowne13/Specialized-Crates) will no longer be updated or maintained: PM2 has taken over the project and will be updating it there! So please go check out the work that he's done and if you'd like to view the source code / fork it, do that from PM2's repository and not this one. From a95d66b4f2e048c4b288e4343aa4fc0059bca21e Mon Sep 17 00:00:00 2001 From: Noah <60553050+VQ9@users.noreply.github.com> Date: Tue, 6 Jul 2021 22:33:21 +0100 Subject: [PATCH 6/7] Delete .github/workflows directory --- .github/workflows/maven.yml | 24 ------------------------ 1 file changed, 24 deletions(-) delete mode 100644 .github/workflows/maven.yml diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml deleted file mode 100644 index c8aeb3a..0000000 --- a/.github/workflows/maven.yml +++ /dev/null @@ -1,24 +0,0 @@ -# This workflow will build a Java project with Maven -# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven - -name: Java CI with Maven - -on: - push: - branches: [ master ] - pull_request: - branches: [ master ] - -jobs: - build: - - runs-on: ubuntu-latest - - steps: - - uses: actions/checkout@v2 - - name: Set up JDK 1.8 - uses: actions/setup-java@v1 - with: - java-version: 1.8 - - name: Build with Maven - run: mvn -B package --file pom.xml From 9bd18b027902a07539cef01b18e6eb8e97f6bf5c Mon Sep 17 00:00:00 2001 From: VQ9 Date: Tue, 2 Nov 2021 18:13:23 +0000 Subject: [PATCH 7/7] Test --- build.gradle | 179 +++++ pom.xml | 8 +- .../me/ztowne13/customcrates/DataHandler.java | 177 ----- .../me/ztowne13/customcrates/Messages.java | 185 ----- .../me/ztowne13/customcrates/Settings.java | 163 ---- .../ztowne13/customcrates/SettingsValue.java | 585 -------------- .../customcrates/SpecializedCrates.java | 523 ------------ .../customcrates/api/CrateOpenEvent.java | 50 -- .../customcrates/commands/CommandCrate.java | 158 ---- .../customcrates/commands/CommandKey.java | 58 -- .../customcrates/commands/CommandRewards.java | 58 -- .../customcrates/commands/Commands.java | 49 -- .../customcrates/commands/sub/Claim.java | 59 -- .../customcrates/commands/sub/Config.java | 29 - .../customcrates/commands/sub/Debug.java | 111 --- .../commands/sub/DelAllCrateType.java | 26 - .../commands/sub/DeleteCrate.java | 34 - .../customcrates/commands/sub/Edit.java | 55 -- .../customcrates/commands/sub/Errors.java | 34 - .../customcrates/commands/sub/ForceOpen.java | 62 -- .../customcrates/commands/sub/GiveCrate.java | 116 --- .../customcrates/commands/sub/GiveKey.java | 151 ---- .../customcrates/commands/sub/Help.java | 29 - .../customcrates/commands/sub/Info.java | 24 - .../commands/sub/LastConfigMenu.java | 27 - .../customcrates/commands/sub/ListCrates.java | 22 - .../commands/sub/ListHistory.java | 33 - .../customcrates/commands/sub/Reload.java | 22 - .../customcrates/commands/sub/SpawnCrate.java | 53 -- .../customcrates/commands/sub/SubCommand.java | 61 -- .../commands/sub/ToggleParticles.java | 22 - .../commands/sub/VirtualCrates.java | 55 -- .../ztowne13/customcrates/crates/Crate.java | 299 ------- .../customcrates/crates/CrateSettings.java | 474 ----------- .../crates/CrateSettingsBuilder.java | 306 ------- .../customcrates/crates/CrateState.java | 9 - .../customcrates/crates/PlacedCrate.java | 192 ----- .../crates/SettingsConverter.java | 74 -- .../crateaction/AttemptCrateUseAction.java | 99 --- .../crateaction/AttemptKeyUseAction.java | 68 -- .../crates/crateaction/CrateAction.java | 190 ----- .../crates/crateaction/LeftClickAction.java | 57 -- .../customcrates/crates/options/CAction.java | 312 -------- .../crates/options/CFirework.java | 116 --- .../crates/options/CHologram.java | 287 ------- .../crates/options/CLuckyChest.java | 222 ------ .../crates/options/CMultiCrateInventory.java | 477 ----------- .../crates/options/CParticle.java | 276 ------- .../customcrates/crates/options/CReward.java | 271 ------- .../customcrates/crates/options/CSetting.java | 39 - .../customcrates/crates/options/CSound.java | 140 ---- .../crates/options/CrateItemHandler.java | 72 -- .../crates/options/KeyItemHandler.java | 180 ----- .../crates/options/ObtainType.java | 45 -- .../crates/options/actions/ActionEffect.java | 26 - .../options/actions/BukkitActionEffect.java | 49 -- .../options/actions/NMSActionEffect.java | 59 -- .../options/actions/actionbar/ActionBar.java | 10 - .../actions/actionbar/ActionBarV1_7_8.java | 41 - .../actionbar/ActionBarV1_9_10_11.java | 37 - .../crates/options/actions/title/Title.java | 52 -- .../options/actions/title/TitleV1_11.java | 403 ---------- .../actions/title/TitleV1_7_8_9_10.java | 400 ---------- .../options/holograms/DynamicHologram.java | 92 --- .../holograms/animations/Animation.java | 22 - .../holograms/animations/HoloAnimType.java | 44 -- .../holograms/animations/HoloAnimation.java | 46 -- .../animations/MultiLineChangeAnimation.java | 70 -- .../animations/TextChangeAnimation.java | 67 -- .../particles/BukkitParticleEffect.java | 97 --- .../options/particles/FireworkData.java | 287 ------- .../options/particles/NMSParticleEffect.java | 62 -- .../options/particles/ParticleData.java | 220 ------ .../options/particles/ParticleEffect.java | 203 ----- .../options/particles/effects/CirclePA.java | 50 -- .../particles/effects/DoubleSpiralPA.java | 64 -- .../particles/effects/GrowingSpiralPA.java | 71 -- .../effects/OffsetTiltedRingsPA.java | 69 -- .../particles/effects/PEAnimationType.java | 58 -- .../effects/ParticleAnimationEffect.java | 39 - .../options/particles/effects/SpiralPA.java | 58 -- .../particles/effects/TiltedRingsPA.java | 69 -- .../crates/options/rewards/Reward.java | 567 ------------- .../options/rewards/RewardConverter.java | 182 ----- .../displaymenu/RewardDisplayType.java | 29 - .../rewards/displaymenu/RewardDisplayer.java | 99 --- .../displaymenu/SimpleRewardDisplayer.java | 44 -- .../displaymenu/SortedRewardDisplayer.java | 61 -- .../custom/CustomRewardDisplayer.java | 158 ---- .../displaymenu/custom/DisplayPage.java | 276 ------- .../crates/options/sounds/SoundData.java | 54 -- .../types/animations/AnimationDataHolder.java | 123 --- .../types/animations/CrateAnimation.java | 248 ------ .../types/animations/CrateAnimationType.java | 147 ---- .../types/animations/block/NMSChestState.java | 36 - .../animations/block/OpenChestAnimation.java | 174 ---- .../animations/inventory/CSGOAnimation.java | 288 ------- .../inventory/CSGOAnimationDataHolder.java | 56 -- .../inventory/DiscoverAnimation.java | 393 --------- .../DiscoverAnimationDataHolder.java | 62 -- .../inventory/EncloseAnimation.java | 211 ----- .../inventory/EncloseAnimationDataHolder.java | 39 - .../InventoryAnimationDataHolder.java | 68 -- .../inventory/InventoryCrateAnimation.java | 156 ---- .../animations/inventory/MenuAnimation.java | 156 ---- .../inventory/MenuAnimationDataHolder.java | 33 - .../inventory/RouletteAnimation.java | 200 ----- .../RouletteAnimationDataHolder.java | 50 -- .../animations/minimal/GiveKeyAnimation.java | 54 -- .../minimal/GiveKeyAnimationDataHolder.java | 12 - .../types/display/CrateDisplayType.java | 12 - .../display/DynamicCratePlaceholder.java | 27 - .../crates/types/display/EntityType.java | 184 ----- .../types/display/MaterialPlaceholder.java | 55 -- .../display/npcs/Citizens2NPCPlaceHolder.java | 112 --- .../types/display/npcs/IdentifierTrait.java | 19 - .../types/display/npcs/MobPlaceholder.java | 103 --- .../interfaces/InventoryBuilder.java | 77 -- .../interfaces/InventoryUtils.java | 28 - .../externalhooks/EconomyHandler.java | 50 -- .../externalhooks/PlaceHolderAPIHandler.java | 188 ----- .../externalhooks/holograms/Hologram.java | 29 - .../holograms/HologramManager.java | 35 - .../holograms/cmi/ZripsHologram.java | 57 -- .../holograms/cmi/ZripsHologramManager.java | 17 - .../holograms/holograms/SainttXHologram.java | 65 -- .../holograms/SainttXHologramManager.java | 17 - .../holographicdisplays/HDHologram.java | 50 -- .../HDHologramManager.java | 17 - .../nohologram/NoHologramManager.java | 35 - .../interfaces/files/FileDataLoader.java | 181 ----- .../interfaces/files/FileHandler.java | 360 --------- .../interfaces/files/FileSettings.java | 13 - .../interfaces/igc/IGCDefaultItems.java | 36 - .../interfaces/igc/IGCListEditor.java | 181 ----- .../interfaces/igc/IGCListSelector.java | 144 ---- .../customcrates/interfaces/igc/IGCMenu.java | 179 ----- .../interfaces/igc/IGCMenuMain.java | 115 --- .../interfaces/igc/buttons/IGCButton.java | 17 - .../interfaces/igc/buttons/IGCButtonBack.java | 32 - .../igc/buttons/IGCButtonRewardFilter.java | 33 - .../interfaces/igc/buttons/IGCButtonType.java | 23 - .../igc/crates/IGCCrateActions.java | 172 ---- .../igc/crates/IGCCrateAnimation.java | 91 --- .../igc/crates/IGCCrateFireworks.java | 120 --- .../igc/crates/IGCCrateHolograms.java | 226 ------ .../igc/crates/IGCCrateParticle.java | 296 ------- .../igc/crates/IGCCrateParticleColor.java | 117 --- .../igc/crates/IGCCrateParticles.java | 174 ---- .../igc/crates/IGCCrateRewards.java | 148 ---- .../interfaces/igc/crates/IGCCrateSound.java | 118 --- .../interfaces/igc/crates/IGCCrateSounds.java | 108 --- .../igc/crates/IGCCratesEssentials.java | 287 ------- .../interfaces/igc/crates/IGCCratesMain.java | 240 ------ .../interfaces/igc/crates/IGCMenuCrate.java | 35 - .../interfaces/igc/crates/IGCMineCrate.java | 176 ----- .../igc/crates/IGCMultiCrateMain.java | 88 --- .../interfaces/igc/crates/IGCTierMenu.java | 26 - .../igc/crates/IGCTierSelector.java | 125 --- .../crates/crateanimations/IGCAnimCSGO.java | 213 ----- .../crateanimations/IGCAnimDiscover.java | 235 ------ .../crateanimations/IGCAnimEnclose.java | 122 --- .../crates/crateanimations/IGCAnimMenu.java | 99 --- .../crateanimations/IGCAnimOpenChest.java | 126 --- .../crateanimations/IGCAnimRoulette.java | 194 ----- .../crates/crateanimations/IGCAnimation.java | 32 - .../previeweditor/IGCCratePreviewEditor.java | 121 --- .../previeweditor/IGCCratePreviewMenu.java | 212 ----- .../IGCCratePreviewOrRewardMenu.java | 60 -- .../IGCCratePreviewPageChooser.java | 137 ---- .../previeweditor/IGCCratePreviewRewards.java | 143 ---- .../igc/fileconfigs/IGCMenuConfig.java | 92 --- .../fileconfigs/IGCMenuConfigCategory.java | 247 ------ .../igc/fileconfigs/IGCMenuCrateConfig.java | 172 ---- .../fileconfigs/IGCMenuCrateOrMulticrate.java | 111 --- .../igc/fileconfigs/IGCMenuCrates.java | 110 --- .../igc/fileconfigs/IGCMenuMessages.java | 86 -- .../igc/fileconfigs/IGCMenuSQL.java | 98 --- .../fileconfigs/rewards/IGCDragAndDrop.java | 119 --- .../fileconfigs/rewards/IGCMenuAddReward.java | 146 ---- .../rewards/IGCMenuFallbackReward.java | 86 -- .../IGCMenuFallbackRewardSelector.java | 124 --- .../fileconfigs/rewards/IGCMenuReward.java | 287 ------- .../fileconfigs/rewards/IGCMenuRewards.java | 158 ---- .../igc/inputmenus/AnvilInputMenu.java | 46 -- .../igc/inputmenus/ChatInputMenu.java | 47 -- .../interfaces/igc/inputmenus/InputMenu.java | 152 ---- .../igc/inputmenus/InputMenuGUI.java | 27 - .../igc/items/IGCColoredArmour.java | 95 --- .../interfaces/igc/items/IGCItemEditor.java | 334 -------- .../items/CompressedPotionEffect.java | 46 -- .../interfaces/items/EditableItem.java | 71 -- .../interfaces/items/ItemBuilder.java | 569 ------------- .../interfaces/items/NBTTagBuilder.java | 210 ----- .../interfaces/items/SaveableItem.java | 13 - .../interfaces/items/SaveableItemBuilder.java | 354 --------- .../items/attributes/BukkitGlowEffect.java | 35 - .../attributes/CompressedEnchantment.java | 52 -- .../interfaces/items/attributes/RGBColor.java | 41 - .../interfaces/logging/StatusLogger.java | 136 ---- .../interfaces/logging/StatusLoggerEvent.java | 748 ------------------ .../interfaces/logging/UpdateChecker.java | 107 --- .../customcrates/interfaces/sql/SQL.java | 219 ----- .../interfaces/sql/SQLConnection.java | 109 --- .../interfaces/sql/SQLQueryThread.java | 84 -- .../listeners/BlockBreakListener.java | 83 -- .../listeners/BlockPlaceListener.java | 45 -- .../listeners/BlockRemoveListener.java | 56 -- .../customcrates/listeners/ChatListener.java | 75 -- .../listeners/CommandPreprocessListener.java | 37 - .../listeners/DamageListener.java | 25 - .../listeners/InteractListener.java | 74 -- .../listeners/InventoryActionListener.java | 299 ------- .../listeners/NPCEventListener.java | 34 - .../listeners/PlayerConnectionListener.java | 43 - .../listeners/PluginEnableListener.java | 37 - .../listeners/TabCompleteListener.java | 166 ---- .../players/PlayerDataManager.java | 327 -------- .../customcrates/players/PlayerManager.java | 287 ------- .../players/data/DataHandler.java | 35 - .../players/data/FlatFileDataHandler.java | 69 -- .../data/IndividualFileDataHandler.java | 64 -- .../players/data/SQLDataHandler.java | 102 --- .../players/data/StorageType.java | 19 - .../players/data/VirtualCrateData.java | 42 - .../data/events/CrateCooldownEvent.java | 105 --- .../players/data/events/DataEvent.java | 23 - .../players/data/events/HistoryEvent.java | 103 --- .../customcrates/utils/ChatUtils.java | 131 --- .../customcrates/utils/CrateUtils.java | 41 - .../customcrates/utils/DebugUtils.java | 78 -- .../customcrates/utils/LocationUtils.java | 35 - .../ztowne13/customcrates/utils/NPCUtils.java | 122 --- .../utils/ReflectionUtilities.java | 155 ---- .../me/ztowne13/customcrates/utils/Utils.java | 268 ------- .../customcrates/utils/VersionUtils.java | 63 -- .../customcrates/SpecialisedCrates.kt | 418 ++++++++++ .../customcrates/api/SpecialisedCratesAPI.kt | 4 + .../customcrates/api/events/CrateOpenEvent.kt | 18 + .../customcrates/commands/ACFHandler.kt | 177 +++++ .../me/ztowne13/customcrates/crates/Crate.kt | 57 ++ .../customcrates/crates/CrateConfiguration.kt | 4 + .../customcrates/crates/CrateInstances.kt | 4 + .../ztowne13/customcrates/data/DataHandler.kt | 4 + .../ztowne13/customcrates/data/json/Read.kt | 4 + .../ztowne13/customcrates/data/json/Save.kt | 4 + .../me/ztowne13/customcrates/data/sql/Read.kt | 4 + .../me/ztowne13/customcrates/data/sql/Save.kt | 4 + .../customcrates/handlers/CrateHandler.kt | 4 + .../customcrates/handlers/EconomyHandler.kt | 4 + .../customcrates/holograms/HologramHandler.kt | 4 + .../holograms/types/HolographicDisplays.kt | 4 + .../listeners/BlockBreakListener.kt | 77 ++ .../listeners/BlockPlaceListener.kt | 33 + .../listeners/BlockRemoveListener.kt | 45 ++ .../customcrates/listeners/ChatListener.kt | 68 ++ .../listeners/CommandPreprocessListener.kt | 26 + .../customcrates/listeners/DamageListener.kt | 19 + .../listeners/InteractListener.kt | 62 ++ .../listeners/InventoryActionListener.kt | 276 +++++++ .../listeners/NPCEventListener.kt | 27 + .../listeners/PlayerConnectionListener.kt | 34 + .../listeners/PluginEnableListener.kt | 29 + .../listeners/TabCompleteListener.kt | 153 ++++ .../customcrates/particles/ParticleHandler.kt | 4 + .../customcrates/players/CratesPlayer.kt | 4 + .../ztowne13/customcrates/rewards/Reward.kt | 4 + .../customcrates/storage/StorageProvider.kt | 4 + .../me/ztowne13/customcrates/utils/Logging.kt | 23 + src/main/resources/plugin.yml | 10 +- 270 files changed, 1794 insertions(+), 29092 deletions(-) create mode 100644 build.gradle delete mode 100644 src/main/java/me/ztowne13/customcrates/DataHandler.java delete mode 100644 src/main/java/me/ztowne13/customcrates/Messages.java delete mode 100644 src/main/java/me/ztowne13/customcrates/Settings.java delete mode 100644 src/main/java/me/ztowne13/customcrates/SettingsValue.java delete mode 100644 src/main/java/me/ztowne13/customcrates/SpecializedCrates.java delete mode 100644 src/main/java/me/ztowne13/customcrates/api/CrateOpenEvent.java delete mode 100644 src/main/java/me/ztowne13/customcrates/commands/CommandCrate.java delete mode 100644 src/main/java/me/ztowne13/customcrates/commands/CommandKey.java delete mode 100644 src/main/java/me/ztowne13/customcrates/commands/CommandRewards.java delete mode 100644 src/main/java/me/ztowne13/customcrates/commands/Commands.java delete mode 100644 src/main/java/me/ztowne13/customcrates/commands/sub/Claim.java delete mode 100644 src/main/java/me/ztowne13/customcrates/commands/sub/Config.java delete mode 100644 src/main/java/me/ztowne13/customcrates/commands/sub/Debug.java delete mode 100644 src/main/java/me/ztowne13/customcrates/commands/sub/DelAllCrateType.java delete mode 100644 src/main/java/me/ztowne13/customcrates/commands/sub/DeleteCrate.java delete mode 100644 src/main/java/me/ztowne13/customcrates/commands/sub/Edit.java delete mode 100644 src/main/java/me/ztowne13/customcrates/commands/sub/Errors.java delete mode 100644 src/main/java/me/ztowne13/customcrates/commands/sub/ForceOpen.java delete mode 100644 src/main/java/me/ztowne13/customcrates/commands/sub/GiveCrate.java delete mode 100644 src/main/java/me/ztowne13/customcrates/commands/sub/GiveKey.java delete mode 100644 src/main/java/me/ztowne13/customcrates/commands/sub/Help.java delete mode 100644 src/main/java/me/ztowne13/customcrates/commands/sub/Info.java delete mode 100644 src/main/java/me/ztowne13/customcrates/commands/sub/LastConfigMenu.java delete mode 100644 src/main/java/me/ztowne13/customcrates/commands/sub/ListCrates.java delete mode 100644 src/main/java/me/ztowne13/customcrates/commands/sub/ListHistory.java delete mode 100644 src/main/java/me/ztowne13/customcrates/commands/sub/Reload.java delete mode 100644 src/main/java/me/ztowne13/customcrates/commands/sub/SpawnCrate.java delete mode 100644 src/main/java/me/ztowne13/customcrates/commands/sub/SubCommand.java delete mode 100644 src/main/java/me/ztowne13/customcrates/commands/sub/ToggleParticles.java delete mode 100644 src/main/java/me/ztowne13/customcrates/commands/sub/VirtualCrates.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/Crate.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/CrateSettings.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/CrateSettingsBuilder.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/CrateState.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/PlacedCrate.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/SettingsConverter.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/crateaction/AttemptCrateUseAction.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/crateaction/AttemptKeyUseAction.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/crateaction/CrateAction.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/crateaction/LeftClickAction.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/CAction.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/CFirework.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/CHologram.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/CLuckyChest.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/CMultiCrateInventory.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/CParticle.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/CReward.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/CSetting.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/CSound.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/CrateItemHandler.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/KeyItemHandler.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/ObtainType.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/actions/ActionEffect.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/actions/BukkitActionEffect.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/actions/NMSActionEffect.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/actions/actionbar/ActionBar.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/actions/actionbar/ActionBarV1_7_8.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/actions/actionbar/ActionBarV1_9_10_11.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/actions/title/Title.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/actions/title/TitleV1_11.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/actions/title/TitleV1_7_8_9_10.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/holograms/DynamicHologram.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/holograms/animations/Animation.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/holograms/animations/HoloAnimType.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/holograms/animations/HoloAnimation.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/holograms/animations/MultiLineChangeAnimation.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/holograms/animations/TextChangeAnimation.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/particles/BukkitParticleEffect.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/particles/FireworkData.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/particles/NMSParticleEffect.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/particles/ParticleData.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/particles/ParticleEffect.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/particles/effects/CirclePA.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/particles/effects/DoubleSpiralPA.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/particles/effects/GrowingSpiralPA.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/particles/effects/OffsetTiltedRingsPA.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/particles/effects/PEAnimationType.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/particles/effects/ParticleAnimationEffect.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/particles/effects/SpiralPA.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/particles/effects/TiltedRingsPA.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/rewards/Reward.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/rewards/RewardConverter.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/rewards/displaymenu/RewardDisplayType.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/rewards/displaymenu/RewardDisplayer.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/rewards/displaymenu/SimpleRewardDisplayer.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/rewards/displaymenu/SortedRewardDisplayer.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/rewards/displaymenu/custom/CustomRewardDisplayer.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/rewards/displaymenu/custom/DisplayPage.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/options/sounds/SoundData.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/types/animations/AnimationDataHolder.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/types/animations/CrateAnimation.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/types/animations/CrateAnimationType.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/types/animations/block/NMSChestState.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/types/animations/block/OpenChestAnimation.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/CSGOAnimation.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/CSGOAnimationDataHolder.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/DiscoverAnimation.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/DiscoverAnimationDataHolder.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/EncloseAnimation.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/EncloseAnimationDataHolder.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/InventoryAnimationDataHolder.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/InventoryCrateAnimation.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/MenuAnimation.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/MenuAnimationDataHolder.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/RouletteAnimation.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/RouletteAnimationDataHolder.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/types/animations/minimal/GiveKeyAnimation.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/types/animations/minimal/GiveKeyAnimationDataHolder.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/types/display/CrateDisplayType.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/types/display/DynamicCratePlaceholder.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/types/display/EntityType.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/types/display/MaterialPlaceholder.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/types/display/npcs/Citizens2NPCPlaceHolder.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/types/display/npcs/IdentifierTrait.java delete mode 100644 src/main/java/me/ztowne13/customcrates/crates/types/display/npcs/MobPlaceholder.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/InventoryBuilder.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/InventoryUtils.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/EconomyHandler.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/PlaceHolderAPIHandler.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/Hologram.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/HologramManager.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/cmi/ZripsHologram.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/cmi/ZripsHologramManager.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/holograms/SainttXHologram.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/holograms/SainttXHologramManager.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/holographicdisplays/HDHologram.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/holographicdisplays/HDHologramManager.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/nohologram/NoHologramManager.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/files/FileDataLoader.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/files/FileHandler.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/files/FileSettings.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/IGCDefaultItems.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/IGCListEditor.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/IGCListSelector.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/IGCMenu.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/IGCMenuMain.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/buttons/IGCButton.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/buttons/IGCButtonBack.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/buttons/IGCButtonRewardFilter.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/buttons/IGCButtonType.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateActions.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateAnimation.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateFireworks.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateHolograms.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateParticle.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateParticleColor.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateParticles.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateRewards.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateSound.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateSounds.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCratesEssentials.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCratesMain.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCMenuCrate.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCMineCrate.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCMultiCrateMain.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCTierMenu.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCTierSelector.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/crateanimations/IGCAnimCSGO.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/crateanimations/IGCAnimDiscover.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/crateanimations/IGCAnimEnclose.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/crateanimations/IGCAnimMenu.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/crateanimations/IGCAnimOpenChest.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/crateanimations/IGCAnimRoulette.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/crateanimations/IGCAnimation.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/previeweditor/IGCCratePreviewEditor.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/previeweditor/IGCCratePreviewMenu.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/previeweditor/IGCCratePreviewOrRewardMenu.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/previeweditor/IGCCratePreviewPageChooser.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/previeweditor/IGCCratePreviewRewards.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/IGCMenuConfig.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/IGCMenuConfigCategory.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/IGCMenuCrateConfig.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/IGCMenuCrateOrMulticrate.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/IGCMenuCrates.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/IGCMenuMessages.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/IGCMenuSQL.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/rewards/IGCDragAndDrop.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/rewards/IGCMenuAddReward.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/rewards/IGCMenuFallbackReward.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/rewards/IGCMenuFallbackRewardSelector.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/rewards/IGCMenuReward.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/rewards/IGCMenuRewards.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/inputmenus/AnvilInputMenu.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/inputmenus/ChatInputMenu.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/inputmenus/InputMenu.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/inputmenus/InputMenuGUI.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/items/IGCColoredArmour.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/igc/items/IGCItemEditor.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/items/CompressedPotionEffect.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/items/EditableItem.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/items/ItemBuilder.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/items/NBTTagBuilder.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/items/SaveableItem.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/items/SaveableItemBuilder.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/items/attributes/BukkitGlowEffect.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/items/attributes/CompressedEnchantment.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/items/attributes/RGBColor.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/logging/StatusLogger.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/logging/StatusLoggerEvent.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/logging/UpdateChecker.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/sql/SQL.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/sql/SQLConnection.java delete mode 100644 src/main/java/me/ztowne13/customcrates/interfaces/sql/SQLQueryThread.java delete mode 100644 src/main/java/me/ztowne13/customcrates/listeners/BlockBreakListener.java delete mode 100644 src/main/java/me/ztowne13/customcrates/listeners/BlockPlaceListener.java delete mode 100644 src/main/java/me/ztowne13/customcrates/listeners/BlockRemoveListener.java delete mode 100644 src/main/java/me/ztowne13/customcrates/listeners/ChatListener.java delete mode 100644 src/main/java/me/ztowne13/customcrates/listeners/CommandPreprocessListener.java delete mode 100644 src/main/java/me/ztowne13/customcrates/listeners/DamageListener.java delete mode 100644 src/main/java/me/ztowne13/customcrates/listeners/InteractListener.java delete mode 100644 src/main/java/me/ztowne13/customcrates/listeners/InventoryActionListener.java delete mode 100644 src/main/java/me/ztowne13/customcrates/listeners/NPCEventListener.java delete mode 100644 src/main/java/me/ztowne13/customcrates/listeners/PlayerConnectionListener.java delete mode 100644 src/main/java/me/ztowne13/customcrates/listeners/PluginEnableListener.java delete mode 100644 src/main/java/me/ztowne13/customcrates/listeners/TabCompleteListener.java delete mode 100644 src/main/java/me/ztowne13/customcrates/players/PlayerDataManager.java delete mode 100644 src/main/java/me/ztowne13/customcrates/players/PlayerManager.java delete mode 100644 src/main/java/me/ztowne13/customcrates/players/data/DataHandler.java delete mode 100644 src/main/java/me/ztowne13/customcrates/players/data/FlatFileDataHandler.java delete mode 100644 src/main/java/me/ztowne13/customcrates/players/data/IndividualFileDataHandler.java delete mode 100644 src/main/java/me/ztowne13/customcrates/players/data/SQLDataHandler.java delete mode 100644 src/main/java/me/ztowne13/customcrates/players/data/StorageType.java delete mode 100644 src/main/java/me/ztowne13/customcrates/players/data/VirtualCrateData.java delete mode 100644 src/main/java/me/ztowne13/customcrates/players/data/events/CrateCooldownEvent.java delete mode 100644 src/main/java/me/ztowne13/customcrates/players/data/events/DataEvent.java delete mode 100644 src/main/java/me/ztowne13/customcrates/players/data/events/HistoryEvent.java delete mode 100644 src/main/java/me/ztowne13/customcrates/utils/ChatUtils.java delete mode 100644 src/main/java/me/ztowne13/customcrates/utils/CrateUtils.java delete mode 100644 src/main/java/me/ztowne13/customcrates/utils/DebugUtils.java delete mode 100644 src/main/java/me/ztowne13/customcrates/utils/LocationUtils.java delete mode 100644 src/main/java/me/ztowne13/customcrates/utils/NPCUtils.java delete mode 100644 src/main/java/me/ztowne13/customcrates/utils/ReflectionUtilities.java delete mode 100644 src/main/java/me/ztowne13/customcrates/utils/Utils.java delete mode 100644 src/main/java/me/ztowne13/customcrates/utils/VersionUtils.java create mode 100644 src/main/kotlin/me/ztowne13/customcrates/SpecialisedCrates.kt create mode 100644 src/main/kotlin/me/ztowne13/customcrates/api/SpecialisedCratesAPI.kt create mode 100644 src/main/kotlin/me/ztowne13/customcrates/api/events/CrateOpenEvent.kt create mode 100644 src/main/kotlin/me/ztowne13/customcrates/commands/ACFHandler.kt create mode 100644 src/main/kotlin/me/ztowne13/customcrates/crates/Crate.kt create mode 100644 src/main/kotlin/me/ztowne13/customcrates/crates/CrateConfiguration.kt create mode 100644 src/main/kotlin/me/ztowne13/customcrates/crates/CrateInstances.kt create mode 100644 src/main/kotlin/me/ztowne13/customcrates/data/DataHandler.kt create mode 100644 src/main/kotlin/me/ztowne13/customcrates/data/json/Read.kt create mode 100644 src/main/kotlin/me/ztowne13/customcrates/data/json/Save.kt create mode 100644 src/main/kotlin/me/ztowne13/customcrates/data/sql/Read.kt create mode 100644 src/main/kotlin/me/ztowne13/customcrates/data/sql/Save.kt create mode 100644 src/main/kotlin/me/ztowne13/customcrates/handlers/CrateHandler.kt create mode 100644 src/main/kotlin/me/ztowne13/customcrates/handlers/EconomyHandler.kt create mode 100644 src/main/kotlin/me/ztowne13/customcrates/holograms/HologramHandler.kt create mode 100644 src/main/kotlin/me/ztowne13/customcrates/holograms/types/HolographicDisplays.kt create mode 100644 src/main/kotlin/me/ztowne13/customcrates/listeners/BlockBreakListener.kt create mode 100644 src/main/kotlin/me/ztowne13/customcrates/listeners/BlockPlaceListener.kt create mode 100644 src/main/kotlin/me/ztowne13/customcrates/listeners/BlockRemoveListener.kt create mode 100644 src/main/kotlin/me/ztowne13/customcrates/listeners/ChatListener.kt create mode 100644 src/main/kotlin/me/ztowne13/customcrates/listeners/CommandPreprocessListener.kt create mode 100644 src/main/kotlin/me/ztowne13/customcrates/listeners/DamageListener.kt create mode 100644 src/main/kotlin/me/ztowne13/customcrates/listeners/InteractListener.kt create mode 100644 src/main/kotlin/me/ztowne13/customcrates/listeners/InventoryActionListener.kt create mode 100644 src/main/kotlin/me/ztowne13/customcrates/listeners/NPCEventListener.kt create mode 100644 src/main/kotlin/me/ztowne13/customcrates/listeners/PlayerConnectionListener.kt create mode 100644 src/main/kotlin/me/ztowne13/customcrates/listeners/PluginEnableListener.kt create mode 100644 src/main/kotlin/me/ztowne13/customcrates/listeners/TabCompleteListener.kt create mode 100644 src/main/kotlin/me/ztowne13/customcrates/particles/ParticleHandler.kt create mode 100644 src/main/kotlin/me/ztowne13/customcrates/players/CratesPlayer.kt create mode 100644 src/main/kotlin/me/ztowne13/customcrates/rewards/Reward.kt create mode 100644 src/main/kotlin/me/ztowne13/customcrates/storage/StorageProvider.kt create mode 100644 src/main/kotlin/me/ztowne13/customcrates/utils/Logging.kt diff --git a/build.gradle b/build.gradle new file mode 100644 index 0000000..7159022 --- /dev/null +++ b/build.gradle @@ -0,0 +1,179 @@ +/* + * This file was generated by the Gradle 'init' task. + */ + +plugins { + id "java" + id "maven-publish" + id "org.jetbrains.kotlin.jvm" version "1.5.30" + id "com.github.johnrengelman.shadow" version "7.0.0" +} + +archivesBaseName = "SpecialisedCrates" +group = "me.ztowne13" +version = "2.14.0-DEV" +sourceCompatibility = JavaVersion.VERSION_1_8 + +ext { + base = "me.ztowne13.customcrates.shaded." +} + +repositories { + mavenCentral() + maven { + url = "https://hub.spigotmc.org/nexus/content/repositories/snapshots/" + content { + includeGroup 'org.bukkit' + includeGroup 'org.spigotmc' + } + } + maven { + url = "https://oss.sonatype.org/content/groups/public/" + } + + maven { + url = "https://oss.sonatype.org/content/repositories/snapshots" + } + + maven { + url = "https://oss.sonatype.org/content/repositories/central" + } + + maven { + url = "https://repo.extendedclip.com/content/repositories/placeholderapi/" + } + + maven { + url = "https://repo.citizensnpcs.co/" + } + + maven { + url = "https://repo.codemc.io/repository/maven-releases/" + } + + maven { + url = "https://jitpack.io" + } + + maven { + url = "https://repo.codemc.org/repository/maven-public/" + content { + includeGroup("org.codemc.worldguardwrapper") + } + } + + maven { + url = "https://repo.aikar.co/content/groups/aikar/" + content { + includeGroup("co.aikar") + } + } + + maven { + url = "https://repo.mattstudios.me/artifactory/public/" + } + + maven { + url = "https://repo.vshnv.tech/" + } + + maven { + url = "https://repo.mattstudios.me/artifactory/public/" + } + +} + +shadowJar { + relocate("org.bstats", "${base}bstats") + relocate("com.zaxxer.hikari", "${base}hikari") + relocate("com.github", "${base}xseries") + relocate("net.kyori", "${base}kyori") + relocate("dev.triumphteam.gui", "${base}gui") + relocate("co.aikar.commands", "${base}acf") + relocate("com.okkero", "${base}scheduler") + relocate("ch.jalu.configme", "${base}configme") + + archiveFileName = "SpecialisedCrates-${project.version}.jar" + +} + +dependencies { + // Command Handling + implementation("co.aikar:acf-paper:0.5.0-SNAPSHOT") + + // Configuration Lib + implementation("ch.jalu:configme:1.2.0") + + // Bstats Data Collecting + implementation("org.bstats:bstats-bukkit:2.2.1") + + // Cross-Version Support + implementation('com.github.cryptomorin:XSeries:8.4.0') + + // Adventure and MiniMessage + implementation('net.kyori:adventure-platform-bukkit:4.0.0') + + // GUIs + implementation("dev.triumphteam:triumph-gui:3.0.3") + + // Database Stuff + implementation('com.zaxxer:HikariCP:5.0.0') + + // Logger + implementation('org.slf4j:slf4j-api:1.7.32') + + // Kotlin collections + implementation('org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.5.30') + + // Coroutines Duh + implementation('org.jetbrains.kotlinx:kotlinx-coroutines-core:1.5.2-native-mt') + implementation files("E:/Documents/Dependancies/skedule-1.2.6.jar") + + // Gson + implementation("com.google.code.gson:gson:2.8.8") + + // Bukkit Version + compileOnly("org.spigotmc:spigot-api:1.17.1-R0.1-SNAPSHOT") + + // Vault Support + compileOnly("com.github.MilkBowl:VaultAPI:1.7.1") + + // Citizens Support + compileOnly("net.citizensnpcs:citizens:2.0.27-SNAPSHOT") + + // Hologram Support + compileOnly("com.sainttx.holograms:holograms:2.13") + compileOnly("com.gmail.filoghost.holographicdisplays:holographicdisplays-api:2.4.4") + + // PlaceholderAPI + compileOnly("me.clip:placeholderapi:2.10.10") +} + +sourceSets { + test.compileClasspath += configurations.compileOnly + test.runtimeClasspath += configurations.compileOnly +} + +compileJava { + options.compilerArgs += ["-parameters"] + options.fork = true + options.forkOptions.executable = 'javac' +} + +compileKotlin { + kotlinOptions.jvmTarget = JavaVersion.VERSION_1_8 + kotlinOptions.javaParameters = true +} +compileTestKotlin { + kotlinOptions.jvmTarget = JavaVersion.VERSION_1_8 +} + +tasks.withType(JavaCompile) { + options.encoding = 'UTF-8' +} + +import org.apache.tools.ant.filters.ReplaceTokens + +processResources { + filter ReplaceTokens, tokens: [version: version] +} \ No newline at end of file diff --git a/pom.xml b/pom.xml index d57279a..d8f68b0 100644 --- a/pom.xml +++ b/pom.xml @@ -11,7 +11,7 @@ SpecializedCrates - me.ztowne13.customcrates.SpecializedCrates + me.ztowne13.me.ztowne13.customcrates.SpecializedCrates Ztowne13 1.8 UTF-8 @@ -93,7 +93,7 @@ com.github.cryptomorin XSeries - 7.5.3 + 8.4.0 compile @@ -139,11 +139,11 @@ org.bstats.bukkit - me.ztowne13.customcrates.interfaces.externalhooks + me.ztowne13.me.ztowne13.customcrates.interfaces.externalhooks com.cryptomorin.xseries - me.ztowne13.customcrates.utils.xseries + me.ztowne13.me.ztowne13.customcrates.utils.xseries diff --git a/src/main/java/me/ztowne13/customcrates/DataHandler.java b/src/main/java/me/ztowne13/customcrates/DataHandler.java deleted file mode 100644 index f55ba76..0000000 --- a/src/main/java/me/ztowne13/customcrates/DataHandler.java +++ /dev/null @@ -1,177 +0,0 @@ -package me.ztowne13.customcrates; - -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.interfaces.files.FileHandler; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.Bukkit; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.FileConfiguration; - -import java.util.*; - -public class DataHandler { - private static final String PLAYER_CMDS_PATH = "queued-player-commands"; - private static final int LOGIN_WAIT = 20; - - private final SpecializedCrates instance; - private final FileHandler dataFile; - private final Map> queuedGiveCommands = new HashMap<>(); - - public DataHandler(SpecializedCrates instance, FileHandler dataFile) { - this.instance = instance; - this.dataFile = dataFile; - } - - public void loadFromFile() { - FileConfiguration fileConfig = dataFile.get(); - - // Queued give commands - ConfigurationSection configSection = fileConfig.getConfigurationSection(PLAYER_CMDS_PATH); - if (configSection != null) { - - for (Object queuedCmd : configSection.getKeys(false)) { - String uuidStr = queuedCmd.toString(); - UUID uuid = UUID.fromString(uuidStr); - - ArrayList cmds = new ArrayList<>(); - - for (String cmd : configSection.getStringList(uuidStr)) { - QueuedGiveCommand queuedGiveCommand = new QueuedGiveCommand(cmd); - if (queuedGiveCommand.isStillExists()) { - cmds.add(queuedGiveCommand); - } - } - - queuedGiveCommands.put(uuid, cmds); - } - } - } - - public void saveToFile() { - FileConfiguration fileConfig = dataFile.get(); - - // Queued give commands - for (Map.Entry> entry : queuedGiveCommands.entrySet()) { - ArrayList giveCmdsStr = new ArrayList<>(); - for (QueuedGiveCommand cmd : entry.getValue()) { - giveCmdsStr.add(cmd.toString()); - } - - fileConfig.set(PLAYER_CMDS_PATH + "." + entry.getKey().toString(), giveCmdsStr.toArray()); - } - - dataFile.save(); - } - - public void addQueuedGiveCommand(QueuedGiveCommand queuedGiveCommand) { - UUID uuid = queuedGiveCommand.getUuid(); - - List thisCmds; - thisCmds = queuedGiveCommands.getOrDefault(uuid, new ArrayList<>()); - thisCmds.add(queuedGiveCommand); - - queuedGiveCommands.put(uuid, thisCmds); - } - - public void playAllQueuedGiveCommands(final UUID uuid) { - Bukkit.getScheduler().runTaskLater(instance, () -> { - if (queuedGiveCommands.containsKey(uuid)) { - for (QueuedGiveCommand cmd : queuedGiveCommands.get(uuid)) - cmd.run(); - - queuedGiveCommands.remove(uuid); - dataFile.get().set(PLAYER_CMDS_PATH + "." + uuid.toString(), null); - } - }, LOGIN_WAIT); - } - - public Map> getQueuedGiveCommands() { - return queuedGiveCommands; - } - - public class QueuedGiveCommand { - UUID uuid; - boolean key; - boolean virtual; - int amount; - Crate crate; - boolean stillExists = true; - - public QueuedGiveCommand(String cmd) { - String[] args = cmd.split(";"); - this.uuid = UUID.fromString(args[0]); - this.key = Boolean.parseBoolean(args[1]); - this.virtual = Boolean.parseBoolean(args[2]); - this.amount = Integer.parseInt(args[3]); - try { - if (Crate.existsNotCaseSensitive(args[4])) { - this.crate = Crate.getCrate(instance, args[4], false); - } else { - stillExists = false; - } - } catch (Exception exc) { - stillExists = false; - } - } - - public QueuedGiveCommand(UUID uuid, boolean key, boolean virtual, int amount, Crate crate) { - this.uuid = uuid; - this.key = key; - this.virtual = virtual; - this.amount = amount; - this.crate = crate; - } - - public UUID getUuid() { - return uuid; - } - - public void run() { - try { - String give = key ? "givekey" : "givecrate"; - String crateName = crate.getName(); - String uuidToStr = uuid.toString(); - String amntStr = amount + ""; - // virtual - - String[] args = new String[virtual ? 5 : 4]; - - args[0] = give; - args[1] = crateName; - args[2] = uuidToStr; - args[3] = amntStr; - if (virtual) - args[4] = "-v"; - - // Crate = 3, Key = 4 - - - if (key) { - ChatUtils.log("[SpecializedCrate] Executing givecrate command for player that was offline."); - instance.getCommandCrate().getSubCommands().get(4).run(instance, instance.getCommandCrate(), args); - } else { - ChatUtils.log("[SpecializedCrate] Executing givekey command for player that was offline."); - instance.getCommandCrate().getSubCommands().get(3).run(instance, instance.getCommandCrate(), args); - } - } catch (Exception exc) { - ChatUtils - .log("&7Failed to run a qued givekey or givecrate command. The crate to give the player probably" + - " no longer exists. The qued command will be removed."); - exc.printStackTrace(); - } - } - - public boolean isStillExists() { - return stillExists; - } - - public Crate getCrate() { - return crate; - } - - @Override - public String toString() { - return uuid + ";" + key + ";" + virtual + ";" + amount + ";" + crate.getName() + ";"; - } - } -} diff --git a/src/main/java/me/ztowne13/customcrates/Messages.java b/src/main/java/me/ztowne13/customcrates/Messages.java deleted file mode 100644 index 78a9c4b..0000000 --- a/src/main/java/me/ztowne13/customcrates/Messages.java +++ /dev/null @@ -1,185 +0,0 @@ -package me.ztowne13.customcrates; - -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.entity.Player; - -import java.util.EnumMap; - -public enum Messages { - NO_PERMISSIONS, - - FAIL_OPEN, - - ALREADY_OPENING_CRATE, - - DENY_CREATIVE_MODE, - - DENY_PLACE_KEY, - - PLACED_CRATE, - - FOUND_LUCKY_CHEST, - - WAIT_ONE_SECOND, - - BROKEN_CRATE, - - FAILED_BREAK_CRATE, - - NO_KEY_USE, - - DENIED_USE_CRATE, - - INVENTORY_TOO_FULL, - - COOLDOWN_START, - - COOLDOWN_END, - - CRATE_ON_COOLDOWN, - - CRATE_DISABLED, - - DENIED_PLACE_LOCATION, - - TOGGLE_LUCKYCRATE, - - NO_PERMISSION_CRATE, - - OPENING_VIRTUALCRATES, - - INSUFFICIENT_VIRTUAL_CRATES, - - CONFIRM_OPEN, - - CONFIRM_OPEN_ALL, - - LOADING_FROM_DATABASE, - - PLACEHOLDER_SECONDS("", "seconds"), - - PLACEHOLDER_MINUTES("", "minutes"), - - PLACEHOLDER_HOURS("", "hours"), - - PLACEHOLDER_DAYS("", "days"), - - ECONOMY_NOT_ENOUGH_MONEY("", "&4&lERROR: &cYou do not have enough money, you need %amount% and are %short% short."), - - COMMAND_REWARDS_USAGE("", "&4&lERROR: &cUsage: /rewards [crate name]"), - - COMMAND_REWARDS_OPENING("", "&6&lINFO: &eOpening reward preview for %crate% crate."), - - COMMAND_REWARDS_INVALID_CRATE("", "&4&lERROR: &c%crate% is not a valid crate."), - - CANT_CRAFT_KEYS("", "&4&lERROR: &cYou are not allowed to craft keys."), - - RECEIVED_KEY("", "&2&lSUCCESS! &aYou just received %amount% %crate% key(s)!"), - - RECEIVED_VIRTUAL_KEY("", "&2&lSUCCESS! &aYou just received %amount% virtual %crate% key(s)!"), - - GIVEN_FALLBACK_REWARD("", - "&6&lINFO: &eYou already have the %reward% &ereward, so you have been given the %fallbackreward% &ereward instead."), - - BLACKLISTED_PLUGIN( - "&cIMPORTANT: THIS COPY OF THE SPECIALIZED CRATES HAS BEEN BLACKLISTED BECAUSE THE USER WHO PURCHASED IT" + - " IS NOT THE ONLY PERSON USING IT, OR THIS PERSON HAS REFUNDED IT. IF YOU BELIEVE THIS IS AN ERROR, PLEASE RE-DOWNLOAD THE PLUGIN (NO" + - " NEED TO REGENERATE CONFIG) AND TRY AGAIN. IF IT'S STILL NOT WORKING, PLEASE CONTACT ZTOWNE13."), - - CRATES_CLAIM_DENY_DEPOSIT_KEYS("", "&4&lHey! &cYou can not deposit keys into /crates claim."), - - BYPASS_BREAK_RESTRICTIONS("&9&lNOTICE! &bThis crate typically isn't placeable, you have bypassed this restriction."), - - SUCCESS_DELETE("&2&lSUCCESS! &aDeleted the %crate% crate from this location."), - - CRATE_DISABLED_ADMIN( - "&6&lNOTE! &eIf you did not disable this crate manually, something was not configured properly. Please type" + - " /scrates errors (crate name) to see possible issues."), - - NEEDS_UPDATE("&9&lNOTICE: &bSpecialized Crates has an update available: v%version%"), - - HEADER("&3&l>> &7&m--------------- &6&lCrates &7&m---------------&3&l <<"), - - FOOTER("&3&l>> &7&m----------------------------------------------&3&l <<"); - - private static final EnumMap CACHED_MESSAGES = new EnumMap<>(Messages.class); - private final String msg; - private final String defaultMsg; - - Messages() { - this(""); - } - - Messages(String msg) { - this(msg, ""); - } - - Messages(String msg, String defaultMsg) { - this.msg = msg; - this.defaultMsg = defaultMsg; - } - - public static void clearCache() { - CACHED_MESSAGES.clear(); - } - - public String getFromConf(SpecializedCrates instance) { - if (CACHED_MESSAGES.containsKey(this)) - return CACHED_MESSAGES.get(this); - - try { - String val = instance.getMessageFile().get().getString(nameFormatted()); - - if (val == null) - throw new Exception(); - - CACHED_MESSAGES.put(this, ChatUtils.toChatColor(val)); - return ChatUtils.toChatColor(val); - } catch (Exception exc) { - if (defaultMsg.equalsIgnoreCase("")) { - CACHED_MESSAGES.put(this, ChatUtils.toChatColor( - "&eThis value isn't set, please tell the server operator to configure the " + name() + " value.")); - } else { - CACHED_MESSAGES.put(this, ChatUtils.toChatColor(defaultMsg)); - instance.getMessageFile().get().set(nameFormatted(), defaultMsg); - instance.getMessageFile().save(); - } - return CACHED_MESSAGES.get(this); - } - } - - public String nameFormatted() { - return name().toLowerCase().replace("_", "-"); - } - - public void msgSpecified(SpecializedCrates instance, Player player) { - msgSpecified(instance, player, new String[]{}, new String[]{}); - } - - public void msgSpecified(SpecializedCrates instance, Player player, String[] replaceValue, String[] setValue) { - String correctMSG = getProperMsg(instance); - if (correctMSG.equalsIgnoreCase("none") - || correctMSG.equalsIgnoreCase("") - || correctMSG.equalsIgnoreCase("&f")) { - return; - } - - for (int i = 0; i < replaceValue.length; i++) { - correctMSG = correctMSG.replace(replaceValue[i], setValue[i]); - } - - player.sendMessage(correctMSG); - } - - public void writeValue(SpecializedCrates instance, String value) { - instance.getMessageFile().get().set(name().toLowerCase().replace("_", "-").toLowerCase(), value); - } - - public String getProperMsg(SpecializedCrates instance) { - return ChatUtils.toChatColor(getMsg().equalsIgnoreCase("") ? getFromConf(instance) : getMsg()); - } - - public String getMsg() { - return msg; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/Settings.java b/src/main/java/me/ztowne13/customcrates/Settings.java deleted file mode 100644 index 478fd76..0000000 --- a/src/main/java/me/ztowne13/customcrates/Settings.java +++ /dev/null @@ -1,163 +0,0 @@ -package me.ztowne13.customcrates; - -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.PlacedCrate; -import me.ztowne13.customcrates.interfaces.files.FileHandler; -import me.ztowne13.customcrates.utils.*; -import org.bukkit.Location; - -import java.io.File; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class Settings { - private final SpecializedCrates instance; - - private final HashMap infoToLog = new HashMap<>(); - private final HashMap configValues = new HashMap<>(); - - private final ArrayList failedPlacedCrate = new ArrayList<>(); - - public Settings(SpecializedCrates instance) { - this.instance = instance; - } - - - public void load() { - loadSettings(); - ChatUtils.log(""); - loadCrates(false); - loadCrates(true); - loadPlacedCrates(); - loadInfo(); - ChatUtils.log(""); - ChatUtils.log(""); - } - - public void loadCrates(boolean multiCrate) { - instance.getDebugUtils().log("loadCrates - CALL", getClass()); - File folder = new File(instance.getDataFolder().getPath() + "/Crates"); - File[] listOfFiles = folder.listFiles(); - - instance.getDebugUtils().log("loadCrates - Beginning loop", getClass()); - for (int i = 0; i < listOfFiles.length; i++) { - instance.getDebugUtils().log("loadCrates - Looping " + i, getClass()); - if (listOfFiles[i].isFile()) { - instance.getDebugUtils().log("loadCrates - Is file " + i, getClass()); - File f = listOfFiles[i]; - - if (f.getName().contains(";") || f.getName().contains(",")) { - ChatUtils.log(new String[]{"FAILED TO LOAD THE " + f.getName() + " CRATE.", - " CAUSE: Crate's Name contains ',' or ';' characters."}); - continue; - } - - instance.getDebugUtils().log("loadCrates - Attempting load", getClass()); - if (f.getName().endsWith(".crate") && !multiCrate) { - instance.getDebugUtils().log("loadCrates - Loading " + f.getName() + " is .crate", getClass()); - String crateName = f.getName().replace(".crate", ""); - Crate.getCrate(instance, crateName); - instance.getDebugUtils().log("loadCrates - Done", getClass()); - } else if (f.getName().endsWith(".multicrate") && multiCrate) { - instance.getDebugUtils().log("loadCrates - Loading " + f.getName() + " is .multicrate", getClass()); - String crateName = f.getName().replace(".multicrate", ""); - Crate.getCrate(instance, crateName, true); - instance.getDebugUtils().log("loadCrates - Done", getClass()); - } - } - } - } - - public void loadPlacedCrates() { - for (String s : instance.getActiveCratesFile().get().getKeys(false)) - if (!loadCrateFromFile(s)) - failedPlacedCrate.add(s); - } - - public boolean loadCrateFromFile(String s) { - FileHandler activeCrates = instance.getActiveCratesFile(); - String crateName = activeCrates.get().getString(s + ".crate"); - Location l = LocationUtils.stringToLoc(s); - - if (Crate.exists(crateName)) { - Crate crates = Crate.getCrate(instance, crateName); - - PlacedCrate cm = PlacedCrate.get(instance, l); - if (cm == null) { - ChatUtils.log("location: " + s); - return false; - } - - if (crates.isEnabled()) { - cm.setup(crates, false); - } else { - cm.setCratesEnabled(false); - } - - if (activeCrates.get().contains(s + ".placedTime")) { - cm.setPlacedTime(activeCrates.get().getLong(s + ".placedTime")); - } else { - cm.setPlacedTime(0L); - } - } else { - ChatUtils.log(new String[]{"ERROR: " + crateName + " DOES NOT EXIST TO BE USED AT LOCATION: " + s}); - } - - return true; - } - - public void loadSettings() { - for (SettingsValue sv : SettingsValue.values()) { - getConfigValues().put(sv.getPath(), instance.getConfig().get(sv.getPath())); - } - } - - public void loadInfo() { - Utils.addToInfoLog(instance, "Server version", VersionUtils.getServerVersion()); - Utils.addToInfoLog(instance, "Citizens Installed", - (NPCUtils.isCitizensInstalled() ? "" : "&c") + Utils.isPLInstalled("Citizens") + ""); - - int enabled = 0; - int disabled = 0; - for (Crate crates : Crate.getLoadedCrates().values()) { - if (crates.isEnabled()) { - enabled++; - } else { - disabled++; - } - } - - Utils.addToInfoLog(instance, "Crates loaded", enabled + " enabled &4/ &c" + disabled + " disabled"); - Utils.addToInfoLog(instance, "Crates placed", PlacedCrate.getPlacedCrates().keySet().size() + ""); - - Utils.addToInfoLog(instance, "Plugin version", instance.getDescription().getVersion()); - - } - - public void writeSettingsValues() { - FileHandler fu = new FileHandler(instance, "config.yml", true, true); - for (String s : getConfigValues().keySet()) { - fu.get().set(s, getConfigValues().get(s)); - } - - fu.save(); - } - - public Boolean getConfigValAsBoolean(String path) { - return Boolean.valueOf(getConfigValues().get(path).toString()); - } - - public Map getConfigValues() { - return configValues; - } - - public Map getInfoToLog() { - return infoToLog; - } - - public List getFailedPlacedCrate() { - return failedPlacedCrate; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/SettingsValue.java b/src/main/java/me/ztowne13/customcrates/SettingsValue.java deleted file mode 100644 index 2957037..0000000 --- a/src/main/java/me/ztowne13/customcrates/SettingsValue.java +++ /dev/null @@ -1,585 +0,0 @@ -package me.ztowne13.customcrates; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.EnumMap; -import java.util.List; - -public enum SettingsValue { - STORE_DATA("store-data", Category.GENERAL_SETTINGS, String.class, - new String[]{ - "FLATFILE", - "MYSQL", - "PLAYERFILES" - }, - new String[]{ - "Stores all player data in a single file", - "Stores all player data in a MySQL database. The connection info is defined in the MySQL.yml file", - "Stores all player data in individual files for each player" - } - , false, "FLATFILE", "Data Storage Type", - new String[]{ - "Set how would you like to store", - "player data. Options: FLATFILE,", - "MYSQL, or PLAYERFILES." - }), - - LOG_SUCCESSES("log-successes", Category.GENERAL_SETTINGS, String.class, - new String[]{ - "EVERYTHING", - "FAILURES", - "NOTHING" - }, - new String[]{ - "Logs both successfully loaded configuration data and the data that had issues", - "Logs only the issues with the configuration files", - "Logs nothing to console except the loaded crate names" - } - , false, "FAILURES", "Console Log Type", - new String[]{ - "Set how much would you like to", - "be logged to console.", - "Use EVERYTHING, FAILURES, or", - "NOTHING." - }), - - PUSHBACK("push-back", Category.CRATE_SETTINGS, Boolean.class, false, true, "Pushback On Fail", - new String[]{ - "Players will be pushed back if", - "they fail to open a crate" - }), - - AUTO_CLOSE("auto-close", Category.DEPRECATED, Boolean.class, false, true, "Auto Close Animations", - new String[]{ - "Crate animations should automatically", - "close when done. This is a default value", - "and will be overriden by the specific crate's", - "auto-close value.", - "THE RECOMMENDED SOLUTION", - "IS NOW THE 'auto-close' VALUE IN EACH .CRATE", - "FILE" - }), - - REQUIRED_SLOTS("required-slots", Category.CRATE_SETTINGS, Integer.class, false, 1, "Required Slots To Open Crates", - new String[]{ - "Set amount of slots required", - "to open a crate?" - }), - - OPEN_CREATIVE("open-creative", Category.CRATE_SETTINGS, Boolean.class, false, true, "Open Crates In Creative", - new String[]{ - "Players can open crates in", - "creative mode." - }), - - PLACE_CREATIVE("place-creative", Category.CRATE_SETTINGS, Boolean.class, false, true, "Place Crates In Creative", - new String[]{ - "Players can place crates in", - "creative mode." - }), - - LUCKYCHEST_CREATIVE("luckychest-creative", Category.LUCKY_CRATE_SETTINGS, Boolean.class, false, false, - "Find Luckychests In Creative", - new String[]{ - "Players can find lucky chests", - "in creative mode." - }), - - LUCKYCHEST_ALLOW_PLACED_BLOCKS("luckychest-allow-placed-blocks", Category.LUCKY_CRATE_SETTINGS, Boolean.class, false, - false, - "Luckychests For Placed Blocks", - new String[]{ - "Lucky chests (mine crates) WILL", - "spawn even when the block broken", - "was placed by a player.", - "NOTE: Placed block data IS NOT SAVED", - "on reload/restart as to not take too", - "many server resources. It is simply", - "meant to be a deterrent for placing", - "and breaking blocks over and over to", - "find lucky chests (mine crates)." - }), - - REQUIRE_KEY_LORE("require-key-lore", Category.KEY_SETTINGS, Boolean.class, false, true, "Require Key Lore To Open", - new String[]{ - "A key's lore is required to", - "match the key." - }), - - CA_FADE_IN("fade-in-time", Category.CRATE_SETTINGS, Integer.class, false, 0, "Title Fade In Time", - new String[]{ - "Set how long would you like titles", - "or subtitles to take to fade in.", - "(In seconds)" - }), - - CA_STAY("stay-time", Category.CRATE_SETTINGS, Integer.class, false, 4, "Title Stay Time", - new String[]{ - "Set how long would you like titles", - "or subtitles to stay on the screen.", - "(In seconds)" - }), - - CA_FADE_OUT("fade-out-time", Category.CRATE_SETTINGS, Integer.class, false, 1, "Title Fade Out Time", - new String[]{ - "Set how long would you like titles", - "or subtitles to take to fade out.", - "In seconds" - }), - - LUCKYCHEST_DESPAWN("luckychest-despawn-after", Category.CRATE_SETTINGS, Integer.class, false, -1, - "Luckychest Despawn Time", - new String[]{ - "Set how many MINUTES luckycrates will", - " take to despawn.", - "Set to -1 to never despawn." - }), - - REWARD_DISPLAY_ENABLED("enabled", Category.REWARD_DISPLAY_SETTINGS, Boolean.class, false, true, "Use Reward Displayer", - new String[]{ - "Crate will display their rewards", - "when left clicked." - }), - - REWARD_DISPLAY_NAME("inv-reward-display-name", Category.DEPRECATED, String.class, true, "&4%crate% &cRewards", - "Default Preview Menu Name", - new String[]{ - "Set the reward display inventory's.", - "This is a default value and will be", - "overriden by the crate's own reward", - "displayer name value.", - "THE RECOMMENDED", - "SOLUTION NOW IS TO EDIT THE", - "'reward-display.name' VALUE IN EACH .CRATE", - "FILE" - }), - - REWARD_ITEM_NAME("inv-reward-item-name", Category.GENERAL_SETTINGS, String.class, true, "&c%displayname%", - "Default Reward Name Format", - new String[]{ - "Set the reward display item's name.", - "This is a default value and will be", - "overriden by the crate's own reward", - "displayer name value." - }), - - REWARD_ITEM_LORE("inv-reward-item-lore", Category.GENERAL_SETTINGS, Collection.class, false, - new String[]{"&7-", "&eChance: &6%writtenchance%%"}, - "Default Reward Lore", - new String[]{ - "Edit the reward display item's lore.", - "This is a default value and will be", - "overriden by the crate's own reward", - "displayer name value." - }), - - EXPLODE_DYNAMIC("explosions-destroy-dynamic-crates", Category.CRATE_SETTINGS, Boolean.class, false, true, - "Allow Explosions", - new String[]{ - "Explosions will destroy dynamic crates." - }), - - HOLOGRAM_OFFSET("hologram-offset", Category.CRATE_SETTINGS, Double.class, false, 0, "Global Hologram Offset", - new String[]{ - "Set the global hologram location offset.", - "This offset will be applied IN ADDITION", - "to the hologram offset specified in each", - "crate's file." - }), - - PLACE_EFFECT("place-effect", Category.CRATE_SETTINGS, Boolean.class, false, true, "Placing Effect", - new String[]{ - "A cool effect will be displayed when", - "a crate is placed." - }), - - PRIORITIZE_PHYSICAL_KEY("prioritize-physical-key", Category.KEY_SETTINGS, Boolean.class, false, true, - "Phyiscal/Virtual Key Priority", - new String[]{ - "Uses a physical key first if the", - "player has a physical & virtaul key." - }), - - VIRTUAL_CRATE_LORE("virtual-crate-lore", Category.DEPRECATED, String.class, true, - "&cCrates: &f(&7%crates%&f)", "Virtual Crate Lore", - new String[]{ - "This is no longer the recommended way", - "to put the quantity of keys for a crate", - "in an item's lore. Instead, change the", - "crate's 'crate item' that would normally", - "be placed down to have a lore that uses", - "the %crates% placeholder anywhere inside", - "of it.", - "THE RECOMMENDED SOLUTION IS NOW", - "ADDING %crate% TO THE CRATE ITEM'S", - "LORE." - }), - - VIRTUAL_KEY_LORE("virtual-key-lore", Category.DEPRECATED, String.class, true, "&cKeys: &f(&7%keys%&f)", - "Virtual Key Lore", - new String[]{ - "This is no longer the recommended way", - "to put the quantity of keys for a crate", - "in an item's lore. Instead, change the", - "crate's 'crate item' that would normally", - "be placed down to have a lore that uses", - "the %crates% placeholder anywhere inside", - "of it.", - "THE RECOMMENDED SOLUTION IS NOW", - "ADDING %key% TO THE CRATE ITEM'S", - "LORE." - }), - - CRATES_COMMAND_MULTICRATE("crates-command-multicrate", Category.VIRTUAL_CRATE_SETTINGS, String.class, - new String[]{}, - new String[]{}, - false, "AllCrates", - "'/Crates' Crate Name", - new String[]{ - "The name of the crate that", - "is opened when non-OP players", - "type /crates." - }), - - CRATES_COMMAND_NAME("crates-command-name", Category.VIRTUAL_CRATE_SETTINGS, String.class, true, "&b&lVirtual &7&lCrates", - "'/Crates' Menu Name", - new String[]{ - "The name to be displayed on the", - "/crates virtual crates menu." - }), - - MC_REWARD_DISPLAY_LEFTCLICK("mc-reward-display-leftclick", Category.REWARD_DISPLAY_SETTINGS, Boolean.class, false, true, - "Multicrates Reward Preview", - new String[]{ - "MultiCrates will display rewards", - "on left click instead of", - "right click." - }), - -// NOTIFY_UPDATES("notify-updates", Boolean.class, false, true, -// new String[]{ -// "The plugin will notify administrators", -// "when there is an update", -// "for the plugin." -// }), - - DEBUG("debug", Category.GENERAL_SETTINGS, Boolean.class, false, false, "Debug Mode", - new String[]{ - "The plugin will log developer", - "information to console. ONLY ENABLE", - "IF ZTOWNE13 SAYS SO - it's information", - "will be useless without him." - }), - - VIRTUAL_CRATE_KEYCOUNT("virtual-crate-keycount", Category.DEPRECATED, Boolean.class, false, false, - "Show 'virtual-key-lore' Value", - new String[]{ - "Multicrates will show the", - "'virtual-key-lore' on crates", - "in a multicrate.", - "THE RECOMMENDED SOLUTION IS NOW", - "ADDING %key% TO THE CRATE ITEM'S", - "LORE." - }), - - VIRTUAL_CRATE_CRATECOUNT("virtual-crate-cratecount", Category.DEPRECATED, Boolean.class, false, false, - "Show 'virtual-crate-lore' Value", - new String[]{ - "Multicrates will show the", - "'virtual-crate-lore' on crates", - "in a multicrate.", - "THE RECOMMENDED SOLUTION IS NOW", - "ADDING %crates% TO THE CRATE ITEM'S", - "LORE." - }), - - VIRTUAL_KEY_INSTEAD_OF_DROP("virtual-key-instead-of-drop", Category.CRATE_SETTINGS, Boolean.class, false, false, - "Virtual Key Instead of Drop", - new String[]{ - "A player will be given a", - "virtual key instead of the key", - "dropping on the floor when", - "their inventory is full." - }), - - SHIFT_CLICK_OPEN_ALL("shift-click-open-all", Category.CRATE_SETTINGS, Boolean.class, false, true, "Shift-Click Open All", - new String[]{ - "Shift clicking on a crate will", - "use EVERY key a player is holding", - "in their hand.", - "NOTE: Opening every key only gives", - "one reward per key - regardless of", - "animation type." - }), - - SHIFT_CLICK_CONFIRM("shift-click-confirm", Category.CRATE_SETTINGS, Boolean.class, false, true, "Shift-Click Confirm", - new String[]{ - "The user has to shift-click again", - "to confirm opening with every", - "physical & virtual key." - }), - - CONFIRM_OPEN("confirm-open", Category.CRATE_SETTINGS, Boolean.class, false, false, "Confirm Open", - new String[]{ - "The user will have to click the", - "crate again to confirm opening." - }), - - CONFIRM_TIMEOUT("confirm-timeout", Category.CRATE_SETTINGS, Integer.class, false, 3, "Confirm Timeout Length", - new String[]{ - "The time, in seconds, the player", - "has to confirm opening a crate if", - "shift-click-confirm or", - "confirm-open is enabled." - }), - - REQUIRE_VIRTUAL_CRATE_AND_KEY("require-virtual-crate-and-key", Category.VIRTUAL_CRATE_SETTINGS, Boolean.class, false, - false, "Require Virtual Crate", - new String[]{ - "In MultiCrates (inventory crate), ", - "both a virtual key AND a virtual crate", - "is required to open the crate." - }), - - KEEP_CRATE_BLOCK_CONSISTENT("keep-crate-block-consistent", Category.CRATE_SETTINGS, Boolean.class, false, true, - "Keep Crate Block Consistent", - new String[]{ - "Every time the server is restarted/", - "reloaded, all of the crates will be", - "replaced to ensure no other blocks", - "or plugin commands have overridden", - "them." - }), - - KEY_ALLOW_LEFT_CLICK_INTERACTION("key-allow-left-click-interaction", Category.KEY_SETTINGS, Boolean.class, false, false, - "Allow Key Interaction", - new String[]{ - "When a player left clicks with a key,", - "the event won't be cancelled. The only", - "reason this would be set to true is if", - "keys need to interact with other plugins", - "like a sell-shop plugin where, to set up", - "the shop, a sign needs to be left-clicked", - "with a key." - }), - - PARTICLE_VIEW_DISTANCE("particle-view-distance", Category.CRATE_SETTINGS, Integer.class, false, 25, - "Particle View Distance", - new String[]{ - "The distance, in blocks, away that players", - "can be and still see crate particles" - }), - - LEFT_CLICK_KEY_PREVIEW("left-click-key-preview", Category.REWARD_DISPLAY_SETTINGS, Boolean.class, false, false, - "Left Click Key Preview", - new String[]{ - "When a player left-clicks with a key (anywhere)", - "it opens that specific crate's reward", - "preview menu." - }), - - USE_CRATE_NAME_FOR_DISPLAY("use-crate-name-for-display", Category.GENERAL_SETTINGS, Boolean.class, false, false, - "Use Crate Item Name", - new String[]{ - "Anywhere there is a %crate% placeholder", - "the crate item's display name will be used", - "instead of just the crate's name." - }), - - CRATES_CLAIM_INVENTORY_NAME("crates-claim-inventory-name", Category.VIRTUAL_CRATE_SETTINGS, String.class, true, - "&7&l> &6&lCrates Claim", - "/Crates Claim Inv. Name", - new String[]{ - "The name of the inventory when a player", - "types /crates claim." - }), - - CRATES_CLAIM_ALLOW_DEPOSIT("crates-claim-allow-deposit", Category.VIRTUAL_CRATE_SETTINGS, Boolean.class, false, true, - "Allow deposit in /crate claim", - new String[]{ - "Player's can deposit keys into the /crates", - "claim inventory in addition to withdraw keys" - }), - - DATA_SAVE_METHOD("flatfile-data-save-method", Category.GENERAL_SETTINGS, String.class, - new String[]{ - "INTERVAL", - "DISABLE" - }, - new String[]{ - "If new player data needs to be saved, it is saved every X seconds, specified by 'data-save-interval' in addition to when the plugin is disabled." + - " This is the least efficient as it periodically saves the file but safest as server crashes will be less likely to lead to data loss.", - "Player data is only saved when the server is disabled (server restart, reload, etc.). This will lead to data loss on crashes but will be the best performance" - }, - true, "INTERVAL", "FLATFILE Save Method", - new String[]{ - "If the datatype is FLATFILE, either INTERVAL where player data is saved periodically and on plugin disable to ensure no data loss but has worse performance, " + - "or DISABLE where player data is saved only on plugin disable (server restart, reload, etc.) which will result in data loss on crashes " + - "but has much better server performance." - }), - - DATA_SAVE_INTERVAL("flatfile-save-interval", Category.GENERAL_SETTINGS, Integer.class, true, 300, "FLATFILE Save Interval", - new String[]{ - "If the data type is FLATFILE and 'data-save-method' is set to INTERVAL, this is the interval IN SECONDS that the data will be saved if there" + - " is new data to be saved. If there is no new data to be saved, it won't waste time re-saving." - }), - - PLAYER_HISTORY_LIMIT("player-history-limit", Category.GENERAL_SETTINGS, Integer.class, true, 500, "Player History Limit", - new String[]{ - "The maximum number of most recent history data points to store for a player. The lower the number, the less amount of history is stored " + - "(which is bad if you want to track who opened what) but allows for greater plugin performance as loading player data is significantly " + - "faster, putting less of a load on server resources." - }); - - private static final EnumMap valuesCache = new EnumMap<>(SettingsValue.class); - private final String easyName; - private final String path; - private final String[] descriptor; - private final Object obj; - private final Object defaultVal; - private final boolean withColor; - private final Category category; - private final String[] listValues; - private final String[] listValueDescriptors; - - SettingsValue(String path, Category category, Object obj, boolean withColor, Object defaultVal, String easyName, - String[] descriptor) { - this(path, category, obj, null, null, withColor, defaultVal, easyName, descriptor); - } - - SettingsValue(String path, Category category, Object obj, String[] listValues, String[] listValueDescriptors, boolean withColor, Object defaultVal, String easyName, - String[] descriptor) { - this.category = category; - this.easyName = easyName; - this.path = path; - this.descriptor = descriptor; - this.obj = obj; - this.defaultVal = defaultVal; - this.withColor = withColor; - this.listValueDescriptors = listValueDescriptors; - this.listValues = listValues; - } - - public static void clearCache() { - valuesCache.clear(); - } - - public static SettingsValue getByPath(String s) { - for (SettingsValue sv : values()) { - if (sv.getPath().equalsIgnoreCase(s)) { - return sv; - } - } - - return null; - } - - public Object getValue(SpecializedCrates cc) { - if (valuesCache.containsKey(this)) { - return valuesCache.get(this); - } else { - Object val = cc.getSettings().getConfigValues().get(path); - if (val == null) - val = defaultVal; - - valuesCache.put(this, val); - return getValue(cc); - } - } - - public void setValue(SpecializedCrates sc, Object val) { - sc.getSettings().getConfigValues().put(getPath(), val); - valuesCache.put(this, val); - } - - public String getPath() { - return path; - } - - public String[] getDescriptor() { - return descriptor; - } - - public Object getObj() { - return obj; - } - - public boolean isWithColor() { - return withColor; - } - - public String getEasyName() { - return easyName; - } - - public String[] getListValues() { - return listValues; - } - - public String[] getListValueDescriptors() { - return listValueDescriptors; - } - - public enum Category { - GENERAL_SETTINGS("General", "General Settings", - "This includes general settings for the entire plugin.", - "To edit a crate's specific settings, do /scrates edit (crate)"), - - KEY_SETTINGS("Key", "Key Settings", - "General settings for how keys are handled and interact with crates, including shift-click to open all, etc.", - "To edit key settings for a specific crate, type /scrates edit (crate), click 'The Essentials' and configurations are there."), - - CRATE_SETTINGS("Crate", "Crate Settings", - "General settings for all crates, including creative settings, crate block consistencies, etc.", - "To edit crate settings for a specific crate, type /scrates edit (crate)"), - - LUCKY_CRATE_SETTINGS("Lucky Crate", "Lucky Crate Settings", - "General settings for all lucky crates including despawn time, etc.", - "To make a chest a lucky chest, type /scratest edit (crate), click 'The Essentials' then change the obtain-type to LUCKYCHEST."), - - VIRTUAL_CRATE_SETTINGS("Virtual Crate", "Virtual Crate Settings", - "General settings for anything virtual-crate related, including the /crates menu, and /crates claim settings.", - "If you want a virtual key for a crate, type /scrates givekey (crate) (player) (amount) -v"), - - REWARD_DISPLAY_SETTINGS("Reward Preview", "Reward Preview Settings", - "General settings for the reward displays, including whether or not they're enabled.", - "To edit a crate's reward preview menu, do /scrates edit (crate), click 'Rewards', then click 'Reward Preview Editor'"), - - DEPRECATED("Deprecated", "Deprecated (No Longer Recommended)", - "These settings still work but are no longer the recommended way to perform these functions", - "Most of these functionalities have been moved to the /scrates edit (crate) menu and are editable per-crate instead of globally."); - - private final String title; - private final String shortTitle; - private final String[] description; - - Category(String shortTitle, String title, String... description) { - this.shortTitle = shortTitle; - this.title = title; - this.description = description; - } - - public String getShortTitle() { - return shortTitle; - } - - public String getTitle() { - return title; - } - - public String[] getDescription() { - return description; - } - - public List getAssociatedValues() { - ArrayList values = new ArrayList<>(); - for (SettingsValue value : SettingsValue.values()) { - if (value.category == this) { - values.add(value); - } - } - - return values; - } - } -} diff --git a/src/main/java/me/ztowne13/customcrates/SpecializedCrates.java b/src/main/java/me/ztowne13/customcrates/SpecializedCrates.java deleted file mode 100644 index e76c2ed..0000000 --- a/src/main/java/me/ztowne13/customcrates/SpecializedCrates.java +++ /dev/null @@ -1,523 +0,0 @@ -package me.ztowne13.customcrates; - -import me.ztowne13.customcrates.commands.CommandCrate; -import me.ztowne13.customcrates.commands.CommandKey; -import me.ztowne13.customcrates.commands.CommandRewards; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.CrateState; -import me.ztowne13.customcrates.crates.PlacedCrate; -import me.ztowne13.customcrates.crates.options.CHologram; -import me.ztowne13.customcrates.crates.options.CReward; -import me.ztowne13.customcrates.crates.options.particles.ParticleData; -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import me.ztowne13.customcrates.crates.types.animations.block.OpenChestAnimation; -import me.ztowne13.customcrates.interfaces.externalhooks.EconomyHandler; -import me.ztowne13.customcrates.interfaces.externalhooks.PlaceHolderAPIHandler; -import me.ztowne13.customcrates.interfaces.externalhooks.holograms.HologramManager; -import me.ztowne13.customcrates.interfaces.externalhooks.holograms.cmi.ZripsHologramManager; -import me.ztowne13.customcrates.interfaces.externalhooks.holograms.holograms.SainttXHologramManager; -import me.ztowne13.customcrates.interfaces.externalhooks.holograms.holographicdisplays.HDHologramManager; -import me.ztowne13.customcrates.interfaces.externalhooks.holograms.nohologram.NoHologramManager; -import me.ztowne13.customcrates.interfaces.files.FileHandler; -import me.ztowne13.customcrates.interfaces.sql.SQLQueryThread; -import me.ztowne13.customcrates.listeners.*; -import me.ztowne13.customcrates.players.PlayerDataManager; -import me.ztowne13.customcrates.players.PlayerManager; -import me.ztowne13.customcrates.players.data.FlatFileDataHandler; -import me.ztowne13.customcrates.players.data.IndividualFileDataHandler; -import me.ztowne13.customcrates.players.data.events.CrateCooldownEvent; -import me.ztowne13.customcrates.utils.*; -import org.bstats.bukkit.MetricsLite; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.event.Listener; -import org.bukkit.plugin.java.JavaPlugin; -import org.bukkit.scheduler.BukkitTask; - -import java.util.ArrayList; -import java.util.List; - -public class SpecializedCrates extends JavaPlugin { - - private final ArrayList alreadyUpdated = new ArrayList<>(); - private FileHandler messageFile; - private FileHandler rewardsFile; - private FileHandler activeCratesFile; - private FileHandler crateConfigFile; - private FileHandler dataFile; - private FileHandler sqlFile; - private Settings settings; - private HologramManager hologramManager; - private DataHandler dataHandler; - private EconomyHandler economyHandler; - private CommandCrate commandCrate; - private BukkitTask bukkitTask; - private MetricsLite metricsLite = null; - private PlaceHolderAPIHandler placeHolderAPIHandler = null; - private DebugUtils debugUtils = null; - private int tick = 0; - private int totalTicks = 0; - private int saveFilesTick = 0; - private boolean allowTick = true; - private boolean hasAttemptedReload = false; - private boolean particlesEnabled = true; - private long total = 0; - private long count = 0; - - @Override - public void onEnable() { - onEnable(true); - } - - public void onEnable(boolean register) { - if (metricsLite == null) { - metricsLite = new MetricsLite(this, 5642); - } - if (debugUtils == null) { - debugUtils = new DebugUtils(this); - } - - if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null && !isUsingPlaceholderAPI()) { - placeHolderAPIHandler = new PlaceHolderAPIHandler(this); - placeHolderAPIHandler.register(); - } - - reloadConfig(); - saveDefaultConfig(); - loadFiles(); - - this.dataHandler = new DataHandler(this, dataFile); - this.economyHandler = new EconomyHandler(this); - - setSettings(new Settings(this)); - - if (Utils.isPLInstalled("HolographicDisplays")) { - Utils.addToInfoLog(this, "Hologram Plugin", "HolographicDisplays"); - this.hologramManager = new HDHologramManager(this); - } else if (Utils.isPLInstalled("Holograms")) { - Utils.addToInfoLog(this, "Hologram Plugin", "Holograms"); - this.hologramManager = new SainttXHologramManager(this); - } else if (Utils.isPLInstalled("CMI")) { - Utils.addToInfoLog(this, "Hologram Plugin", "CMI"); - this.hologramManager = new ZripsHologramManager(this); - } else { - Utils.addToInfoLog(this, "Hologram Plugin", "None"); - this.hologramManager = new NoHologramManager(this); - } - - getSettings().load(); - - registerCommands(); - if (register) { - registerAll(); - } - - for (Player p : Bukkit.getOnlinePlayers()) { - PlayerManager.get(this, p); - } - - NPCUtils.load(register); - NPCUtils.checkUncheckMobs(this, false, 20); - - loadRewards(); - - run(); - - dataHandler.loadFromFile(); - allowTick = true; - - getSettings().getInfoToLog().put("Metrics", metricsLite == null ? "&cdisabled" : "&aenabled"); - - // Check to see if the plugin needs a reload to find the hologram plugin - if (!hasAttemptedReload) { - Bukkit.getScheduler().runTaskLater(this, () -> { - if (getSettings().getInfoToLog().containsKey("Hologram Plugin") && - getSettings().getInfoToLog().get("Hologram Plugin").equalsIgnoreCase("None")) { - hasAttemptedReload = true; - ChatUtils - .log("&e[SpecializedCrates] No hologram plugin was found. In the off-chance that this is because the hologram plugin" + - " opted to ignore the softdepend and loaded after SpecializedCrates, the plugin is reloading once to " + - "try again."); - reload(); - } - }, 1); - } - - if (Bukkit.getServer().getSpawnRadius() != 0) { - ChatUtils.log("&4WARNING: &cThe value 'spawn-protection' is set to " + Bukkit.getServer().getSpawnRadius() + - " in the server.properties file. This WILL cause issues with SpecializedCrates - any crates near spawn will " + - "only be openable for OP players. Please go to your server.properties file in the main directory of your server" + - " and change spawn-protection: 0."); - } - } - - @Override - public void onDisable() { - allowTick = false; - - try { - finishUpPlayers(); - } catch (Exception exc) { - // IGNORED - } - - dataHandler.saveToFile(); - - CHologram.deleteAll(); - NPCUtils.checkUncheckMobs(true); - OpenChestAnimation.removeAllItems(); - Messages.clearCache(); - SQLQueryThread.stopRun(); - SQLQueryThread.clearQuery(); - - saveFilesTick(false); - } - - public void saveEverything() { - messageFile.save(); - rewardsFile.save(); - crateConfigFile.save(); - settings.writeSettingsValues(); - for (Crate crate : Crate.getLoadedCrates().values()) { - try { - crate.getSettings().saveAll(); - } catch (Exception exc) { - exc.printStackTrace(); - } - } - } - - public void reload() { - ChatUtils.log("Disabling..."); - - onDisable(); - - setMessageFile(null); - setRewardsFile(null); - setActiveCratesFile(null); - setCrateConfigFile(null); - setSettings(null); - setDataFile(null); - setSqlFile(null); - - getCommand("scrates").setExecutor(null); - getCommand("scrates").setTabCompleter(null); - getCommand("keys").setExecutor(null); - - try { - getCommand("rewards").setExecutor(null); - getCommand("rewards").setTabCompleter(null); - } catch (Exception exc) { - // IGNORED - } - - setTick(0); - - FileHandler.clearLoaded(); - PlacedCrate.clearLoaded(); - PlayerManager.clearLoaded(); - Crate.clearLoaded(); - ReflectionUtilities.clearLoaded(); - Utils.setCachedParticleDistance(-1); - stopRun(); - - setBukkitTask(null); - - CReward.getAllRewards().clear(); - SettingsValue.clearCache(); - - ChatUtils.log("Enabling SpecializedCrates"); - onEnable(false); - } - - public void registerCommands() { - TabCompleteListener tabCompleteListener = new TabCompleteListener(this); - - commandCrate = new CommandCrate(this); - getCommand("scrates").setExecutor(commandCrate); - getCommand("scrates").setTabCompleter(tabCompleteListener); - - getCommand("keys").setExecutor(new CommandKey(this)); - - getCommand("rewards").setExecutor(new CommandRewards(this)); - getCommand("rewards").setTabCompleter(tabCompleteListener); - } - - public void registerAll() { - registerListener(new InteractListener(this)); - registerListener(new BlockBreakListener(this)); - registerListener(new BlockPlaceListener(this)); - registerListener(new BlockRemoveListener(this)); - registerListener(new InventoryActionListener(this)); - registerListener(new PlayerConnectionListener(this)); - registerListener(new CommandPreprocessListener(this)); - registerListener(new ChatListener(this)); - registerListener(new PluginEnableListener(this)); - registerListener(new DamageListener(this)); - - if (NPCUtils.isCitizensInstalled()) { - registerListener(new NPCEventListener(this)); - } - } - - public void loadRewards() { - boolean newValues = false; - - for (String rName : getRewardsFile().get().getKeys(false)) { - if (!CReward.getAllRewards().containsKey(rName)) { - if (!newValues) { - newValues = true; - } - Reward reward = new Reward(this, rName); - reward.loadFromConfig(); - reward.loadChance(); - CReward.getAllRewards().put(rName, reward); - } - } - } - - public void registerListener(Listener listener) { - Bukkit.getPluginManager().registerEvents(listener, this); - } - - public void loadFiles() { - setRewardsFile(new FileHandler(this, "Rewards.yml", true, false)); - setActiveCratesFile(new FileHandler(this, "ActiveCrates.db", false, false)); - setCrateConfigFile(new FileHandler(this, "CrateConfig.yml", true, false)); - setMessageFile(new FileHandler(this, "Messages.yml", true, false)); - setDataFile(new FileHandler(this, "PluginData.db", false, false)); - setSqlFile(new FileHandler(this, "SQL.yml", true, false)); - - getMessageFile().saveDefaults(); - getRewardsFile().saveDefaults(); - getActiveCratesFile().saveDefaults(); - getCrateConfigFile().saveDefaults(); - getDataFile().saveDefaults(); - getSqlFile().saveDefaults(); - } - - public void firstLoadFiles() { - String[] firstFiles = - new String[]{"BasicCrate", "BeginnerCrate", "MiddleCrate", "MasterCrate", "MineChestExample", "ExpertCrate"}; - for (String newFile : firstFiles) { - new FileHandler(this, newFile + ".crate", "Crates/", true, true, false).saveDefaults(); - } - - new FileHandler(this, "AllCrates.multicrate", "Crates/", true, true, false).saveDefaults(); - } - - public void tick() { - if (!allowTick) { - return; - } - - for (PlacedCrate placedCrate : new ArrayList<>(PlacedCrate.getPlacedCrates().values())) { - if (placedCrate.isCratesEnabled()) { - try { - placedCrate.tick(CrateState.PLAY); - } catch (Exception exc) { - exc.printStackTrace(); - } - } - } - - getAlreadyUpdated().clear(); - - setTotalTicks(getTotalTicks() + 1); - setTick(getTick() + 1); - - if (getTick() == 10) { - setTick(0); - saveFilesTick(true); - - for (Player p : Bukkit.getOnlinePlayers()) { - PlayerDataManager pdm = PlayerManager.get(this, p).getPlayerDataManager(); - ArrayList list = new ArrayList<>(pdm.getCrateCooldownEvents()); - - for (CrateCooldownEvent cce : list) { - cce.tickSecond(pdm); - } - } - } - } - - public void saveFilesTick(boolean isInterval) { - saveFilesTick++; - - String dataSaveType = SettingsValue.DATA_SAVE_METHOD.getValue(this).toString(); - int saveInterVal = (int) SettingsValue.DATA_SAVE_INTERVAL.getValue(this); - if (isInterval && (dataSaveType.equalsIgnoreCase("DISABLE") || saveFilesTick % saveInterVal != 0)) { - return; - } - - if (FlatFileDataHandler.isToSave()) { - getDebugUtils().log("saveFilesTick() - Saving playerdata.db flat file"); - FlatFileDataHandler.getFileHandler().save(); - FlatFileDataHandler.resetToSave(); - } - - for (IndividualFileDataHandler file : IndividualFileDataHandler.getToSave()) { - file.getFileHandler().save(); - } - IndividualFileDataHandler.getToSave().clear(); - } - - public void run() { - setBukkitTask(Bukkit.getScheduler().runTaskTimer(this, () -> { - if (DebugUtils.OUTPUT_AVERAGE_TICK) { - long curTimeMillis = System.currentTimeMillis(); - tick(); - long dif = (System.currentTimeMillis() - curTimeMillis); - total += dif; - count++; - long solved = total / count; - - ChatUtils.log("Average: " + solved); - } else { - tick(); - } - }, 0, 2)); - } - - public void finishUpPlayers() { - for (Player p : Bukkit.getOnlinePlayers()) { - PlayerManager pm = PlayerManager.get(this, p); - - if (pm.isInCrateAnimation()) { - pm.getCurrentAnimation().setFastTrack(true, true); - } - - if (pm.isInCratesClaimMenu()) { - p.closeInventory(); - } - } - } - - public void stopRun() { - bukkitTask.cancel(); - } - - public Settings getSettings() { - return settings; - } - - public void setSettings(Settings settings) { - this.settings = settings; - } - - public DebugUtils getDebugUtils() { - return debugUtils; - } - - public void setBukkitTask(BukkitTask bukkitTask) { - this.bukkitTask = bukkitTask; - } - - public int getTick() { - return tick; - } - - public void setTick(int tick) { - this.tick = tick; - } - - public FileHandler getMessageFile() { - return messageFile; - } - - public void setMessageFile(FileHandler messageFile) { - this.messageFile = messageFile; - } - - public FileHandler getRewardsFile() { - return rewardsFile; - } - - public void setRewardsFile(FileHandler rewardsFile) { - this.rewardsFile = rewardsFile; - } - - public FileHandler getActiveCratesFile() { - return activeCratesFile; - } - - public void setActiveCratesFile(FileHandler activeCratesFile) { - this.activeCratesFile = activeCratesFile; - } - - public FileHandler getCrateConfigFile() { - return crateConfigFile; - } - - public void setCrateConfigFile(FileHandler crateConfigFile) { - this.crateConfigFile = crateConfigFile; - } - - public List getAlreadyUpdated() { - return alreadyUpdated; - } - - public HologramManager getHologramManager() { - return this.hologramManager; - } - - public boolean isAllowTick() { - return allowTick; - } - - public FileHandler getDataFile() { - return dataFile; - } - - public void setDataFile(FileHandler dataFile) { - this.dataFile = dataFile; - } - - public DataHandler getDataHandler() { - return dataHandler; - } - - public CommandCrate getCommandCrate() { - return commandCrate; - } - - public FileHandler getSqlFile() { - return sqlFile; - } - - public void setSqlFile(FileHandler sqlFile) { - this.sqlFile = sqlFile; - } - - public EconomyHandler getEconomyHandler() { - return economyHandler; - } - - public boolean isUsingPlaceholderAPI() { - return placeHolderAPIHandler != null; - } - - public boolean isParticlesEnabled() { - return particlesEnabled; - } - - public void setParticlesEnabled(boolean particlesEnabled) { - this.particlesEnabled = particlesEnabled; - } - - public int getTotalTicks() { - return totalTicks; - } - - public void setTotalTicks(int totalTicks) { - this.totalTicks = totalTicks; - } - - public int getSaveFilesTick() { - return saveFilesTick; - } - - public void setSaveFilesTick(int saveFilesTick) { - this.saveFilesTick = saveFilesTick; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/api/CrateOpenEvent.java b/src/main/java/me/ztowne13/customcrates/api/CrateOpenEvent.java deleted file mode 100644 index fbc45ee..0000000 --- a/src/main/java/me/ztowne13/customcrates/api/CrateOpenEvent.java +++ /dev/null @@ -1,50 +0,0 @@ -package me.ztowne13.customcrates.api; - -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import org.bukkit.entity.Player; -import org.bukkit.event.Event; -import org.bukkit.event.HandlerList; - -import java.util.List; - -public class CrateOpenEvent extends Event { - private static final HandlerList HANDLERS_LIST = new HandlerList(); - - private final Crate crate; - private final List rewards; - private final Player player; - private final int openedCratesCount; - - public CrateOpenEvent(Player player, List rewards, Crate crate, int openedCratesCount) { - this.player = player; - this.rewards = rewards; - this.crate = crate; - this.openedCratesCount = openedCratesCount; - } - - public static HandlerList getHandlerList() { - return HANDLERS_LIST; - } - - @Override - public HandlerList getHandlers() { - return HANDLERS_LIST; - } - - public Crate getCrate() { - return crate; - } - - public List getRewards() { - return rewards; - } - - public Player getPlayer() { - return player; - } - - public int getOpenedCratesCount() { - return openedCratesCount; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/commands/CommandCrate.java b/src/main/java/me/ztowne13/customcrates/commands/CommandCrate.java deleted file mode 100644 index 5aede85..0000000 --- a/src/main/java/me/ztowne13/customcrates/commands/CommandCrate.java +++ /dev/null @@ -1,158 +0,0 @@ -package me.ztowne13.customcrates.commands; - -import me.ztowne13.customcrates.Messages; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.commands.sub.*; -import me.ztowne13.customcrates.players.PlayerDataManager; -import me.ztowne13.customcrates.players.PlayerManager; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * All commands for the plugin - */ -public class CommandCrate extends Commands implements CommandExecutor { - private final SpecializedCrates instance; - private final VirtualCrates vcSubCommand; - private final Claim claimSubCommand; - private final ArrayList subCommands; - - public CommandCrate(SpecializedCrates instance) { - super("scrates"); - this.instance = instance; - - vcSubCommand = new VirtualCrates(); - claimSubCommand = new Claim(); - - subCommands = new ArrayList<>(Arrays.asList( - new Config(), - new DelAllCrateType(), - new DeleteCrate(), - new GiveCrate(), - new GiveKey(), - new Help(), - new Info(), - new LastConfigMenu(), - new ListCrates(), - new ListHistory(), - new Reload(), - new Errors(), - new Edit(), - new Debug(), - new ForceOpen(), - new ToggleParticles(), - new SpawnCrate(), - claimSubCommand, - vcSubCommand - )); - } - - @Override - public boolean onCommand(@NotNull CommandSender sender, Command cmd, String cmdLabel, String[] args) { - setCmdSender(sender); - - if (args.length > 0 && canExecute(true, true, "customcrates.admin", "specializedcrates.admin")) { - for (SubCommand subCommand : subCommands) { - if (subCommand.isCommand(args[0])) { - if (subCommand.checkProperUsage(sender, args)) { - return subCommand.run(instance, this, args); - } - return false; - } - } - } - - if (args.length > 0 && args[0].equalsIgnoreCase("luckychest")) { - if (canExecute(false, true, "customcrates.luckychestcommand", "specializedcrates.luckychestcommand")) { - PlayerDataManager pdm = PlayerManager.get(instance, (Player) sender).getPlayerDataManager(); - pdm.setActivatedLuckyChests(!pdm.isActivatedLuckyChests()); - Messages.TOGGLE_LUCKYCRATE.msgSpecified(instance, (Player) sender, new String[]{"%state%"}, - new String[]{pdm.isActivatedLuckyChests() + ""}); - } else { - msg(Messages.NO_PERMISSIONS.getFromConf(instance) - .replace("%permission%", "specializedcrates.luckychestcommand")); - } - return true; - } else if (args.length > 0 && args[0].equalsIgnoreCase("claim")) { - if (canExecute(false, true, "customcrates.claim", "specializedcrates.claim")) { - claimSubCommand.run(instance, this, args); - } else { - msg(Messages.NO_PERMISSIONS.getFromConf(instance) - .replace("%permission%", "specializedcrates.claim")); - } - return true; - } else if (!canExecute(false, true, "customcrates.admin", "specializedcrates.admin")) { - if (vcSubCommand.run(instance, this, args)) { - return true; - } else if (args.length == 0) { - msg(Messages.NO_PERMISSIONS.getFromConf(instance) - .replace("%permission%", "specializedcrates.crates (for users) or specializedcrates.admin (for admins)")); - return true; - } - - msg(Messages.NO_PERMISSIONS.getFromConf(instance) - .replace("%permission%", "specializedcrates.admin")); - } else { - msgPage(1); - } - - - return false; - } - - @Override - public void msgPage(int page) { - msg(""); - msg(""); - msg(""); - msg("&6&lSpecialized &7&lCrates"); - msg(""); - msg("&6&l> &econfig"); - msg(" &7Configure the plugin in game."); - msg("&6&l> &egivekey [crate] [player] [amnt] {-v, for virtual keys}"); - msg(" &7Get the get for the specified crate."); - msg("&6&l> &egivecrate [crate] [player] [amnt] {-v, for virtual crates}"); - msg(" &7Get the item for a specific crate."); - msg("&6&l> &edeletecrate"); - msg(" &7Delete a crate from the world."); - msg("&6&l> &ereload"); - msg(" &7Reload all data from the config.yml."); - msg("&6&l> &elistHistory [player] [amnt of entries]"); - msg(" &7List the crate history for an online player."); - msg("&6&l> &elistCrates"); - msg(" &7List all the valid crates."); - msg("&6&l> &edelAllCrateType [crate]"); - msg(" &7Delete all existing crates of the type."); - msg("&6&l> &einfo"); - msg(" &7Get all info for the plugin."); - msg("&6&l> &eluckychest"); - msg(" &7Toggle whether or not you want luckychests to appear."); - msg("&6&l> &eerrors"); - msg(" &7See all crate errors in game!"); - msg("&6&l> &eedit [crate]"); - msg(" &7Open up the in game config directly for a crate."); - msg("&6&l> &e!"); - msg(" &7Open the last in-game config menu you were in."); - msg("&6&l> &evirtualcrates"); - msg(" &7The menu displayed when a non-admins types /crates"); - msg("&6&l> &eforceopen [crate] {[player], all}"); - msg(" &7Force a player to open a crate."); - msg("&6&l> &etoggleparticles"); - msg(" &7Temporarily disable all particle effects."); - msg("&6&l> &espawncrate [crate] [world] [x] [y] [z]"); - msg(" &7Spawn a crate at a given location."); - msg(""); - - } - - public List getSubCommands() { - return subCommands; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/commands/CommandKey.java b/src/main/java/me/ztowne13/customcrates/commands/CommandKey.java deleted file mode 100644 index 2b991b2..0000000 --- a/src/main/java/me/ztowne13/customcrates/commands/CommandKey.java +++ /dev/null @@ -1,58 +0,0 @@ -package me.ztowne13.customcrates.commands; - -import me.ztowne13.customcrates.Messages; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.players.PlayerDataManager; -import me.ztowne13.customcrates.players.PlayerManager; -import me.ztowne13.customcrates.players.data.VirtualCrateData; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.command.ConsoleCommandSender; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; - -/** - * Created by ztowne13 on 7/30/16. - */ -public class CommandKey extends Commands implements CommandExecutor { - private final SpecializedCrates instance; - - public CommandKey(SpecializedCrates instance) { - super("keys"); - this.instance = instance; - } - - @Override - public boolean onCommand(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String s, String[] strings) { - setCmdSender(commandSender); - - if (!canExecute(false, true, "customcrates.keys", "specializedcrates.keys")) { - if (commandSender instanceof ConsoleCommandSender) { - msg("This command cannot be run from console. To give virtual crates / keys simply add a -v to the end of the /scrates givekey command."); - return false; - } - msg(Messages.NO_PERMISSIONS.getFromConf(instance).replace("%permission%", "specializedcrates.keys")); - return false; - } - - Player p = (Player) commandSender; - PlayerDataManager pdm = PlayerManager.get(instance, p).getPlayerDataManager(); - msg("&7&l> &b&lVirtual &f&lKeys / Crates"); - for (VirtualCrateData vcd : pdm.getVirtualCrateData().values()) { - Crate crate = vcd.getCrate(); - if (vcd.getKeys() > 0 || vcd.getCrates() > 0) { - msg("&b" + vcd.getCrate().getName() + " &f( " + crate.getSettings().getCrateInventoryName() + "&f ) "); - msg(" &8- Crates: &7" + vcd.getCrates()); - msg(" &8- Keys: &7" + vcd.getKeys()); - } - } - return true; - } - - @Override - public void msgPage(int page) { - // EMPTY - } -} diff --git a/src/main/java/me/ztowne13/customcrates/commands/CommandRewards.java b/src/main/java/me/ztowne13/customcrates/commands/CommandRewards.java deleted file mode 100644 index 27adc78..0000000 --- a/src/main/java/me/ztowne13/customcrates/commands/CommandRewards.java +++ /dev/null @@ -1,58 +0,0 @@ -package me.ztowne13.customcrates.commands; - -import me.ztowne13.customcrates.Messages; -import me.ztowne13.customcrates.SettingsValue; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.utils.CrateUtils; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.command.ConsoleCommandSender; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; - -public class CommandRewards extends Commands implements CommandExecutor { - private final SpecializedCrates instance; - - public CommandRewards(SpecializedCrates instance) { - super("rewards"); - this.instance = instance; - } - - @Override - public boolean onCommand(@NotNull CommandSender commandSender, @NotNull Command command, @NotNull String s, String[] args) { - setCmdSender(commandSender); - - if (!canExecute(false, true, "customcrates.rewards", "specializedcrates.rewards")) { - if (getCmdSender() instanceof ConsoleCommandSender) - msg("This command can not be run from console."); - else - Messages.NO_PERMISSIONS.msgSpecified(instance, (Player) commandSender, new String[]{"%permission%"}, - new String[]{"specializedcrates.rewards"}); - return false; - } - - Player player = (Player) commandSender; - if (args.length == 0) - Messages.COMMAND_REWARDS_USAGE.msgSpecified(instance, player); - else { - String crateName = args[0]; - if (Crate.exists(crateName)) { - Crate crate = Crate.getCrate(instance, crateName); - if (CrateUtils.isCrateUsable(crate) && SettingsValue.REWARD_DISPLAY_ENABLED.getValue(instance).equals(Boolean.TRUE) && !crate.isMultiCrate()) { - crate.getSettings().getDisplayer().openFor(player); - Messages.COMMAND_REWARDS_OPENING.msgSpecified(instance, player, new String[]{"%crate%"}, new String[]{crateName}); - return true; - } - } - Messages.COMMAND_REWARDS_INVALID_CRATE.msgSpecified(instance, player, new String[]{"%crate%"}, new String[]{crateName}); - } - return false; - } - - @Override - public void msgPage(int page) { - // EMPTY - } -} diff --git a/src/main/java/me/ztowne13/customcrates/commands/Commands.java b/src/main/java/me/ztowne13/customcrates/commands/Commands.java deleted file mode 100644 index 5551043..0000000 --- a/src/main/java/me/ztowne13/customcrates/commands/Commands.java +++ /dev/null @@ -1,49 +0,0 @@ -package me.ztowne13.customcrates.commands; - -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -public abstract class Commands { - protected final String commandName; - private CommandSender cmdSender; - - public Commands(String commandName) { - this.commandName = commandName; - } - - public abstract void msgPage(int page); - - public boolean canExecute(boolean console, boolean reqperm, String... perms) { - for (String perm : perms) { - if (cmdSender instanceof Player ? !reqperm || cmdSender.hasPermission(perm) : console) { - return true; - } - } - return false; - } - - public void msg(String s) { - if (getCmdSender() instanceof Player) { - ChatUtils.msg((Player) getCmdSender(), s); - } else { - ChatUtils.log(s); - } - } - - public void msgError(String s) { - msg("&4&lERROR! &c" + s); - } - - public void msgSuccess(String s) { - msg("&2&lSUCCESS! &a" + s); - } - - public CommandSender getCmdSender() { - return cmdSender; - } - - public void setCmdSender(CommandSender cmdSender) { - this.cmdSender = cmdSender; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/commands/sub/Claim.java b/src/main/java/me/ztowne13/customcrates/commands/sub/Claim.java deleted file mode 100644 index d613ef0..0000000 --- a/src/main/java/me/ztowne13/customcrates/commands/sub/Claim.java +++ /dev/null @@ -1,59 +0,0 @@ -package me.ztowne13.customcrates.commands.sub; - -import me.ztowne13.customcrates.SettingsValue; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.commands.Commands; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.players.PlayerDataManager; -import me.ztowne13.customcrates.players.PlayerManager; -import me.ztowne13.customcrates.players.data.VirtualCrateData; -import org.bukkit.entity.Player; - -public class Claim extends SubCommand { - public Claim() { - super("claim", 1, ""); - } - - @Override - public boolean run(SpecializedCrates cc, Commands cmds, String[] args) { - if (!(cmds.getCmdSender() instanceof Player)) { - cmds.msgError("This command is only usable by a player."); - return false; - } - - Player player = (Player) cmds.getCmdSender(); - PlayerManager playerManager = PlayerManager.get(cc, player); - PlayerDataManager dataManager = playerManager.getPlayerDataManager(); - - int stacks = 0; - for (VirtualCrateData vcd : dataManager.getVirtualCrateData().values()) { - int stackSize = vcd.getCrate().getSettings().getKeyItemHandler().getItem(1).getMaxStackSize(); - stacks += (vcd.getKeys() / stackSize) + (vcd.getKeys() % stackSize == 0 ? 0 : 1); - if (stacks >= 54) { - break; - } - } - - int rowsNeeded = (stacks / 9) + (stacks % 9 == 0 ? 0 : 1) + 1; - - String invName = SettingsValue.CRATES_CLAIM_INVENTORY_NAME.getValue(cc).toString(); - InventoryBuilder builder = new InventoryBuilder(player, rowsNeeded > 6 ? 54 : (rowsNeeded * 9), invName); - - for (VirtualCrateData vcd : dataManager.getVirtualCrateData().values()) { - int stackSize = vcd.getCrate().getSettings().getKeyItemHandler().getItem(1).getMaxStackSize(); - int keys = vcd.getKeys(); - while (keys > 0 && builder.getInv().firstEmpty() != -1) { - int toAdd = Math.min(keys, stackSize); - builder.getInv().addItem(vcd.getCrate().getSettings().getKeyItemHandler().getItem(toAdd)); - keys -= toAdd; - - dataManager.setVirtualCrateKeys(vcd.getCrate(), dataManager.getVCCrateData(vcd.getCrate()).getKeys() - toAdd); - } - } - - playerManager.setInCratesClaimMenu(true); - builder.open(); - - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/commands/sub/Config.java b/src/main/java/me/ztowne13/customcrates/commands/sub/Config.java deleted file mode 100644 index 2144d3d..0000000 --- a/src/main/java/me/ztowne13/customcrates/commands/sub/Config.java +++ /dev/null @@ -1,29 +0,0 @@ -package me.ztowne13.customcrates.commands.sub; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.commands.Commands; -import me.ztowne13.customcrates.interfaces.igc.IGCMenuMain; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -/** - * Created by ztowne13 on 6/23/16. - */ -public class Config extends SubCommand { - public Config() { - super("config", 1, "", new String[]{"conf", "c", "configure", "igc", "configuration", "yml"}); - } - - @Override - public boolean run(SpecializedCrates cc, Commands cmds, String[] args) { - CommandSender sender = cmds.getCmdSender(); - if (cmds.canExecute(false, false, "")) { - new IGCMenuMain(cc, (Player) sender, null).open(); - cmds.msgSuccess("Opened in game configuration."); - return true; - } else { - cmds.msgError("This is an in-game command only."); - return false; - } - } -} diff --git a/src/main/java/me/ztowne13/customcrates/commands/sub/Debug.java b/src/main/java/me/ztowne13/customcrates/commands/sub/Debug.java deleted file mode 100644 index 3704d5d..0000000 --- a/src/main/java/me/ztowne13/customcrates/commands/sub/Debug.java +++ /dev/null @@ -1,111 +0,0 @@ -package me.ztowne13.customcrates.commands.sub; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.commands.Commands; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.interfaces.items.NBTTagBuilder; -import me.ztowne13.customcrates.interfaces.items.attributes.BukkitGlowEffect; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.VersionUtils; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; - -public class Debug extends SubCommand { - - public Debug() { - super("debug", 1, ""); - } - - @SuppressWarnings("deprecated") - @Override - public boolean run(SpecializedCrates cc, Commands cmds, String[] args) { - if (!(cmds.getCmdSender() instanceof Player)) { - return false; - } - - Player player = (Player) cmds.getCmdSender(); - - boolean debug = true; // MODIFY HERE - if (debug) { - if (args.length == 1) { - ChatUtils.msgInfo(player, "Commands: iteminfo[tostring,-{-nolore,-ignoreexcluded,-stripcolor}], applytag[{tag id}], glow[-, asbuilder]"); - return true; - } - - if (args[1].equalsIgnoreCase("iteminfo")) { - boolean noLoreArg = false; - boolean ignoreExcludedArg = false; - boolean stripColorArg = false; - - for (String arg : args) { - if (arg.equalsIgnoreCase("-nolore")) { - noLoreArg = true; - } else if (arg.equalsIgnoreCase("-ignoreexcluded")) { - ignoreExcludedArg = true; - } else if (arg.equalsIgnoreCase("-stripcolor")) { - stripColorArg = true; - } - } - - ItemStack stack = player.getItemInHand(); - ItemMeta im = stack.getItemMeta(); - - if (args.length == 3 && args[2].equalsIgnoreCase("tostring")) { - cmds.msg("toString(): " + stack.toString()); - cmds.msg("im.toString(): " + im.toString()); - } - - cmds.msg("Type: " + stack.getType().name()); - - if (!noLoreArg) { - cmds.msg("Lore:"); - for (String s : im.getLore()) { - if (stripColorArg) { - cmds.getCmdSender().sendMessage("- " + ChatUtils.fromChatColor(s)); - } else { - cmds.msg("- " + s); - } - } - } - - - cmds.msg("Enchants: "); - if (VersionUtils.Version.v1_13.isServerVersionOrLater()) { - for (Enchantment ench : im.getEnchants().keySet()) - cmds.msg("- " + ench.getKey().getKey() + " lvl " + im.getEnchants().get(ench)); - } - - cmds.msg("Data: " + stack.getDurability()); - cmds.msg("NBT Tags:"); - for (String s : NBTTagBuilder.getFrom(stack, ignoreExcludedArg)) - cmds.msg("- " + s); - - } else if (args[1].equalsIgnoreCase("applytag")) { - String tag = args[2]; - String id = args[3]; - String combined = tag + " " + id; - - player.setItemInHand(NBTTagBuilder.applyTo(player.getItemInHand(), combined)); - cmds.msgSuccess("Added tag '" + combined + "'"); - } else if (args[1].equalsIgnoreCase("glow")) { - if (args.length > 2) { - if (args[2].equalsIgnoreCase("asbuilder")) { - ItemBuilder builder = new ItemBuilder(player.getItemInHand()); - builder.setGlowing(true); - ItemBuilder dupedBuilder = new ItemBuilder(builder); - player.setItemInHand(dupedBuilder.getStack()); - cmds.msg("Added glow effect via itembuilder"); - } - } else { - new BukkitGlowEffect(player.getItemInHand()).apply(); - cmds.msg("Added glow effect"); - } - } - } else { - ChatUtils.msgError(player, "This command is disabled in non-development builds."); - } - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/commands/sub/DelAllCrateType.java b/src/main/java/me/ztowne13/customcrates/commands/sub/DelAllCrateType.java deleted file mode 100644 index b58b4c0..0000000 --- a/src/main/java/me/ztowne13/customcrates/commands/sub/DelAllCrateType.java +++ /dev/null @@ -1,26 +0,0 @@ -package me.ztowne13.customcrates.commands.sub; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.commands.Commands; -import me.ztowne13.customcrates.crates.Crate; - -/** - * Created by ztowne13 on 6/23/16. - */ -public class DelAllCrateType extends SubCommand { - public DelAllCrateType() { - super("delallcratetype", 2, "Usage: /SCrates DelAllCrateType (Crate)", new String[]{"dellallcrate", "deleteallcrates", "deleteallcratetype"}); - } - - @Override - public boolean run(SpecializedCrates cc, Commands cmds, String[] args) { - if (Crate.exists(args[1])) { - Crate.getCrate(cc, args[1]).deleteAllPlaced(); - cmds.msgSuccess("Deleted all " + args[1] + " crates!"); - return true; - } else { - cmds.msgError("Crate " + args[1] + " doesn't exist."); - return false; - } - } -} diff --git a/src/main/java/me/ztowne13/customcrates/commands/sub/DeleteCrate.java b/src/main/java/me/ztowne13/customcrates/commands/sub/DeleteCrate.java deleted file mode 100644 index 3859f59..0000000 --- a/src/main/java/me/ztowne13/customcrates/commands/sub/DeleteCrate.java +++ /dev/null @@ -1,34 +0,0 @@ -package me.ztowne13.customcrates.commands.sub; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.commands.Commands; -import me.ztowne13.customcrates.players.PlayerManager; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.entity.Player; - -/** - * Created by ztowne13 on 6/23/16. - */ -public class DeleteCrate extends SubCommand { - public DeleteCrate() { - super("deletecrate", 1, "", new String[]{"delcrate"}); - } - - @Override - public boolean run(SpecializedCrates cc, Commands cmds, String[] args) { - if (cmds.canExecute(false, false, "")) { - Player p = (Player) cmds.getCmdSender(); - PlayerManager pm = PlayerManager.get(cc, p); - - if (pm.isDeleteCrate()) { - pm.setDeleteCrate(false); - ChatUtils.msgSuccess(p, "You will no longer delete a crate!"); - } else { - pm.setDeleteCrate(true); - ChatUtils.msg(p, "&ePlease LEFT-CLICK the crate you'd like to delete."); - ChatUtils.msg(p, " &o&6Use /SCrates deletecrate to disable this mode."); - } - } - return true; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/commands/sub/Edit.java b/src/main/java/me/ztowne13/customcrates/commands/sub/Edit.java deleted file mode 100644 index 7373dad..0000000 --- a/src/main/java/me/ztowne13/customcrates/commands/sub/Edit.java +++ /dev/null @@ -1,55 +0,0 @@ -package me.ztowne13.customcrates.commands.sub; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.commands.Commands; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.PlacedCrate; -import me.ztowne13.customcrates.interfaces.igc.crates.IGCCratesMain; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.entity.Player; - -import java.util.TreeSet; - -/** - * Created by ztowne13 on 7/4/16. - */ -public class Edit extends SubCommand { - public Edit() { - super("edit", 1, "", new String[]{"e"}); - } - - @Override - public boolean run(SpecializedCrates cc, Commands cmds, String[] args) { - if (cmds.getCmdSender() instanceof Player) { - Player p = (Player) cmds.getCmdSender(); - - if (args.length == 1) { - TreeSet set = new TreeSet<>(); - set.add(Material.AIR); - if (p.getTargetBlock(set, 20) != null) { - Block b = p.getTargetBlock(set, 20); - if (PlacedCrate.crateExistsAt(b.getLocation())) { - PlacedCrate pc = PlacedCrate.get(cc, b.getLocation()); - new IGCCratesMain(cc, p, null, pc.getCrate()).open(); - ChatUtils.msgSuccess(p, "Opening config menu for crate: " + pc.getCrate().getName()); - return true; - } - } - ChatUtils.msgError(p, "You are not looking at a crate to open!"); - } else { - if (Crate.existsNotCaseSensitive(args[1])) { - Crate crate = Crate.getCrate(cc, args[1]); - new IGCCratesMain(cc, p, null, crate).open(); - ChatUtils.msgSuccess(p, "Opening config menu for crate: " + crate.getName()); - return true; - } - ChatUtils.msgError(p, args[1] + " is not a valid crate name."); - } - } else { - cmds.msg("This command can only be run from in-game."); - } - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/commands/sub/Errors.java b/src/main/java/me/ztowne13/customcrates/commands/sub/Errors.java deleted file mode 100644 index faca32d..0000000 --- a/src/main/java/me/ztowne13/customcrates/commands/sub/Errors.java +++ /dev/null @@ -1,34 +0,0 @@ -package me.ztowne13.customcrates.commands.sub; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.commands.Commands; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.utils.ChatUtils; - -/** - * Created by ztowne13 on 6/30/16. - */ -public class Errors extends SubCommand { - public Errors() { - super("errors", 1, ""); - } - - @Override - public boolean run(SpecializedCrates cc, Commands cmds, String[] args) { - if (args.length == 1) { - for (Crate crate : Crate.getLoadedCrates().values()) { - cmds.getCmdSender().sendMessage(ChatUtils.toChatColor("&4&l----------")); - cmds.getCmdSender().sendMessage(ChatUtils.toChatColor("&c" + crate.getName())); - crate.getSettings().getStatusLogger().logAll(cmds.getCmdSender(), false); - } - } else if (args.length > 1) { - if (Crate.existsNotCaseSensitive(args[1])) { - cmds.msg("&4&lErrors:"); - Crate.getCrate(cc, args[1]).getSettings().getStatusLogger().logAll(cmds.getCmdSender(), true); - } else { - cmds.msgError(args[1] + " is not a valid crate name to identify loading failures for."); - } - } - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/commands/sub/ForceOpen.java b/src/main/java/me/ztowne13/customcrates/commands/sub/ForceOpen.java deleted file mode 100644 index 0597971..0000000 --- a/src/main/java/me/ztowne13/customcrates/commands/sub/ForceOpen.java +++ /dev/null @@ -1,62 +0,0 @@ -package me.ztowne13.customcrates.commands.sub; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.commands.Commands; -import me.ztowne13.customcrates.crates.Crate; -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import org.bukkit.entity.Player; - -import java.util.UUID; - -public class ForceOpen extends SubCommand { - public ForceOpen() { - super("forceopen", 3, "Usage: /scrates forceopen [crate] {[player], all}", new String[]{"force", "fopen"}); - } - - @SuppressWarnings("deprecated") - @Override - public boolean run(SpecializedCrates cc, Commands cmds, String[] args) { - if (args.length == 3) { - String crateName = args[1]; - String playerName = args[2]; - - if (Crate.exists(crateName)) { - Crate crate = Crate.getCrate(cc, args[1]); - - OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(playerName); - if (!offlinePlayer.isOnline()) { - try { - UUID uuid = UUID.fromString(playerName); - offlinePlayer = Bukkit.getOfflinePlayer(uuid); - } catch (Exception exc) { - // IGNORED - } - } - - if (offlinePlayer.isOnline()) { - Player player = offlinePlayer.getPlayer(); - run(crate, player); - return true; - } - - if (playerName.equalsIgnoreCase("all")) { - for (Player player : Bukkit.getOnlinePlayers()) - run(crate, player); - - return true; - } - - cmds.msgError(playerName + " is not a valid online player's name or UUID."); - return false; - } - cmds.msgError(crateName + " is not a valid crate name."); - } - - return false; - } - - public void run(Crate crate, Player player) { - crate.getSettings().getCrateAnimation().startAnimation(player, player.getLocation(), !crate.isMultiCrate(), true); - } -} diff --git a/src/main/java/me/ztowne13/customcrates/commands/sub/GiveCrate.java b/src/main/java/me/ztowne13/customcrates/commands/sub/GiveCrate.java deleted file mode 100644 index caa5220..0000000 --- a/src/main/java/me/ztowne13/customcrates/commands/sub/GiveCrate.java +++ /dev/null @@ -1,116 +0,0 @@ -package me.ztowne13.customcrates.commands.sub; - -import me.ztowne13.customcrates.DataHandler; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.commands.Commands; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.players.PlayerDataManager; -import me.ztowne13.customcrates.players.PlayerManager; -import me.ztowne13.customcrates.utils.Utils; -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - -import java.util.UUID; - -/** - * Created by ztowne13 on 6/23/16. - */ -public class GiveCrate extends SubCommand { - public GiveCrate() { - super("givecrate", 2, "Usage: /SCrates GiveCrate (Crate) (Player/ALL) [Amount] [-v : for a virtual crate]", - new String[]{"gcrate", "gc", "crategive", "crate"}); - } - - @SuppressWarnings("deprecated") - @Override - public boolean run(SpecializedCrates cc, Commands cmds, String[] args) { - if (Crate.exists(args[1])) { - int amount = 1; - if (args.length >= 4) { - if (Utils.isInt(args[3])) { - amount = Integer.parseInt(args[3]); - } else { - cmds.msgError(args[3] + " is not a valid number."); - return true; - } - } - - Crate crate = Crate.getCrate(cc, args[1]); - ItemStack toAdd = crate.getSettings().getCrateItemHandler().getItem(amount); - - if (args.length < 3) { - if (cmds.getCmdSender() instanceof Player) { - Player p = (Player) cmds.getCmdSender(); - cmds.msgSuccess("Given crate for crate: " + args[1]); - Utils.addItemAndDropRest(p, toAdd); - } - return true; - } - - String end = args[args.length - 1]; - boolean isVirtual = end.toLowerCase().startsWith("-v"); - - if (args[2].equalsIgnoreCase("ALL")) { - if (isVirtual) { - for (Player p : Bukkit.getOnlinePlayers()) { - PlayerDataManager pdm = PlayerManager.get(cc, p).getPlayerDataManager(); - pdm.setVirtualCrateCrates(crate, pdm.getVCCrateData(crate).getCrates() + amount); - } - cmds.msgSuccess("Given a virtual crate for " + args[1] + " to every online player."); - return true; - } - cmds.msgSuccess("Given a physical crate for " + args[1] + " to every online player."); - Utils.giveAllItem(toAdd); - return true; - } - - Player op = Bukkit.getPlayer(args[2]); - Player op2 = null; - try { - op2 = Bukkit.getPlayer(UUID.fromString(args[2])); - } catch (Exception exc) { - // IGNORED - } - - boolean foundPlayer = true; - - if (op == null && op2 == null && !args[2].equalsIgnoreCase("ALL")) { - foundPlayer = false; - } - - if (!foundPlayer) { - OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(args[2]); - - cmds.msgError(args[2] + - " is not an online player / online player's UUID. Adding the commands to the queue for when they rejoin."); - DataHandler dataHandler = cc.getDataHandler(); - try { - DataHandler.QueuedGiveCommand queuedGiveCommand = dataHandler.new QueuedGiveCommand( - offlinePlayer.getUniqueId(), false, isVirtual, - amount, crate); - - dataHandler.addQueuedGiveCommand(queuedGiveCommand); - } catch (Exception exc) { - exc.printStackTrace(); - cmds.msgError("FAILED to add the give command! The player and/or UUID do not exist."); - } - return false; - } - - Player toGive = op == null ? op2 : op; - PlayerDataManager pdm = PlayerManager.get(cc, toGive).getPlayerDataManager(); - if (isVirtual) { - pdm.setVirtualCrateCrates(crate, pdm.getVCCrateData(crate).getCrates() + amount); - cmds.msgSuccess("Given virtual crate for crate: " + args[1]); - } else { - Utils.addItemAndDropRest(toGive, toAdd); - cmds.msgSuccess("Given physical crate for crate: " + args[1]); - } - return true; - } - cmds.msgError(args[1] + " crate does NOT exist."); - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/commands/sub/GiveKey.java b/src/main/java/me/ztowne13/customcrates/commands/sub/GiveKey.java deleted file mode 100644 index 2e08756..0000000 --- a/src/main/java/me/ztowne13/customcrates/commands/sub/GiveKey.java +++ /dev/null @@ -1,151 +0,0 @@ -package me.ztowne13.customcrates.commands.sub; - -import me.ztowne13.customcrates.DataHandler; -import me.ztowne13.customcrates.Messages; -import me.ztowne13.customcrates.SettingsValue; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.commands.Commands; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.players.PlayerDataManager; -import me.ztowne13.customcrates.players.PlayerManager; -import me.ztowne13.customcrates.utils.Utils; -import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - -import java.util.UUID; - -/** - * Created by ztowne13 on 6/23/16. - */ -public class GiveKey extends SubCommand { - public GiveKey() { - super("givekey", 2, "Usage: /SCrates GiveKey (Crate) (Player/ALL) [Amount] [-v : for a virtual crate]", - new String[]{"gkey", "gk", "key"}); - } - - @SuppressWarnings("deprecated") - @Override - public boolean run(SpecializedCrates cc, Commands cmds, String[] args) { - if (Crate.exists(args[1])) { - int amount = 1; - if (args.length >= 4) { - if (Utils.isInt(args[3])) { - amount = Integer.parseInt(args[3]); - } else { - cmds.msgError(args[3] + " is not a valid number."); - return true; - } - } - - Crate crate = Crate.getCrate(cc, args[1]); - ItemStack toAdd = crate.getSettings().getKeyItemHandler().getItem(amount); - - if (args.length < 3) { - if (cmds.getCmdSender() instanceof Player) { - Player p = (Player) cmds.getCmdSender(); - cmds.msgSuccess("Given key for crate: " + args[1]); - - boolean toNotDrop = SettingsValue.VIRTUAL_KEY_INSTEAD_OF_DROP.getValue(cc).equals(Boolean.TRUE); - int count = Utils.addItemAndDropRest(p, toAdd, !toNotDrop); - - if (toNotDrop) { - PlayerDataManager pdm = PlayerManager.get(cc, p).getPlayerDataManager(); - pdm.setVirtualCrateKeys(crate, pdm.getVCCrateData(crate).getKeys() + count); - if (count != 0) { - Messages.RECEIVED_VIRTUAL_KEY - .msgSpecified(cc, p, new String[]{"%crate%", "%amount%"}, new String[]{crate.getDisplayName(), "" + count}); - } - Messages.RECEIVED_KEY.msgSpecified(cc, p, new String[]{"%crate%", "%amount%"}, new String[]{crate.getDisplayName(), "" + (amount - count)}); - } else { - Messages.RECEIVED_KEY.msgSpecified(cc, p, new String[]{"%crate%", "%amount%"}, new String[]{crate.getDisplayName(), "" + amount}); - } - } - return true; - } - - String end = args[args.length - 1]; - boolean isVirtual = end.toLowerCase().startsWith("-v"); - - if (args[2].equalsIgnoreCase("ALL")) { - if (isVirtual) { - for (Player p : Bukkit.getOnlinePlayers()) { - PlayerDataManager pdm = PlayerManager.get(cc, p).getPlayerDataManager(); - pdm.setVirtualCrateKeys(crate, pdm.getVCCrateData(crate).getKeys() + amount); - Messages.RECEIVED_VIRTUAL_KEY.msgSpecified(cc, p, new String[]{"%crate%", "%amount%"}, new String[]{crate.getDisplayName(), "" + amount}); - } - cmds.msgSuccess("Given a virtual key for " + args[1] + " to every online player."); - return true; - } - Utils.giveAllItem(toAdd); - for (Player p : Bukkit.getOnlinePlayers()) { - Messages.RECEIVED_KEY.msgSpecified(cc, p, new String[]{"%crate%", "%amount%"}, new String[]{crate.getDisplayName(), "" + amount}); - } - cmds.msgSuccess("Given a physical key for " + args[1] + " to every online player."); - return true; - } - - Player op = Bukkit.getPlayer(args[2]); - Player op2 = null; - try { - op2 = Bukkit.getPlayer(UUID.fromString(args[2])); - } catch (Exception exc) { - // IGNORED - } - - boolean foundPlayer = true; - - if (op == null && op2 == null && !args[2].equalsIgnoreCase("ALL")) { - foundPlayer = false; - } - - if (!foundPlayer) { - OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(args[2]); - - cmds.msgError(args[2] + - " is not an online player / online player's UUID. Adding the commands to the queue for when they rejoin."); - DataHandler dataHandler = cc.getDataHandler(); - try { - DataHandler.QueuedGiveCommand queuedGiveCommand = dataHandler.new QueuedGiveCommand( - offlinePlayer.getUniqueId(), true, isVirtual, - amount, crate); - - dataHandler.addQueuedGiveCommand(queuedGiveCommand); - } catch (Exception exc) { - exc.printStackTrace(); - cmds.msgError("FAILED to add the give command! The player and/or UUID do not exist."); - } - return false; - } - - Player toGive = op == null ? op2 : op; - PlayerDataManager pdm = PlayerManager.get(cc, toGive).getPlayerDataManager(); - if (isVirtual) { - pdm.setVirtualCrateKeys(crate, pdm.getVCCrateData(crate).getKeys() + amount); - cmds.msgSuccess("Given virtual key for crate: " + args[1]); - Messages.RECEIVED_VIRTUAL_KEY.msgSpecified(cc, toGive, new String[]{"%crate%", "%amount%"}, new String[]{crate.getDisplayName(), "" + amount}); - } else { - Boolean toNotDrop = SettingsValue.VIRTUAL_KEY_INSTEAD_OF_DROP.getValue(cc).equals(Boolean.TRUE); - int count = Utils.addItemAndDropRest(toGive, toAdd, !toNotDrop); - - if (toNotDrop) { - pdm.setVirtualCrateKeys(crate, pdm.getVCCrateData(crate).getKeys() + count); - if (count != 0) { - Messages.RECEIVED_VIRTUAL_KEY - .msgSpecified(cc, toGive, new String[]{"%crate%", "%amount%"}, new String[]{crate.getDisplayName(), "" + count}); - } - - Messages.RECEIVED_KEY.msgSpecified(cc, toGive, new String[]{"%crate%", "%amount%"}, new String[]{crate.getDisplayName(), "" + (amount - count)}); - } else { - Messages.RECEIVED_KEY.msgSpecified(cc, toGive, new String[]{"%crate%", "%amount%"}, new String[]{crate.getDisplayName(), "" + amount}); - } - - cmds.msgSuccess("Given physical key for crate: " + args[1]); - } - return true; - } - cmds.msgError(args[1] + " crate does NOT exist."); - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/commands/sub/Help.java b/src/main/java/me/ztowne13/customcrates/commands/sub/Help.java deleted file mode 100644 index 558a5df..0000000 --- a/src/main/java/me/ztowne13/customcrates/commands/sub/Help.java +++ /dev/null @@ -1,29 +0,0 @@ -package me.ztowne13.customcrates.commands.sub; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.commands.Commands; -import me.ztowne13.customcrates.utils.Utils; - -/** - * Created by ztowne13 on 6/23/16. - */ -public class Help extends SubCommand { - public Help() { - super("help", 1, ""); - } - - @Override - public boolean run(SpecializedCrates cc, Commands cmds, String[] args) { - if (args.length == 2) { - if (Utils.isInt(args[1])) { - cmds.msgPage(Integer.parseInt(args[1])); - return true; - } else { - cmds.msgError(args[1] + " is not a valid page number."); - return false; - } - } - cmds.msgPage(1); - return true; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/commands/sub/Info.java b/src/main/java/me/ztowne13/customcrates/commands/sub/Info.java deleted file mode 100644 index a39b718..0000000 --- a/src/main/java/me/ztowne13/customcrates/commands/sub/Info.java +++ /dev/null @@ -1,24 +0,0 @@ -package me.ztowne13.customcrates.commands.sub; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.commands.Commands; - -/** - * Created by ztowne13 on 6/23/16. - */ -public class Info extends SubCommand { - public Info() { - super("info", 1, "", new String[]{"about", "inf", "details"}); - } - - @Override - public boolean run(SpecializedCrates cc, Commands cmds, String[] args) { - cc.getSettings().loadInfo(); - cmds.msg("&6&lCurrent &e&lS&7&lC &6&lInformation >"); - - for (String s : cc.getSettings().getInfoToLog().keySet()) { - cmds.msg(" &b" + s + " &3&l- &a" + cc.getSettings().getInfoToLog().get(s)); - } - return true; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/commands/sub/LastConfigMenu.java b/src/main/java/me/ztowne13/customcrates/commands/sub/LastConfigMenu.java deleted file mode 100644 index 9572bfd..0000000 --- a/src/main/java/me/ztowne13/customcrates/commands/sub/LastConfigMenu.java +++ /dev/null @@ -1,27 +0,0 @@ -package me.ztowne13.customcrates.commands.sub; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.commands.Commands; -import me.ztowne13.customcrates.players.PlayerManager; -import org.bukkit.entity.Player; - -/** - * Created by ztowne13 on 6/23/16. - */ -public class LastConfigMenu extends SubCommand { - public LastConfigMenu() { - super("!", 1, ""); - } - - @Override - public boolean run(SpecializedCrates cc, Commands cmds, String[] args) { - Player p = (Player) cmds.getCmdSender(); - try { - PlayerManager.get(cc, p).getLastOpenMenu().open(); - cmds.msgSuccess("Opened last crate config page."); - } catch (Exception exc) { - p.chat("/scrates config"); - } - return true; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/commands/sub/ListCrates.java b/src/main/java/me/ztowne13/customcrates/commands/sub/ListCrates.java deleted file mode 100644 index ab8d85a..0000000 --- a/src/main/java/me/ztowne13/customcrates/commands/sub/ListCrates.java +++ /dev/null @@ -1,22 +0,0 @@ -package me.ztowne13.customcrates.commands.sub; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.commands.Commands; -import me.ztowne13.customcrates.crates.Crate; - -/** - * Created by ztowne13 on 6/23/16. - */ -public class ListCrates extends SubCommand { - public ListCrates() { - super("listcrates", 1, "", new String[]{"crates", "lcrates", "listcrate"}); - } - - @Override - public boolean run(SpecializedCrates cc, Commands cmds, String[] args) { - for (Crate crates : Crate.getLoadedCrates().values()) { - cmds.msg("&6- &f" + crates.getName()); - } - return true; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/commands/sub/ListHistory.java b/src/main/java/me/ztowne13/customcrates/commands/sub/ListHistory.java deleted file mode 100644 index ed706e3..0000000 --- a/src/main/java/me/ztowne13/customcrates/commands/sub/ListHistory.java +++ /dev/null @@ -1,33 +0,0 @@ -package me.ztowne13.customcrates.commands.sub; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.commands.Commands; -import me.ztowne13.customcrates.players.data.events.HistoryEvent; -import me.ztowne13.customcrates.utils.Utils; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - -/** - * Created by ztowne13 on 6/23/16. - */ -public class ListHistory extends SubCommand { - public ListHistory() { - super("listhistory", 3, "Usage: /SCrates listHistory (Player) (Amount of shown entries)", new String[]{"lhistory", "history"}); - } - - @Override - public boolean run(SpecializedCrates cc, Commands cmds, String[] args) { - Player p = Bukkit.getPlayer(args[1]); - if (p != null) { - if (Utils.isInt(args[2])) { - int showEntries = Integer.parseInt(args[2]); - HistoryEvent.listFor(cc, cmds.getCmdSender(), p, showEntries); - } else { - cmds.msgError(args[2] + " is not a valid "); - } - } else { - cmds.msgError(args[1] + " is not an online player."); - } - return true; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/commands/sub/Reload.java b/src/main/java/me/ztowne13/customcrates/commands/sub/Reload.java deleted file mode 100644 index 5562ba0..0000000 --- a/src/main/java/me/ztowne13/customcrates/commands/sub/Reload.java +++ /dev/null @@ -1,22 +0,0 @@ -package me.ztowne13.customcrates.commands.sub; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.commands.Commands; - -/** - * Created by ztowne13 on 6/23/16. - */ -public class Reload extends SubCommand { - public Reload() { - super("reload", 1, ""); - } - - @Override - public boolean run(SpecializedCrates cc, Commands cmds, String[] args) { - long start = System.currentTimeMillis(); - cmds.msg("&6&lINFO! &eReloading..."); - cc.reload(); - cmds.msgSuccess("Reloaded the Specialized Crate plugin &7(" + (System.currentTimeMillis() - start) + "ms)&a."); - return true; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/commands/sub/SpawnCrate.java b/src/main/java/me/ztowne13/customcrates/commands/sub/SpawnCrate.java deleted file mode 100644 index bc57b4d..0000000 --- a/src/main/java/me/ztowne13/customcrates/commands/sub/SpawnCrate.java +++ /dev/null @@ -1,53 +0,0 @@ -package me.ztowne13.customcrates.commands.sub; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.commands.Commands; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.PlacedCrate; -import me.ztowne13.customcrates.utils.Utils; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.World; - -public class SpawnCrate extends SubCommand { - public SpawnCrate() { - super("spawncrate", 5, "/scrates spawncrate (crate) (world) X Y Z"); - } - - @Override - public boolean run(SpecializedCrates cc, Commands cmds, String[] args) { - if (Crate.exists(args[1])) { - Crate toSpawn = Crate.getCrate(cc, args[1]); - World world = Bukkit.getWorld(args[2]); - - if (world == null) { - cmds.msgError(args[2] + " is not a valid world."); - return false; - } - - if (!Utils.isInt(args[5])) { - cmds.msgError(args[5] + " is not a valid number."); - return false; - } - if (!Utils.isInt(args[3])) { - cmds.msgError(args[3] + " is not a valid number."); - return false; - } - if (!Utils.isInt(args[4])) { - cmds.msgError(args[4] + " is not a valid number."); - return false; - } - - int x = Integer.parseInt(args[3]); - int y = Integer.parseInt(args[4]); - int z = Integer.parseInt(args[5]); - - Location location = new Location(world, x, y, z); - - PlacedCrate cm = PlacedCrate.get(cc, location); - cm.setup(toSpawn, true, false); - cmds.msgSuccess("Created crate in world " + world.getName() + " at " + x + ", " + y + ", " + z); - } - return true; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/commands/sub/SubCommand.java b/src/main/java/me/ztowne13/customcrates/commands/sub/SubCommand.java deleted file mode 100644 index 9ee80df..0000000 --- a/src/main/java/me/ztowne13/customcrates/commands/sub/SubCommand.java +++ /dev/null @@ -1,61 +0,0 @@ -package me.ztowne13.customcrates.commands.sub; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.commands.Commands; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.command.CommandSender; - -import java.util.HashMap; -import java.util.Map; - -/** - * Created by ztowne13 on 6/23/16. - */ -public abstract class SubCommand { - private static final HashMap mappedAliases = new HashMap<>(); - private final String[] aliases; - private final int minimumArgs; - private final String commandTitle; - private final String usageMessage; - - public SubCommand(String commandTitle, int minimumArgs, String usageMessage) { - this(commandTitle, minimumArgs, usageMessage, new String[]{}); - } - - public SubCommand(String commandTitle, int minimumArgs, String usageMessage, String[] aliases) { - this.minimumArgs = minimumArgs; - this.commandTitle = commandTitle; - this.usageMessage = usageMessage; - this.aliases = aliases; - for (String alias : aliases) { - mappedAliases.put(alias, commandTitle); - } - } - - public static Map getMappedAliases() { - return mappedAliases; - } - - public abstract boolean run(SpecializedCrates cc, Commands cmds, String[] args); - - public boolean checkProperUsage(CommandSender sender, String[] args) { - boolean enoughArgs = args.length >= minimumArgs; - if (!enoughArgs) { - sender.sendMessage(ChatUtils.toChatColor("&4&lERROR! &c" + ChatUtils.toChatColor(usageMessage))); - } - - return enoughArgs; - } - - public boolean isCommand(String s) { - if (commandTitle.equalsIgnoreCase(s)) { - return true; - } - for (String alias : aliases) { - if (alias.equalsIgnoreCase(s)) { - return true; - } - } - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/commands/sub/ToggleParticles.java b/src/main/java/me/ztowne13/customcrates/commands/sub/ToggleParticles.java deleted file mode 100644 index 464a5de..0000000 --- a/src/main/java/me/ztowne13/customcrates/commands/sub/ToggleParticles.java +++ /dev/null @@ -1,22 +0,0 @@ -package me.ztowne13.customcrates.commands.sub; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.commands.Commands; - -public class ToggleParticles extends SubCommand { - public ToggleParticles() { - super("toggleparticles", 0, "", new String[]{"particles", "togleparticles", "toggleparticle", "tparticles"}); - } - - @Override - public boolean run(SpecializedCrates cc, Commands cmds, String[] args) { - cc.setParticlesEnabled(!cc.isParticlesEnabled()); - if (cc.isParticlesEnabled()) { - cmds.msgSuccess("Particles have been re-enabled!"); - } else { - cmds.msgSuccess("Particles have been &2&lTEMPORARILY &adisabled. This particle toggle does NOT persist through reloads or restarts. If you truly want " + - "the particles to be disabled, considered changing the 'particle-view-distance' in the config.yml to 0."); - } - return true; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/commands/sub/VirtualCrates.java b/src/main/java/me/ztowne13/customcrates/commands/sub/VirtualCrates.java deleted file mode 100644 index 26b037b..0000000 --- a/src/main/java/me/ztowne13/customcrates/commands/sub/VirtualCrates.java +++ /dev/null @@ -1,55 +0,0 @@ -package me.ztowne13.customcrates.commands.sub; - -import me.ztowne13.customcrates.Messages; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.commands.Commands; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.players.PlayerManager; -import org.bukkit.entity.Player; - -/** - * Created by ztowne13 on 8/3/16. - */ -public class VirtualCrates extends SubCommand { - private boolean tryLoad = false; - private boolean successfulLoad = false; - private Crate crate; - - public VirtualCrates() { - super("virtualcrates", 1, ""); - } - - @Override - public boolean run(SpecializedCrates cc, Commands cmds, String[] args) { - if (!tryLoad) { - tryLoad = true; - - String crateName = cc.getSettings().getConfigValues().get("crates-command-multicrate").toString(); - if (Crate.exists(crateName)) { - crate = Crate.getCrate(cc, crateName); - successfulLoad = crate.isMultiCrate(); - } - } - - if (cmds.canExecute(false, true, "customcrates.crates", "specializedcrates.crates") || - cmds.canExecute(false, true, "customcrates.admin", "specializedcrates.admin")) { - if (successfulLoad) { - Player p = (Player) cmds.getCmdSender(); - PlayerManager pm = PlayerManager.get(cc, p); - Messages.OPENING_VIRTUALCRATES.msgSpecified(cc, p); - crate.getSettings().getMultiCrateSettings() - .getInventory(p, cc.getSettings().getConfigValues().get("crates-command-name").toString(), true) - .open(); - // FIX THIS BECAUSE I THINK THE CODE CHECKS IF THE LAST OPENED CRATE WAS A MULTICRATE BY CHECKING ITS LOCATION - pm.setLastOpenCrate(p.getLocation()); - pm.openCrate(crate); - pm.setUseVirtualCrate(true); - return true; - } - cmds.msgError( - "The crate name specified for this command is either not a valid crate name or the crate is not a mutlicrate."); - return true; - } - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/Crate.java b/src/main/java/me/ztowne13/customcrates/crates/Crate.java deleted file mode 100644 index 91ad5f1..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/Crate.java +++ /dev/null @@ -1,299 +0,0 @@ -package me.ztowne13.customcrates.crates; - -import me.ztowne13.customcrates.DataHandler; -import me.ztowne13.customcrates.SettingsValue; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import me.ztowne13.customcrates.interfaces.files.FileHandler; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.CrateUtils; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.*; - -public class Crate { - private static Map loadedCrates = new HashMap<>(); - - private final SpecializedCrates instance; - private final boolean loadedProperly; - private String name; - private int placedCount = 0; - private String lastOpenedName = "Nobody"; - private String lastOpenedReward = "Nothing"; - private boolean enabled = true; - private boolean disabledByError = false; - private boolean canBeEnabled = true; - private boolean isMultiCrate; - private boolean isUsedForCratesCommand = false; - private boolean needsReload = false; - - private CrateSettings crateSettings; - - public Crate(SpecializedCrates instance, String name, boolean newFile) { - this(instance, name, newFile, false); - } - - public Crate(SpecializedCrates instance, String name, boolean newFile, boolean isMultiCrate) { - instance.getDebugUtils().log("Crate() - new", getClass()); - this.instance = instance; - this.name = name; - - this.isMultiCrate = isMultiCrate; - this.crateSettings = new CrateSettings(instance, this, newFile); - - setEnabled(!getSettings().getSettingsBuilder().hasValue("enabled") || crateSettings.getFileConfiguration().getBoolean("enabled")); - - getLoadedCrates().put(name, this); - - getSettings().loadAll(); - loadedProperly = true; - } - - public static Crate getCrate(SpecializedCrates cc, String name) { - return getCrate(cc, name, false); - } - - public static Crate getCrate(SpecializedCrates cc, String name, boolean isMultiCrate) { - for (String crateName : getLoadedCrates().keySet()) { - if (crateName.equalsIgnoreCase(name)) { - return getLoadedCrates().get(crateName); - } - } - - return new Crate(cc, name, false, isMultiCrate); - } - - public static boolean existsNotCaseSensitive(String name) { - for (String crates : getLoadedCrates().keySet()) { - if (crates.equalsIgnoreCase(name)) { - return true; - } - } - return false; - } - - public static boolean exists(String name) { - return getLoadedCrates().containsKey(name); - } - - public static void clearLoaded() { - getLoadedCrates().clear(); - setLoadedCrates(new HashMap<>()); - } - - public static Map getLoadedCrates() { - return loadedCrates; - } - - public static void setLoadedCrates(Map loadedCrates) { - Crate.loadedCrates = loadedCrates; - } - - public void tick(Location l, CrateState cstate, Player p, List rewards) { - tick(l, null, cstate, p, rewards); - } - - public void tick(Location l, PlacedCrate placedCrate, CrateState cstate, Player p, List rewards) { - getSettings().getParticle().runAll(l, cstate, rewards); - if (cstate.equals(CrateState.OPEN) && CrateUtils.isCrateUsable(this)) { - getSettings().getSound().runAll(p, l, rewards); - getSettings().getFirework().runAll(l, rewards); - if (rewards != null && !rewards.isEmpty()) { - getSettings().getAction().playAll(p, placedCrate, rewards, false); - } - } - } - - public boolean rename(String newName) { - - if (newName.contains(".")) { - newName = newName.split("\\.")[0]; - } - - if (FileHandler.getMap().containsKey(newName + ".crate") || - FileHandler.getMap().containsKey(newName + ".multicrate")) { - return false; - } - - FileHandler newFile = - new FileHandler(getInstance(), newName + (isMultiCrate() ? ".multicrate" : ".crate"), - "/Crates", true, true, true); - newFile.reload(); - - try { - getSettings().getFileHandler().copy(newFile); - } catch (Exception exc) { - exc.printStackTrace(); - return false; - } - - HashMap placed = new HashMap<>(PlacedCrate.getPlacedCrates()); - - for (Map.Entry entry : placed.entrySet()) { - PlacedCrate cm = entry.getValue(); - if (cm.getCrate().equals(this)) { - cm.rename(newName); - PlacedCrate.getPlacedCrates().remove(entry.getKey()); - } - } - - deleteCrate(); - return true; - } - - public String deleteCrate() { - deleteAllPlaced(); - - Path path = getSettings().getFileHandler().getDataFile().toPath(); - - try { - Files.deleteIfExists(path); - ChatUtils.log("Successfully deleted file " + path); - } catch (Exception e) { - return "An I/O error occurred, please try reloading or contacting the plugin author."; - } - - for (UUID id : instance.getDataHandler().getQueuedGiveCommands().keySet()) { - List cmds = instance.getDataHandler().getQueuedGiveCommands().get(id); - for (DataHandler.QueuedGiveCommand cmd : cmds) { - if (cmd.getCrate().equals(this)) { - cmds.remove(cmd); - instance.getDataHandler().getQueuedGiveCommands().remove(id); - instance.getDataHandler().getQueuedGiveCommands().put(id, cmds); - } - } - } - - instance.getDataHandler().saveToFile(); - - Bukkit.getScheduler().scheduleSyncDelayedTask(instance, instance::reload, 20); - return path.toString(); - } - - public List deleteAllPlaced() { - HashMap placed = new HashMap<>(PlacedCrate.getPlacedCrates()); - ArrayList deleted = new ArrayList<>(); - - for (PlacedCrate cm : placed.values()) { - if (cm.getCrate().equals(this)) { - deleted.add(cm); - cm.getCrate().getSettings().getPlaceholder().remove(cm); - cm.delete(); - } - } - - return deleted; - } - - public SpecializedCrates getInstance() { - return instance; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public CrateSettings getSettings() { - return crateSettings; - } - - public void setSettings(CrateSettings cs) { - this.crateSettings = cs; - } - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - for (PlacedCrate cm : PlacedCrate.getPlacedCrates().values()) { - cm.setCratesEnabled(enabled); - } - - this.enabled = enabled; - } - - public boolean isCanBeEnabled() { - return canBeEnabled; - } - - public void setCanBeEnabled(boolean canBeEnabled) { - this.canBeEnabled = canBeEnabled; - } - - public boolean isMultiCrate() { - return isMultiCrate; - } - - public void setMultiCrate(boolean multiCrate) { - isMultiCrate = multiCrate; - } - - public int getPlacedCount() { - return placedCount; - } - - public void setPlacedCount(int placedCount) { - this.placedCount = placedCount; - } - - public boolean isUsedForCratesCommand() { - return isUsedForCratesCommand; - } - - public void setUsedForCratesCommand(boolean usedForCratesCommand) { - isUsedForCratesCommand = usedForCratesCommand; - } - - public String getLastOpenedName() { - return lastOpenedName; - } - - public void setLastOpenedName(String lastOpenedName) { - this.lastOpenedName = lastOpenedName; - } - - public String getLastOpenedReward() { - return lastOpenedReward; - } - - public void setLastOpenedReward(String lastOpenedReward) { - this.lastOpenedReward = lastOpenedReward; - } - - public String getDisplayName() { - if (SettingsValue.USE_CRATE_NAME_FOR_DISPLAY.getValue(getInstance()).equals(Boolean.TRUE) - && getSettings().getCrateItemHandler().getItem().hasDisplayName()) { - return getSettings().getCrateItemHandler().getItem().getDisplayName(true); - } - return getName(); - } - - public boolean isLoadedProperly() { - return loadedProperly; - } - - public boolean isNeedsReload() { - return needsReload; - } - - public void setNeedsReload(boolean needsReload) { - this.needsReload = needsReload; - } - - public boolean isDisabledByError() { - return disabledByError; - } - - public void setDisabledByError(boolean disabledByError) { - this.disabledByError = disabledByError; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/CrateSettings.java b/src/main/java/me/ztowne13/customcrates/crates/CrateSettings.java deleted file mode 100644 index bc71916..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/CrateSettings.java +++ /dev/null @@ -1,474 +0,0 @@ -package me.ztowne13.customcrates.crates; - -import me.ztowne13.customcrates.SettingsValue; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.options.*; -import me.ztowne13.customcrates.crates.options.rewards.displaymenu.RewardDisplayType; -import me.ztowne13.customcrates.crates.options.rewards.displaymenu.RewardDisplayer; -import me.ztowne13.customcrates.crates.types.animations.CrateAnimation; -import me.ztowne13.customcrates.crates.types.animations.CrateAnimationType; -import me.ztowne13.customcrates.crates.types.display.CrateDisplayType; -import me.ztowne13.customcrates.crates.types.display.DynamicCratePlaceholder; -import me.ztowne13.customcrates.interfaces.files.FileHandler; -import me.ztowne13.customcrates.interfaces.logging.StatusLogger; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.CrateUtils; -import org.bukkit.configuration.file.FileConfiguration; - -public class CrateSettings { - private final SpecializedCrates instance; - private final CrateSettingsBuilder crateSettingsBuilder; - private boolean requireKey; - private boolean tiersOverrideDefaults = true; - private ObtainType obtainType; - private int cooldown = 0; - private int cost = -1; - private double hologramOffset = 0; - private KeyItemHandler keyItemHandler; - private CrateItemHandler crateItemHandler; - private CrateDisplayType crateDisplayType = CrateDisplayType.BLOCK; - private DynamicCratePlaceholder dynamicCratePlaceholder; - private RewardDisplayer displayer; - private RewardDisplayType rewardDisplayType; - private CrateAnimation crateAnimation; - private CrateAnimationType crateAnimationType; - private boolean canFastTrack = false; - private boolean autoClose = true; - private CHologram hologram; - private CParticle particle; - private CSound sound; - private CAction action; - private CFirework firework; - private CLuckyChest luckyChest; - private CReward reward; - private CMultiCrateInventory multiCrateInventory; - private Crate crate; - private StatusLogger statusLogger; - private String name; - private String crateInventoryName = ""; - private String permission = "no permission"; - private FileConfiguration fileConfiguration; - private FileHandler fileHandler; - - public CrateSettings(SpecializedCrates instance, Crate crate, boolean newFile) { - this.instance = instance; - this.crate = crate; - this.name = crate.getName(); - this.statusLogger = new StatusLogger(instance); - - this.fileHandler = new FileHandler(instance, crate.getName() + (crate.isMultiCrate() ? ".multicrate" : ".crate"), "/Crates", true, - true, newFile); - this.fileConfiguration = fileHandler.get(); - - this.crateSettingsBuilder = new CrateSettingsBuilder(this); - } - - public void saveAll() { - saveIndividualValues(); - - getKeyItemHandler().saveToFile(); - getCrateItemHandler().saveToFile(); - - if (getObtainType().equals(ObtainType.LUCKYCHEST)) { - getLuckyChestSettings().saveToFile(); - } - getHologram().saveToFile(); - getParticle().saveToFile(); - getSound().saveToFile(); - - if (!getCrate().isMultiCrate()) { - getReward().saveToFile(); - getAction().saveToFile(); - getFirework().saveToFile(); - getDisplayer().saveToFile(); - } else { - getMultiCrateSettings().saveToFile(); - } - - getFileHandler().save(); - } - - - public void saveIndividualValues() { - fileConfiguration.set("enabled", crate.isEnabled()); - fileConfiguration.set("cooldown", getCooldown()); - fileConfiguration.set("obtain-method", getObtainType().name()); - fileConfiguration.set("display.type", getPlaceholder().toString()); - fileConfiguration.set("hologram-offset", getHologramOffset()); - fileConfiguration.set("auto-close", isAutoClose()); - fileConfiguration.set("key.require", isRequireKey()); - fileConfiguration.set("cost", getCost()); - fileConfiguration.set("allow-skip-animation", isCanFastTrack()); - - fileConfiguration.set("permission", getPermission().equalsIgnoreCase("no permission") ? null : getPermission()); - - if (!getPlaceholder().toString().equalsIgnoreCase("block")) { - fileConfiguration.set("display." + (getPlaceholder().toString().equalsIgnoreCase("mob") ? "creature" : "name"), getPlaceholder().getType()); - } - - if (getCrateInventoryName() != null) { - fileConfiguration.set("inventory-name", ChatUtils.fromChatColor(getCrateInventoryName())); - } - - if (!getCrate().isMultiCrate()) { - fileConfiguration.set("open.crate-animation", getCrateType().name()); - } - - } - - public void loadAll() { - instance.getDebugUtils().log("loadAll() - CALL"); - // Crate Loging - String toLog = SettingsValue.LOG_SUCCESSES.getValue(getCrate().getInstance()).toString(); - instance.getDebugUtils().log("loadAll() - Preparing to load notice."); - loadNotice(toLog); - instance.getDebugUtils().log("loadAll() - Loaded notice."); - - setParticle(new CParticle(getCrate())); - setHologram(new CHologram(getCrate())); - setKeyItemHandler(new KeyItemHandler(getCrate())); - setCrateItemHandler(new CrateItemHandler(getCrate())); - setSound(new CSound(getCrate())); - - if (!getCrate().isMultiCrate()) { - setReward(new CReward(getCrate())); - setAction(new CAction(getCrate())); - setFirework(new CFirework(getCrate())); - setLuckyChestSettings(new CLuckyChest(getCrate())); - } else { - setMultiCrateSettings(new CMultiCrateInventory(getCrate())); - } - - if (getFileHandler().isProperLoad()) { - // Base Settings - - getCrateItemHandler().loadFor(getSettingsBuilder(), null); - getSettingsBuilder().setupCooldown(); - getSettingsBuilder().setupDisplay(); - getSettingsBuilder().setupObtainMethod(); - getSettingsBuilder().setupCrateInventoryName(); - getSettingsBuilder().setupPermission(); - getSettingsBuilder().setupAutoClose(); - getSettingsBuilder().setupHologramOffset(); - getSettingsBuilder().setupDisplayer(); - getSettingsBuilder().setupCost(); - getSettingsBuilder().setupAllowSkipAnimation(); - - // Base Settings for non-MultiCrates - if (!getCrate().isMultiCrate()) { - getKeyItemHandler().loadFor(getSettingsBuilder(), null); - getSettingsBuilder().setupCrateAnimation(); - } - - // Particles - getParticle().loadFor(getSettingsBuilder(), CrateState.PLAY); - getParticle().loadFor(getSettingsBuilder(), CrateState.OPEN); - - // Holograms - getHologram().loadFor(getSettingsBuilder(), CrateState.PLAY); - - // Sounds - getSound().loadFor(getSettingsBuilder(), CrateState.OPEN); - - // Lucky Chest - if (getObtainType().equals(ObtainType.LUCKYCHEST)) { - getLuckyChestSettings().loadFor(getSettingsBuilder(), null); - } - - if (!getCrate().isMultiCrate()) { - // Rewards - getReward().loadFor(getSettingsBuilder(), CrateState.OPEN); - - // Actions - getAction().loadFor(getSettingsBuilder(), CrateState.OPEN); - - // Fireworks - getFirework().loadFor(getSettingsBuilder(), CrateState.OPEN); - - getCrate().getSettings().getCrateType().setupFor(crate); - getCrateAnimation().loadDataValues(getStatusLogger()); - } else { - getMultiCrateSettings().loadFor(getSettingsBuilder(), CrateState.OPEN); - } - - - if (!toLog.equalsIgnoreCase("NOTHING")) { - getStatusLogger().logAll(); - } - } else { - crate.setEnabled(false); - crate.setCanBeEnabled(false); - } - } - - public void loadNotice(String toLog) { - if (!toLog.equalsIgnoreCase("NOTHING")) { - ChatUtils.log(""); - if (!CrateUtils.isCrateUsable(getCrate())) { - ChatUtils.log("&b" + getCrate().getName() + " &c(Disabled)"); - } else { - ChatUtils.log("&b" + getCrate().getName()); - } - } - } - - public boolean isRequireKey() { - return requireKey; - } - - public void setRequireKey(boolean requireKey) { - this.requireKey = requireKey; - } - - public Crate getCrate() { - return crate; - } - - public void setCrate(Crate crate) { - this.crate = crate; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public FileConfiguration getFileConfiguration() { - return fileConfiguration; - } - - public void setFileConfiguration(FileConfiguration fileConfiguration) { - this.fileConfiguration = fileConfiguration; - } - - public CParticle getParticle() { - return particle; - } - - public void setParticle(CParticle particle) { - this.particle = particle; - } - - public CReward getReward() { - return reward; - } - - public void setReward(CReward reward) { - this.reward = reward; - } - - public CHologram getHologram() { - return hologram; - } - - public void setHologram(CHologram holograms) { - this.hologram = holograms; - } - - public ObtainType getObtainType() { - return obtainType; - } - - public void setObtainType(ObtainType obtainType) { - this.obtainType = obtainType; - } - - public CrateAnimationType getCrateType() { - return crateAnimationType; - } - - public void setCrateType(CrateAnimationType crateType) { - this.crateAnimationType = crateType; - } - - public StatusLogger getStatusLogger() { - return statusLogger; - } - - public void setStatusLogger(StatusLogger statusLogger) { - this.statusLogger = statusLogger; - } - - public boolean isTiersOverrideDefaults() { - return tiersOverrideDefaults; - } - - public void setTiersOverrideDefaults(boolean tiersOverrideDefaults) { - this.tiersOverrideDefaults = tiersOverrideDefaults; - } - - public CrateSettingsBuilder getSettingsBuilder() { - return crateSettingsBuilder; - } - - public CLuckyChest getLuckyChestSettings() { - return luckyChest; - } - - public void setLuckyChestSettings(CLuckyChest luckyChest) { - this.luckyChest = luckyChest; - } - - public boolean luckyChestSettingsExists() { - return luckyChest != null; - } - - public int getCooldown() { - return cooldown; - } - - public void setCooldown(int cooldown) { - this.cooldown = cooldown; - } - - public SpecializedCrates getInstance() { - return instance; - } - - public KeyItemHandler getKeyItemHandler() { - return keyItemHandler; - } - - public void setKeyItemHandler(KeyItemHandler keyItemHandler) { - this.keyItemHandler = keyItemHandler; - } - - public CrateItemHandler getCrateItemHandler() { - return crateItemHandler; - } - - public void setCrateItemHandler(CrateItemHandler crateItemHandler) { - this.crateItemHandler = crateItemHandler; - } - - public DynamicCratePlaceholder getPlaceholder() { - return dynamicCratePlaceholder; - } - - public void setPlaceholder(DynamicCratePlaceholder dynamicCratePlaceholder) { - this.dynamicCratePlaceholder = dynamicCratePlaceholder; - } - - public CSound getSound() { - return sound; - } - - public void setSound(CSound sound) { - this.sound = sound; - } - - public CAction getAction() { - return action; - } - - public void setAction(CAction action) { - this.action = action; - } - - public CFirework getFirework() { - return firework; - } - - public void setFirework(CFirework firework) { - this.firework = firework; - } - - public CrateDisplayType getCrateDisplayType() { - return crateDisplayType; - } - - public void setCrateDisplayType(CrateDisplayType crateDisplayType) { - this.crateDisplayType = crateDisplayType; - } - - public FileHandler getFileHandler() { - return fileHandler; - } - - public void setFileHandler(FileHandler fileHandler) { - this.fileHandler = fileHandler; - } - - public String getCrateInventoryName() { - return crateInventoryName; - } - - public void setCrateInventoryName(String crateInventoryName) { - this.crateInventoryName = crateInventoryName; - } - - public CrateAnimation getCrateAnimation() { - return crateAnimation; - } - - public void setCrateAnimation(CrateAnimation crateAnimation) { - this.crateAnimation = crateAnimation; - } - - public String getPermission() { - return permission; - } - - public void setPermission(String permission) { - this.permission = permission; - } - - public boolean isAutoClose() { - return autoClose; - } - - public void setAutoClose(boolean autoClose) { - this.autoClose = autoClose; - } - - public CMultiCrateInventory getMultiCrateSettings() { - return multiCrateInventory; - } - - public void setMultiCrateSettings(CMultiCrateInventory multiCrateInventory) { - this.multiCrateInventory = multiCrateInventory; - } - - public double getHologramOffset() { - return hologramOffset; - } - - public void setHologramOffset(double hologramOffset) { - this.hologramOffset = hologramOffset; - } - - public RewardDisplayer getDisplayer() { - return displayer; - } - - public void setDisplayer(RewardDisplayer displayer) { - this.displayer = displayer; - } - - public RewardDisplayType getRewardDisplayType() { - return rewardDisplayType; - } - - public void setRewardDisplayType(RewardDisplayType rewardDisplayType) { - this.rewardDisplayType = rewardDisplayType; - } - - public int getCost() { - return cost; - } - - public void setCost(int cost) { - this.cost = cost; - } - - public boolean isCanFastTrack() { - return canFastTrack; - } - - public void setCanFastTrack(boolean canFastTrack) { - this.canFastTrack = canFastTrack; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/CrateSettingsBuilder.java b/src/main/java/me/ztowne13/customcrates/crates/CrateSettingsBuilder.java deleted file mode 100644 index cd07ead..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/CrateSettingsBuilder.java +++ /dev/null @@ -1,306 +0,0 @@ -package me.ztowne13.customcrates.crates; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.options.ObtainType; -import me.ztowne13.customcrates.crates.options.rewards.displaymenu.RewardDisplayType; -import me.ztowne13.customcrates.crates.options.rewards.displaymenu.SimpleRewardDisplayer; -import me.ztowne13.customcrates.crates.options.rewards.displaymenu.SortedRewardDisplayer; -import me.ztowne13.customcrates.crates.options.rewards.displaymenu.custom.CustomRewardDisplayer; -import me.ztowne13.customcrates.crates.types.animations.CrateAnimationType; -import me.ztowne13.customcrates.crates.types.display.CrateDisplayType; -import me.ztowne13.customcrates.crates.types.display.EntityType; -import me.ztowne13.customcrates.crates.types.display.MaterialPlaceholder; -import me.ztowne13.customcrates.crates.types.display.npcs.Citizens2NPCPlaceHolder; -import me.ztowne13.customcrates.crates.types.display.npcs.MobPlaceholder; -import me.ztowne13.customcrates.interfaces.logging.StatusLogger; -import me.ztowne13.customcrates.interfaces.logging.StatusLoggerEvent; -import me.ztowne13.customcrates.utils.NPCUtils; -import me.ztowne13.customcrates.utils.Utils; -import org.bukkit.configuration.file.FileConfiguration; - -public class CrateSettingsBuilder { - private final SpecializedCrates instance; - private CrateSettings settings; - private FileConfiguration fileConfiguration; - - public CrateSettingsBuilder(CrateSettings settings) { - this.settings = settings; - this.fileConfiguration = settings.getFileConfiguration(); - this.instance = settings.getCrate().getInstance(); - } - - public boolean hasValue(String path) { - return getFileConfiguration().contains((path)); - } - - public void setupAutoClose() { - if (hasValue("auto-close")) { - getSettings().setAutoClose(Boolean.parseBoolean(getFileConfiguration().getString("auto-close"))); - StatusLoggerEvent.SETTINGS_AUTOCLOSE_SUCCESS.log(getStatusLogger()); - } - } - - public void setupHologramOffset() { - if (hasValue("hologram-offset")) { - if (Utils.isDouble(fileConfiguration.getString("hologram-offset"))) { - getSettings().setHologramOffset(fileConfiguration.getDouble("hologram-offset")); - StatusLoggerEvent.SETTINGS_HOLOGRAMOFFSET_SUCCESS.log(getStatusLogger()); - return; - } - StatusLoggerEvent.SETTINGS_HOLOGRAMOFFSET_FAILURE.log(getStatusLogger()); - } - } - - public void setupRequireKey() { - if (hasValue("key.require")) { - getSettings().setRequireKey(getFileConfiguration().getBoolean(("key.require"))); - } else { - StatusLoggerEvent.SETTINGS_KEY_REQUIRE_NONEXISTENT.log(getStatusLogger()); - } - } - - public void setupObtainMethod() { - - if (hasValue("obtain-method")) { - try { - ObtainType ot = ObtainType.valueOf(getFileConfiguration().getString("obtain-method").toUpperCase()); - getSettings().setObtainType(ot); - StatusLoggerEvent.SETTINGS_OBTAINMETHOD_SUCCESS.log(getStatusLogger()); - } catch (Exception exc) { - StatusLoggerEvent.SETTINGS_OBTAINMETHOD_INVALID - .log(getStatusLogger(), getFileConfiguration().getString("obtain-method")); - } - return; - } - - StatusLoggerEvent.SETTINGS_OBTAINMETHOD_NONEXISTENT.log(getStatusLogger()); - } - - /*public void setupOverrideDefaults() - { - if(hasV("open.tier-actions-override-defaults")) - { - try - { - getSettings().setTiersOverrideDefaults(getSettings().getFc().getBoolean("open.tier-actions-override-defaults")); - getSl().addEvent(true, "Settings", "Loaded the 'open.tier-actions-override-defaults' value.", "NONE"); - } - catch(Exception exc) - { - getSl().addEvent(false, "Settings", "Failed to load the 'open.tier-actions-override-defaults' value.", getFc().getString("open.tier-actions-override-defaults") + " is not true or false."); - } - } - else - { - getSl().addEvent(false, "Settings", "The 'open.tier-actions-override-defaults' value does not exist.", "NONE"); - } - }*/ - - public void setupCrateAnimation() { - if (hasValue("open.crate-animation")) { - try { - getSettings().setCrateType(CrateAnimationType.valueOf(getFileConfiguration().getString(("open.crate-animation")))); - StatusLoggerEvent.SETTINGS_ANIMATION_SUCCESS.log(getStatusLogger()); - } catch (Exception exc) { - getSettings().setCrateType(CrateAnimationType.BLOCK_CRATEOPEN); - StatusLoggerEvent.SETTINGS_ANIMATION_INVALID - .log(getStatusLogger(), getFileConfiguration().getString("open.crate-animation")); - } - return; - } - - StatusLoggerEvent.SETTINGS_ANIMATION_NONEXISTENT.log(getStatusLogger()); - } - - public void setupCooldown() { - if (hasValue("cooldown")) { - try { - getSettings().setCooldown(getFileConfiguration().getInt("cooldown")); - StatusLoggerEvent.SETTINGS_COOLDOWN_SUCCESS.log(getStatusLogger()); - } catch (Exception exc) { - StatusLoggerEvent.SETTINGS_COOLDOWN_INVALID.log(getStatusLogger()); - } - return; - } - - getFileConfiguration().set("cooldown", 0); - } - - public void setupCost() { - if (hasValue("cost")) { - try { - getSettings().setCost(getFileConfiguration().getInt("cost")); - StatusLoggerEvent.SETTINGS_COST_SUCCESS.log(getStatusLogger()); - } catch (Exception exc) { - StatusLoggerEvent.SETTINGS_COST_INVALID.log(getStatusLogger()); - } - return; - } - - getFileConfiguration().set("cost", -1); - } - - public void setupAllowSkipAnimation() { - if (hasValue("allow-skip-animation")) { - try { - getSettings().setCanFastTrack(getFileConfiguration().getBoolean("allow-skip-animation")); - StatusLoggerEvent.SETTINGS_FASTTRACK_SUCCESS.log(getStatusLogger()); - } catch (Exception exc) { - StatusLoggerEvent.SETTINGS_FASTTRACK_INVALID.log(getStatusLogger()); - } - return; - } - - getFileConfiguration().set("allow-skip-animation", false); - } - - public void setupDisplay() { - if (hasValue("display")) { - CrateDisplayType cdt = CrateDisplayType.BLOCK; - - if (hasValue("display.type")) { - try { - cdt = CrateDisplayType.valueOf(getFileConfiguration().getString("display.type").toUpperCase()); - StatusLoggerEvent.SETTINGS_DISPLAYTYPE_SUCCESS.log(getStatusLogger()); - } catch (Exception exc) { - StatusLoggerEvent.SETTINGS_DISPLAYTYPE_INVALID - .log(getStatusLogger(), getFileConfiguration().getString("display.type")); - } - } - - if (!NPCUtils.isCitizensInstalled() && !cdt.equals(CrateDisplayType.BLOCK)) { - cdt = CrateDisplayType.BLOCK; - StatusLoggerEvent.SETTINGS_DISPLAYTYPE_FAIL_NOCITIZENS.log(getStatusLogger()); - } - - getSettings().setCrateDisplayType(cdt); - - if (cdt == CrateDisplayType.MOB) { - getSettings().setPlaceholder(new MobPlaceholder(instance)); - if (hasValue("display.creature")) { - try { - EntityType ent = EntityType.getEnum(getFileConfiguration().getString("display.creature").toUpperCase()); - getSettings().getPlaceholder().setType(ent.toString()); - - StatusLoggerEvent.SETTINGS_DISPLAYTYPE_CREATURE_SUCCESS.log(getStatusLogger()); - return; - } catch (Exception exc) { - exc.printStackTrace(); - StatusLoggerEvent.SETTINGS_DISPLAYTYPE_CREATURETYPE_INVALID - .log(getStatusLogger(), getFileConfiguration().getString("display.creature")); - } - } else { - StatusLoggerEvent.SETTINGS_DISPLAYTYPE_CREATURETYPE_NONEXISTENT.log(getStatusLogger()); - } - } else if (cdt == CrateDisplayType.NPC) { - getSettings().setPlaceholder(new Citizens2NPCPlaceHolder(instance)); - if (hasValue("display.name")) { - getSettings().getPlaceholder().setType(getFileConfiguration().getString("display.name")); - - StatusLoggerEvent.SETTINGS_DISPLAYTYPE_DISPLAYNAME_SUCCESS.log(getStatusLogger()); - return; - } - StatusLoggerEvent.SETTINGS_DISPLAYTYPE_DISPLAYNAME_NONEXISTENT.log(getStatusLogger()); - } - - getSettings().setPlaceholder(new MaterialPlaceholder(instance)); - return; - } - - StatusLoggerEvent.SETTINGS_DISPLAYTYPE_NONEXISTENT.log(getStatusLogger()); - getFileConfiguration().set("display.type", "block"); - getSettings().getFileHandler().save(); - setupDisplay(); - } - - public void setupCrateInventoryName() { - if (hasValue("inventory-name")) { - String invName = getFileConfiguration().getString("inventory-name"); - if (invName.length() < 33) { - getSettings().setCrateInventoryName(invName); - StatusLoggerEvent.SETTINGS_INVENTORYNAME_SUCCESS.log(getStatusLogger()); - return; - } - - getSettings().setCrateInventoryName(invName.substring(0, 33)); - StatusLoggerEvent.SETTINGS_INVENTORYNAME_INVALID.log(getStatusLogger()); - return; - } - StatusLoggerEvent.SETTINGS_INVENTORYNAME_NONEXISTENT.log(getStatusLogger()); - } - - public void setupPermission() { - if (hasValue("permission")) { - getSettings().setPermission(getFileConfiguration().getString("permission")); - StatusLoggerEvent.SETTINGS_PERMISSION_SUCCESS.log(getStatusLogger()); - return; - } - - getSettings().setPermission("no permission"); - } - - public void setupDisplayer() { - if (hasValue("reward-display.type")) { - String displayerString = getFileConfiguration().getString("reward-display.type").toUpperCase(); - - try { - RewardDisplayType rewardDisplayType = RewardDisplayType.valueOf(displayerString); - Crate crate = getSettings().getCrate(); - getSettings().setRewardDisplayType(rewardDisplayType); - - switch (rewardDisplayType) { - case CUSTOM: - getSettings().setDisplayer(new CustomRewardDisplayer(crate)); - break; - case IN_ORDER: - getSettings().setDisplayer(new SimpleRewardDisplayer(crate)); - break; - case SORTED_HIGH_TO_LOW: - getSettings().setDisplayer(new SortedRewardDisplayer(crate, false)); - break; - case SORTED_LOW_TO_HIGH: - getSettings().setDisplayer(new SortedRewardDisplayer(crate, true)); - break; - } - - StatusLoggerEvent.SETTINGS_REWARD_DISPLAYER_SUCCESS.log(getStatusLogger()); - } catch (Exception exc) { - getSettings().setRewardDisplayType(RewardDisplayType.IN_ORDER); - getSettings().setDisplayer(new SimpleRewardDisplayer(getSettings().getCrate())); - StatusLoggerEvent.SETTINGS_REWARD_DISPLAYER_INVALID.log(getStatusLogger(), displayerString); - } - - getSettings().getDisplayer().load(); - - return; - } - - getSettings().setRewardDisplayType(RewardDisplayType.IN_ORDER); - getSettings().setDisplayer(new SimpleRewardDisplayer(getSettings().getCrate())); - //StatusLoggerEvent.SETTINGS_REWARD_DISPLAYER_NONEXISTENT.log(getSl()); - - getSettings().getDisplayer().load(); - - } - - - public StatusLogger getStatusLogger() { - return getSettings().getStatusLogger(); - } - - public CrateSettings getSettings() { - return settings; - } - - public void setSettings(CrateSettings settings) { - this.settings = settings; - } - - public FileConfiguration getFileConfiguration() { - return fileConfiguration; - } - - public void setFileConfiguration(FileConfiguration fileConfiguration) { - this.fileConfiguration = fileConfiguration; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/CrateState.java b/src/main/java/me/ztowne13/customcrates/crates/CrateState.java deleted file mode 100644 index 87e24f8..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/CrateState.java +++ /dev/null @@ -1,9 +0,0 @@ -package me.ztowne13.customcrates.crates; - -public enum CrateState { - PLAY, - - OPEN, - - PRE_OPEN -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/PlacedCrate.java b/src/main/java/me/ztowne13/customcrates/crates/PlacedCrate.java deleted file mode 100644 index 2a1b78d..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/PlacedCrate.java +++ /dev/null @@ -1,192 +0,0 @@ -package me.ztowne13.customcrates.crates; - -import me.ztowne13.customcrates.SettingsValue; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.options.CHologram; -import me.ztowne13.customcrates.crates.options.ObtainType; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.CrateUtils; -import me.ztowne13.customcrates.utils.LocationUtils; -import org.bukkit.Location; - -import java.util.HashMap; -import java.util.Map; - -/** - * Manages individual placed crates. - */ -public class PlacedCrate { - private static Map placedCrates = new HashMap<>(); - - private final SpecializedCrates instance; - private Crate crate; - - private boolean isCratesEnabled; - private boolean deleted = false; - - private CHologram hologram; - - private Location location; - private Long placedTime; - private boolean used = false; - - public PlacedCrate(SpecializedCrates instance, Location location) { - this.instance = instance; - this.location = location; - - getPlacedCrates().put(location, this); - } - - public static boolean crateExistsAt(Location l) { - return getPlacedCrates().containsKey(l.getBlock().getLocation()); - } - - public static PlacedCrate get(SpecializedCrates cc, Location l) { - Location bl; - try { - bl = l.getBlock().getLocation(); - } catch (Exception exc) { - ChatUtils.log("A crate is trying to be placed in an ungenerated chunk or world. Deleting that placed instance."); - return null; - } - - return getPlacedCrates().containsKey(bl) ? getPlacedCrates().get(bl) : new PlacedCrate(cc, l); - } - - public static void clearLoaded() { - getPlacedCrates().clear(); - setPlacedCrates(new HashMap<>()); - } - - public static Map getPlacedCrates() { - return placedCrates; - } - - public static void setPlacedCrates(Map placedCrates) { - PlacedCrate.placedCrates = placedCrates; - } - - public void delete() { - instance.getActiveCratesFile().get().set(LocationUtils.locToString(getLocation()), null); - instance.getActiveCratesFile().save(); - getHologram().getDynamicHologram().delete(); - getCrate().getSettings().getPlaceholder().remove(this); - getPlacedCrates().remove(getLocation()); - deleted = true; - } - - public void writeToFile() { - instance.getActiveCratesFile().get().set(LocationUtils.locToString(getLocation()) + ".crate", getCrate().getName()); - instance.getActiveCratesFile().get().set(LocationUtils.locToString(getLocation()) + ".placedTime", getPlacedTime()); - instance.getActiveCratesFile().save(); - } - - public void rename(String newCrateName) { - instance.getActiveCratesFile().get().set(LocationUtils.locToString(getLocation()) + ".crate", newCrateName); - instance.getActiveCratesFile().save(); - } - - public void setup(Crate crates, boolean writeToFile) { - setup(crates, writeToFile, true); - } - - public void setup(Crate crates, boolean writeToFile, boolean createdByPlayer) { - this.crate = crates; - crates.setPlacedCount(crates.getPlacedCount() + 1); - setCratesEnabled(CrateUtils.isCrateUsable(crates)); - - if (CrateUtils.isCrateUsable(this)) { - setupDisplay(); - setupHolo(crates, createdByPlayer); - - getCrate().getSettings().getPlaceholder().fixHologram(this); - - if (writeToFile) { - setPlacedTime(System.currentTimeMillis()); - writeToFile(); - } - } - } - - public void setupDisplay() { - getCrate().getSettings().getPlaceholder().place(this); - } - - public void setupHolo(Crate crates, boolean createdByPlayer) { - setHologram(crates.getSettings().getHologram().clone()); - if (!createdByPlayer) { - getHologram().setCreatedByPlayer(false); - } - - Location dupeLoc = getLocation().clone(); - dupeLoc.setY(dupeLoc.getY() + .5); - getHologram().setDynamicHologram(getHologram().createHologram(this, dupeLoc)); - } - - public void tick(CrateState cs) { - if (isCratesEnabled()) { - getCrate().tick(getLocation(), cs, null, null); - //getCrates().getCs().getCh().tick(null, getL(), cs, !getCrates().isMultiCrate()); - getHologram().getDynamicHologram().tick(); - } - - if (crate.getSettings().getObtainType().equals(ObtainType.LUCKYCHEST)) { - int num = (int) instance.getSettings().getConfigValues().get(SettingsValue.LUCKYCHEST_DESPAWN.getPath()) * 60; - if (num > 0 && ((System.currentTimeMillis() - getPlacedTime()) / 1000) > num) { - delete(); - } - } - } - - public CHologram getHologram() { - return hologram; - } - - public void setHologram(CHologram hologram) { - this.hologram = hologram; - } - - public Crate getCrate() { - return crate; - } - - public void setCrate(Crate crate) { - this.crate = crate; - } - - public Location getLocation() { - return location; - } - - public void setLocation(Location location) { - this.location = location; - } - - public boolean isUsed() { - return used; - } - - public void setUsed(boolean used) { - this.used = used; - } - - public boolean isCratesEnabled() { - return isCratesEnabled; - } - - public void setCratesEnabled(boolean cratesEnabled) { - isCratesEnabled = cratesEnabled; - } - - public Long getPlacedTime() { - return placedTime; - } - - public void setPlacedTime(Long placedTime) { - this.placedTime = placedTime; - } - - public boolean isDeleted() { - return deleted; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/SettingsConverter.java b/src/main/java/me/ztowne13/customcrates/crates/SettingsConverter.java deleted file mode 100644 index e29914f..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/SettingsConverter.java +++ /dev/null @@ -1,74 +0,0 @@ -package me.ztowne13.customcrates.crates; - -import me.ztowne13.customcrates.interfaces.files.FileHandler; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.configuration.file.FileConfiguration; - -import java.util.List; - -public class SettingsConverter { - private SettingsConverter() { - // EMPTY - } - - public static void convertParticles(FileHandler fileHandler, String path) { - FileConfiguration fc = fileHandler.get(); - boolean isSet = !fc.getStringList(path).isEmpty(); - - if (isSet) { - ChatUtils.log("Converting particles for " + path + "..."); - List list = fc.getStringList(path); - int i = 0; - for (String s : list) { - try { - i++; - String section = i + ""; - - String[] split = s.replace(" ", "").split(","); - String type = split[0].toUpperCase(); - float rangeX = Float.parseFloat(split[1]); - float rangeY = Float.parseFloat(split[2]); - float rangeZ = Float.parseFloat(split[3]); - float speed = Float.parseFloat(split[4]); - int amnt = Integer.parseInt(split[5]); - String animation = "NONE"; - - if (split.length >= 7) - animation = split[6].toUpperCase(); - - //String section = findNextAvailableNumber(fileHandler, path); - - fc.set(path + "." + section + ".type", type); - fc.set(path + "." + section + ".range-x", rangeX); - fc.set(path + "." + section + ".range-y", rangeY); - fc.set(path + "." + section + ".range-z", rangeZ); - fc.set(path + "." + section + ".speed", speed); - fc.set(path + "." + section + ".amount", amnt); - fc.set(path + "." + section + ".animation", animation); - fc.set(path + "." + section + ".center-x", 0); - fc.set(path + "." + section + ".center-y", 0); - fc.set(path + "." + section + ".center-z", 0); - fileHandler.save(); - ChatUtils.log("Success. Converted " + s); - } catch (Exception exc) { - //exc.printStackTrace(); - ChatUtils - .log("FAILED TO CONVERT PARTICLES. This is like due to a misformatted particle that wasn't in use anyways and can be ignored."); - } - } - } - } - -// public static String findNextAvailableNumber(FileHandler fileHandler, String path) -// { -// ConfigurationSection configSec = fileHandler.get().getConfigurationSection(path); -// for(int i = 0; i < 1000; i++) -// { -// if(!configSec.getKeys(false).contains(i + "")) -// { -// return i + ""; -// } -// } -// return null; -// } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/crateaction/AttemptCrateUseAction.java b/src/main/java/me/ztowne13/customcrates/crates/crateaction/AttemptCrateUseAction.java deleted file mode 100644 index 54431a2..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/crateaction/AttemptCrateUseAction.java +++ /dev/null @@ -1,99 +0,0 @@ -package me.ztowne13.customcrates.crates.crateaction; - -import me.ztowne13.customcrates.Messages; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.PlacedCrate; -import me.ztowne13.customcrates.crates.options.ObtainType; -import me.ztowne13.customcrates.players.PlayerManager; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.CrateUtils; -import me.ztowne13.customcrates.utils.Utils; -import org.bukkit.Bukkit; -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.block.BlockFace; -import org.bukkit.entity.Player; - -public class AttemptCrateUseAction extends CrateAction { - protected final boolean isBlockPlace; - - public AttemptCrateUseAction(SpecializedCrates cc, Player player, Location location, boolean isBlockPlace) { - super(cc, player, location); - this.isBlockPlace = isBlockPlace; - } - - @SuppressWarnings("deprecated") - @Override - public boolean run() { - final PlayerManager pm = PlayerManager.get(instance, player); - - // Check item in hand - if (!Utils.hasItemInHand(player)) { - return false; - } - - final Crate crates = CrateUtils.searchByCrate(player.getItemInHand()); - // Check holding crate - if (crates == null) { - if (CrateUtils.searchByCrate(player.getItemInHand(), true) != null && ( - player.hasPermission("customcrates.place.bypass") || player.hasPermission("customcrates.admin") || - player.hasPermission("specializedcrates.place.bypass") || player.hasPermission("specializedcrates.admin") - )) { - ChatUtils.msgError(player, "This crate is disabled either manually or due to an error and cannot be used."); - } - return false; - } - - if (!location.getBlock().getRelative(BlockFace.UP).getType().equals(Material.AIR)) { - Messages.DENIED_PLACE_LOCATION.msgSpecified(instance, player); - return true; - } - - // Check crate usable - if (!CrateUtils.isCrateUsable(crates)) { - Messages.CRATE_DISABLED.msgSpecified(instance, player); - if (player.hasPermission("customcrates.admin") || player.hasPermission("specializedcrates.admin") || player.isOp()) { - Messages.CRATE_DISABLED_ADMIN.msgSpecified(instance, player); - } - return false; - } - - ObtainType ot = crates.getSettings().getObtainType(); - boolean bypass = false; - - // The crate is a static crate - if (ot.equals(ObtainType.STATIC)) { - if (player.hasPermission("customcrates.place.bypass") || player.hasPermission("customcrates.admin") || - player.hasPermission("specializedcrates.place.bypass") || player.hasPermission("specializedcrates.admin")) { - Messages.BYPASS_BREAK_RESTRICTIONS.msgSpecified(instance, player); - bypass = true; - } else { - Messages.DENIED_USE_CRATE.msgSpecified(instance, player); - return true; - } - } - - // Check if a crate already exists - if (PlacedCrate.crateExistsAt(location)) { - ChatUtils.msgError(player, "There is, somehow, already a crate placed here."); - return bypass; - } - - // Check Creative rules - if (player.getGameMode().equals(GameMode.CREATIVE) && instance.getSettings().getConfigValues().get("place-creative").equals(Boolean.FALSE)) { - crates.getSettings().getCrateAnimation().playFailToOpen(player, false, true); - Messages.DENY_CREATIVE_MODE.msgSpecified(instance, player); - return true; - } - - final PlacedCrate placedCrate = createCrateAt(crates, location); - // For DYNAMIC crates that don't require a key, open immediately. - if (crates.getSettings().getObtainType().equals(ObtainType.DYNAMIC) && !crates.getSettings().isRequireKey()) { - Bukkit.getScheduler().runTaskLater(instance, () -> useCrate(pm, placedCrate, false), 1); - } - - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/crateaction/AttemptKeyUseAction.java b/src/main/java/me/ztowne13/customcrates/crates/crateaction/AttemptKeyUseAction.java deleted file mode 100644 index a7b58c1..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/crateaction/AttemptKeyUseAction.java +++ /dev/null @@ -1,68 +0,0 @@ -package me.ztowne13.customcrates.crates.crateaction; - -import me.ztowne13.customcrates.Messages; -import me.ztowne13.customcrates.SettingsValue; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.PlacedCrate; -import me.ztowne13.customcrates.players.PlayerManager; -import me.ztowne13.customcrates.utils.CrateUtils; -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -public class AttemptKeyUseAction extends CrateAction { - public AttemptKeyUseAction(SpecializedCrates cc, Player player, Location location) { - super(cc, player, location); - } - - @Override - public boolean run() { - PlayerManager pm = PlayerManager.get(instance, player); - - if (!PlacedCrate.crateExistsAt(location)) { - return false; - } - - long curTime = System.currentTimeMillis(); - if (curTime - pm.getLastClickedCrateTime() < 500) { - return true; - } - pm.setLastClickedCrateTime(System.currentTimeMillis()); - - // For SQL, to make sure the player data is loaded - if (!pm.getPlayerDataManager().isLoaded()) { - Messages.LOADING_FROM_DATABASE.msgSpecified(instance, player); - return true; - } - - PlacedCrate cm = PlacedCrate.get(instance, location); - Crate crate = cm.getCrate(); - - if (crate.isMultiCrate() && !CrateUtils.isCrateUsable(cm)) { - Messages.CRATE_DISABLED.msgSpecified(instance, player); - if (player.hasPermission("customcrates.admin") || player.isOp()) { - Messages.CRATE_DISABLED_ADMIN.msgSpecified(instance, player); - } - return true; - } - - Crate crates = cm.getCrate(); - - if (crates.isMultiCrate()) { - if (pm.isInCrate()) { - return true; - } - - crate.getSettings().getMultiCrateSettings().openFor(player, cm); - return true; - } else if (!player.getGameMode().equals(GameMode.CREATIVE) || instance.getSettings().getConfigValues().get("open-creative").equals(Boolean.TRUE)) { - useCrate(pm, cm, player.isSneaking() && (Boolean) SettingsValue.SHIFT_CLICK_OPEN_ALL.getValue(instance)); - return true; - } else { - crate.getSettings().getCrateAnimation().playFailToOpen(player, false, true); - Messages.DENY_CREATIVE_MODE.msgSpecified(instance, player); - return true; - } - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/crateaction/CrateAction.java b/src/main/java/me/ztowne13/customcrates/crates/crateaction/CrateAction.java deleted file mode 100644 index 8cf161f..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/crateaction/CrateAction.java +++ /dev/null @@ -1,190 +0,0 @@ -package me.ztowne13.customcrates.crates.crateaction; - -import me.ztowne13.customcrates.Messages; -import me.ztowne13.customcrates.SettingsValue; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.api.CrateOpenEvent; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.CrateSettings; -import me.ztowne13.customcrates.crates.CrateState; -import me.ztowne13.customcrates.crates.PlacedCrate; -import me.ztowne13.customcrates.crates.options.ObtainType; -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import me.ztowne13.customcrates.players.PlayerDataManager; -import me.ztowne13.customcrates.players.PlayerManager; -import me.ztowne13.customcrates.players.data.events.CrateCooldownEvent; -import me.ztowne13.customcrates.players.data.events.HistoryEvent; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.Utils; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.entity.Player; - -import java.util.ArrayList; - -public abstract class CrateAction { - - protected final SpecializedCrates instance; - protected final Player player; - protected final Location location; - - public CrateAction(SpecializedCrates instance, Player player, Location location) { - this.instance = instance; - this.player = player; - this.location = location; - } - - public static boolean isInventoryTooEmpty(SpecializedCrates instance, Player player) { - return Utils.getOpenInventorySlots(player) >= ((Integer) SettingsValue.REQUIRED_SLOTS.getValue(instance)); - } - - public abstract boolean run(); - - public boolean useCrate(PlayerManager playerManager, PlacedCrate placedCrate, boolean skipAnimation) { - return useCrate(playerManager, placedCrate, skipAnimation, false); - } - - public boolean useCrateHelper(PlayerManager playerManager, PlacedCrate placedCrate, int opened) { - if (opened < 300 && !useCrate(playerManager, placedCrate, true, true, opened)) { - CrateOpenEvent crateOpenEvent = new CrateOpenEvent(player, null, placedCrate.getCrate(), opened); - Bukkit.getPluginManager().callEvent(crateOpenEvent); - return false; - } - return true; - } - - public boolean useCrate(PlayerManager playerManager, PlacedCrate placedCrate, boolean skipAnimation, boolean hasSkipped) { - return useCrate(playerManager, placedCrate, skipAnimation, hasSkipped, 0); - } - - public boolean useCrate(PlayerManager playerManager, PlacedCrate placedCrate, boolean skipAnimation, boolean hasSkipped, int opened) { - Player p = playerManager.getPlayer(); - PlayerDataManager playerDataManager = playerManager.getPlayerDataManager(); - Crate crate = placedCrate.getCrate(); - CrateSettings crateSettings = crate.getSettings(); - Location placedCrateLocation = placedCrate.getLocation(); - - if (crate.isNeedsReload()) { - ChatUtils.msgInfo(p, - "Hey! It looks like you just created a new crate." + - " Whenever you edit something in the in-game config," + - " make sure to click the green '&asave&e' and pink '&dreload&e' button before testing it out!" + - " This crate won't work until saved and reloaded! Try &b/scrates edit " + crate.getName() + " &eto" + - " open up the menu where you can &asave &eand &dreload ðe crate."); - return true; - } - - // Check permissions - if (!p.hasPermission(crateSettings.getPermission()) && !crateSettings.getPermission().equalsIgnoreCase("no permission")) { - Messages.NO_PERMISSION_CRATE.msgSpecified(instance, p); - crate.getSettings().getCrateAnimation().playFailToOpen(p, false, true); - return false; - } - - // Check inventory spaces (defined by value in Config.YML) - if (!isInventoryTooEmpty(instance, p)) { - Messages.INVENTORY_TOO_FULL.msgSpecified(instance, p); - crate.getSettings().getCrateAnimation().playFailToOpen(p, false, true); - return false; - } - // Check cooldown - CrateCooldownEvent cce = playerDataManager.getCrateCooldownEventByCrates(crate); - if (cce != null && !cce.isCooldownOverAsBoolean()) { - cce.playFailure(playerDataManager); - return false; - } - - playerManager.setLastOpenedPlacedCrate(placedCrate); - - // SHIFT-CLICK OPEN - // If the animation needs to be skipped (shift click). Also required to be a static crate - if (skipAnimation && crateSettings.getObtainType().equals(ObtainType.STATIC)) { - if (!playerManager.isConfirming() && SettingsValue.SHIFT_CLICK_CONFIRM.getValue(instance).equals(Boolean.TRUE)) { - playerManager.setConfirming(true); - Messages.CONFIRM_OPEN_ALL.msgSpecified(instance, p, new String[]{"%timeout%"}, new String[]{ - SettingsValue.CONFIRM_TIMEOUT.getValue(instance) + ""}); - return false; - } - - if (!crateSettings.getCrateAnimation().canExecuteFor(p, !crate.isMultiCrate())) { - if (!hasSkipped) - crate.getSettings().getCrateAnimation().playFailToOpen(p, true, true); - return false; - } - - if (!instance.getEconomyHandler().handleCheck(p, crate.getSettings().getCost(), true)) { - return false; - } - - Reward reward = crateSettings.getReward().getRandomReward(); - ArrayList rewards = new ArrayList<>(); - rewards.add(reward); - reward.giveRewardToPlayer(p); - - crateSettings.getKeyItemHandler().takeKeyFromPlayer(p, false); - new HistoryEvent(Utils.currentTimeParsed(), crate, rewards, true) - .addTo(PlayerManager.get(instance, p).getPlayerDataManager()); - new CrateCooldownEvent(crate, System.currentTimeMillis(), true).addTo(playerDataManager); - - useCrateHelper(playerManager, placedCrate, opened + 1); - - if (!hasSkipped) { - crate.tick(placedCrateLocation, placedCrate, CrateState.OPEN, p, new ArrayList<>()); - playerManager.setConfirming(false); - } - return true; - } - - // NORMAL OPEN - if (!playerManager.isConfirming() && SettingsValue.CONFIRM_OPEN.getValue(instance).equals(Boolean.TRUE)) { - playerManager.setConfirming(true); - Messages.CONFIRM_OPEN.msgSpecified(instance, p, new String[]{"%timeout%"}, new String[]{ - SettingsValue.CONFIRM_TIMEOUT.getValue(instance) + ""}); - return false; - } - - if (!instance.getEconomyHandler().handleCheck(p, crateSettings.getCost(), true)) { - crateSettings.getCrateAnimation().playFailToOpen(p, false, true); - return false; - } - - if (!crateSettings.getCrateAnimation().startAnimation(p, placedCrateLocation, !crate.isMultiCrate(), false)) { - instance.getEconomyHandler().failSoReturn(p, crateSettings.getCost()); - playerManager.setLastOpenedPlacedCrate(null); - return false; - } - - // Crate isn't static but it ALSO isn't special handling (i.e. the BLOCK_ CrateTypes) - if (!crateSettings.getObtainType().equals(ObtainType.STATIC) && !crateSettings.getCrateType().isSpecialDynamicHandling()) { - placedCrate.delete(); - placedCrateLocation.getBlock().setType(Material.AIR); - } - new CrateCooldownEvent(crate, System.currentTimeMillis(), true).addTo(playerDataManager); - return !skipAnimation; - } - - public boolean updateCooldown(PlayerManager pm) { - - boolean b = false; - - long ct = System.currentTimeMillis(); - long diff = ct - pm.getCmdCooldown(); - - if (diff < 1000 && !pm.getLastCooldown().equalsIgnoreCase("crate")) { - Messages.WAIT_ONE_SECOND.msgSpecified(instance, pm.getPlayer()); - - b = true; - } - pm.setLastCooldown("crate"); - pm.setCmdCooldown(ct); - return b; - } - - public PlacedCrate createCrateAt(Crate crates, Location l) { - PlacedCrate cm = PlacedCrate.get(instance, l); - cm.setup(crates, true); - - return cm; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/crateaction/LeftClickAction.java b/src/main/java/me/ztowne13/customcrates/crates/crateaction/LeftClickAction.java deleted file mode 100644 index 39e3752..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/crateaction/LeftClickAction.java +++ /dev/null @@ -1,57 +0,0 @@ -package me.ztowne13.customcrates.crates.crateaction; - -import me.ztowne13.customcrates.Messages; -import me.ztowne13.customcrates.SettingsValue; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.PlacedCrate; -import me.ztowne13.customcrates.players.PlayerManager; -import me.ztowne13.customcrates.utils.CrateUtils; -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -public class LeftClickAction extends CrateAction { - public LeftClickAction(SpecializedCrates cc, Player player, Location location) { - super(cc, player, location); - } - - @Override - public boolean run() { - if (!PlacedCrate.crateExistsAt(location)) { - return false; - } - - PlayerManager playerManager = PlayerManager.get(instance, player); - PlacedCrate placedCrate = PlacedCrate.get(instance, location); - - // Code for deleting crates using command or the shift + click shortcut - if (playerManager.isDeleteCrate() || - (player.isSneaking() && (player.hasPermission("customcrates.admin") || - player.hasPermission("specializedcrates.admin")) && - player.getGameMode().equals(GameMode.CREATIVE))) { - placedCrate.delete(); - playerManager.setDeleteCrate(false); - Messages.SUCCESS_DELETE - .msgSpecified(instance, player, new String[]{"%crate%"}, new String[]{placedCrate.getCrate().getName()}); - return true; - } - - // Preventing crates from being broken and displaying reward menu if need be - if (!CrateUtils.isCrateUsable(placedCrate)) { - Messages.CRATE_DISABLED.msgSpecified(instance, player); - if (player.hasPermission("customcrates.admin") || player.hasPermission("specializedcrates.admin") || - player.isOp()) { - Messages.CRATE_DISABLED_ADMIN.msgSpecified(instance, player); - } - return true; - } - - if (!playerManager.isDeleteCrate() && SettingsValue.REWARD_DISPLAY_ENABLED.getValue(instance).equals(Boolean.TRUE)) { - if (!placedCrate.getCrate().isMultiCrate()) - placedCrate.getCrate().getSettings().getDisplayer().openFor(player); - return true; - } - - return true; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/CAction.java b/src/main/java/me/ztowne13/customcrates/crates/options/CAction.java deleted file mode 100644 index a9b97d3..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/CAction.java +++ /dev/null @@ -1,312 +0,0 @@ -package me.ztowne13.customcrates.crates.options; - -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.CrateSettingsBuilder; -import me.ztowne13.customcrates.crates.CrateState; -import me.ztowne13.customcrates.crates.PlacedCrate; -import me.ztowne13.customcrates.crates.options.actions.ActionEffect; -import me.ztowne13.customcrates.crates.options.actions.BukkitActionEffect; -import me.ztowne13.customcrates.crates.options.actions.NMSActionEffect; -import me.ztowne13.customcrates.crates.options.holograms.DynamicHologram; -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import me.ztowne13.customcrates.crates.types.animations.CrateAnimationType; -import me.ztowne13.customcrates.crates.types.animations.block.OpenChestAnimation; -import me.ztowne13.customcrates.interfaces.logging.StatusLoggerEvent; -import me.ztowne13.customcrates.players.PlayerManager; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.VersionUtils; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Item; -import org.bukkit.entity.Player; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class CAction extends CSetting { - private Map>> actions = new HashMap<>(); - - public CAction(Crate crate) { - super(crate, crate.getInstance()); - } - - @Override - public void loadFor(CrateSettingsBuilder crateSettingsBuilder, CrateState crateState) { - if (crateSettingsBuilder.hasValue("open.actions")) { - List list = getCrate().getSettings().getFileConfiguration().getStringList("open.actions"); - for (String s : list) { - addEntryByString("DEFAULT", s); - } - } - - if (crateSettingsBuilder.hasValue("open.crate-tiers")) { - for (String tier : getCrate().getSettings().getFileConfiguration().getConfigurationSection("open.crate-tiers").getKeys(false)) { - if (crateSettingsBuilder.hasValue("open.crate-tiers." + tier + ".actions")) { - List list = - getCrate().getSettings().getFileConfiguration().getStringList("open.crate-tiers." + tier + ".actions"); - for (String s : list) { - addEntryByString(tier, s); - } - } - } - } - } - - public void saveToFile() { - if (!actions.isEmpty()) { - for (Map.Entry>> entry : actions.entrySet()) { - ArrayList toSetList = new ArrayList<>(); - String tier = entry.getKey(); - String path = "open." + (tier.equalsIgnoreCase("DEFAULT") ? "" : "crate-tiers." + tier + ".") + "actions"; - - for (Map.Entry> entry1 : entry.getValue().entrySet()) { - String actionType = entry1.getKey(); - for (String action : entry1.getValue()) { - toSetList.add(ChatUtils.fromChatColor(actionType + ", " + action)); - } - } - - getFileHandler().get().set(path, toSetList); - } - } - } - - public void addEntry(String type, String action, String tier) { - Map> map = getActions().getOrDefault(tier, new HashMap<>()); - - List list = map.getOrDefault(type, new ArrayList<>()); - list.add(action); - map.put(type, list); - - StatusLoggerEvent.ACTION_ADD.log(getCrate(), action, tier); - getActions().put(tier, map); - } - - public void removeEntry(String type, String action, String tier) { - getActions().get(tier).get(type).remove(action); - } - - public void addEntryByString(String crateTier, String toAdd) { - String[] split = toAdd.split(","); - String type = split[0].replace(" ", "").replace(",", ""); - - if (split.length == 1) { - addEntry(type, "", crateTier); - return; - } - - String action = ""; - - boolean b = false; - for (String words : split) { - if (b) - action = words + " "; - b = true; - } - - if (action.startsWith(" ")) - action = action.substring(1); - - action = action.substring(0, action.length() - 1); - action = ChatUtils.toChatColor(action); - - addEntry(type, action, crateTier); - } - - public void playAll(Player player, boolean pre) { - playAll(player, new ArrayList<>(), pre); - } - - public void playAll(Player player, List rewards, boolean pre) { - playAll(player, null, rewards, pre); - } - - public void playAll(Player player, PlacedCrate placedCrate, List rewards, boolean pre) { - instance.getDebugUtils().log("playAll() - CALL (pre: " + pre + ")", getClass()); - - if (rewards.isEmpty() && !pre) - return; - - ActionEffect actionEffect = - VersionUtils.Version.v1_12.isServerVersionOrLater() ? new BukkitActionEffect(instance) : new NMSActionEffect(instance); - actionEffect.newTitle(); - boolean toRunTitle = false; - - ArrayList rewardsAsDisplayname = new ArrayList<>(); - for (Reward r : rewards) { - rewardsAsDisplayname.add(r.getDisplayName(true)); - } - - for (String tier : getActions().keySet()) { - if (pre || (tier.equalsIgnoreCase("DEFAULT") && - !getActions().containsKey(rewards.get(0).getRarity().toLowerCase())) || - rewards.get(0).getRarity().equalsIgnoreCase(tier)) { - for (String actionVal : getActions().get(tier).keySet()) { - String s = actionVal.toUpperCase(); - for (String msg : getActions().get(tier).get(s)) { - if (pre) { - if (actionVal.startsWith("PRE_")) { - s = actionVal.substring(4); - } else { - continue; - } - } else { - if (actionVal.startsWith("PRE_")) { - continue; - } - } - - String rewardsAsString = rewardsAsDisplayname.toString(); - rewardsAsString = rewardsAsString.substring(1, rewardsAsString.length() - 1); - - msg = msg.replace("%player%", player.getName()).replace("%name%", player.getName()); - msg = msg.replace("%displayname%", player.getDisplayName()).replace("%nickname%", player.getDisplayName()) - .replace("%nick%", player.getDisplayName()); - msg = msg.replace("%crate%", getCrate().getName()).replace("%cratename%", getCrate().getDisplayName()); - msg = msg.replace("%reward%", rewardsAsString).replace("%rewards%", rewardsAsString); - msg = ChatUtils.toChatColor(msg); - - if (s.equalsIgnoreCase("MESSAGE")) { - player.sendMessage(msg); - } else if (s.equalsIgnoreCase("BROADCAST")) { - for (Player onlinePlayer : Bukkit.getOnlinePlayers()) { - onlinePlayer.sendMessage(msg); - } - } else if (s.equalsIgnoreCase("ACTIONBAR")) { - actionEffect.getActionBarExecutor().play(player, msg); - } else if (s.equalsIgnoreCase("TITLE")) { - actionEffect.setDisplayTitle(msg); - toRunTitle = true; - } else if (s.equalsIgnoreCase("SUBTITLE")) { - actionEffect.setDisplaySubtitle(msg); - toRunTitle = true; - } else if (s.equalsIgnoreCase("COMMAND")) { - Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), msg); - } else { - ChatUtils.log(new String[]{ - "Please note that an action type called " + s + " was attempted to be run", - " However, this action type does not exist. Valid types are:", - " MESSAGE, BROADCAST, ACTIONBAR, TITLE, SUBTITLE, and COMMAND"}); - } - } - } - } - } - - if (toRunTitle) { - actionEffect.playTitle(player); - } - - if (!pre) { - if (!crate.getSettings().getCrateType().equals(CrateAnimationType.BLOCK_CRATEOPEN) || - !((OpenChestAnimation) crate.getSettings().getCrateAnimation()).isEarlyRewardHologram()) { - if (crate.getSettings().getObtainType().isStatic() || - crate.getSettings().getCrateType().isSpecialDynamicHandling()) - playRewardHologram(player, rewardsAsDisplayname); - } - } - } - - public void playRewardHologram(Player player, List rewards, double additionalYOffset) { - playRewardHologram(player, rewards, additionalYOffset, false, null, -1); - } - - public void playRewardHologram(Player player, List rewards) { - playRewardHologram(player, rewards, 0, false, null, -1); - } - - public void playRewardHologram(Player player, List rewards, double additionalYOffset, boolean attach, Item item, - int openDuration) { - if (rewards.isEmpty()) - return; - - final PlayerManager playerManager = PlayerManager.get(instance, player); - final PlacedCrate placedCrate = playerManager.getLastOpenedPlacedCrate(); - if (placedCrate == null) { - return; - } - - String msg = placedCrate.getCrate().getSettings().getHologram().getRewardHologram(); - if (msg.isEmpty()) { - return; - } - - String rewardsAsString = rewards.toString().substring(1, rewards.toString().length() - 1); - msg = msg.replace("%player%", player.getName()).replace("%name%", player.getName()); - msg = msg.replace("%displayname%", player.getDisplayName()).replace("%nickname%", player.getDisplayName()) - .replace("%nick%", player.getDisplayName()); - msg = msg.replace("%crate%", getCrate().getName()).replace("%cratename%", getCrate().getDisplayName()); - msg = msg.replace("%reward%", rewardsAsString).replace("%rewards%", rewardsAsString); - - msg = ChatUtils.toChatColor(msg); - - final DynamicHologram dynamicHologram = placedCrate.getHologram().getDynamicHologram(); - dynamicHologram.setDisplayingRewardHologram(true); - dynamicHologram.delete(); - - Location rewardLoc = placedCrate.getLocation().clone(); - rewardLoc.setY(rewardLoc.getY() - .3 + getCrate().getSettings().getHologram().getRewardHoloYOffset() + - additionalYOffset); - dynamicHologram.create(rewardLoc); - dynamicHologram.addLine(msg); - - if (attach) { - attachTo(item, msg); - } - - Bukkit.getScheduler().scheduleSyncDelayedTask(instance, () -> { - dynamicHologram.delete(); - - final Location cloneY = placedCrate.getLocation().clone(); - cloneY.setY(cloneY.getY() + .5); - - if (placedCrate.getCrate().getSettings().getObtainType().equals(ObtainType.STATIC)) { - placedCrate.getCrate().getSettings().getHologram().createHologram(cloneY, dynamicHologram); - } - - playerManager.setLastOpenedPlacedCrate(null); - dynamicHologram.setDisplayingRewardHologram(false); - - if (dynamicHologram.getHoloAnimation() != null) { - dynamicHologram.getHoloAnimation().update(true); - } - - }, attach ? openDuration : getCrate().getSettings().getHologram().getRewardHoloDuration()); - } - - public void attachTo(Item item, String rewardName) { - Entity real = null; - - for (Entity entity : item.getLocation().getChunk().getEntities()) { - if (item.getLocation().distance(entity.getLocation()) < 2 && - ChatUtils.removeColor(rewardName).equalsIgnoreCase(ChatUtils.removeColor(entity.getName())) && - !entity.equals(item)) { - real = entity; - break; - } - } - - try { - if (real != null) { - if (VersionUtils.Version.v1_13.isServerVersionOrLater()) - item.addPassenger(real); - else - item.setPassenger(real); - } - } catch (Exception exc) { - exc.printStackTrace(); - } - - } - - public Map>> getActions() { - return actions; - } - - public void setActions(Map>> actions) { - this.actions = actions; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/CFirework.java b/src/main/java/me/ztowne13/customcrates/crates/options/CFirework.java deleted file mode 100644 index 63f214a..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/CFirework.java +++ /dev/null @@ -1,116 +0,0 @@ -package me.ztowne13.customcrates.crates.options; - -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.CrateSettingsBuilder; -import me.ztowne13.customcrates.crates.CrateState; -import me.ztowne13.customcrates.crates.options.particles.FireworkData; -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.interfaces.logging.StatusLoggerEvent; -import me.ztowne13.customcrates.utils.LocationUtils; -import org.bukkit.Location; -import org.bukkit.inventory.ItemStack; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class CFirework extends CSetting { - private Map> fireworks = new HashMap<>(); - - public CFirework(Crate crate) { - super(crate, crate.getInstance()); - } - - @Override - public void loadFor(CrateSettingsBuilder crateSettingsBuilder, CrateState crateState) { - if (crateSettingsBuilder.hasValue("open.fireworks")) { - addFireworks("OPEN", crateSettingsBuilder.getSettings().getFileConfiguration().getStringList("open.fireworks")); - } - if (crateSettingsBuilder.hasValue("open.crate-tiers")) { - for (String id : getSettings().getFileConfiguration().getConfigurationSection("open.crate-tiers").getKeys(false)) { - if (crateSettingsBuilder.hasValue("open.crate-tiers." + id + ".fireworks")) { - addFireworks(id, getSettings().getFileConfiguration().getStringList("open.crate-tiers." + id + ".fireworks")); - } - } - } - } - - public void saveToFile() { - if (!fireworks.isEmpty()) { - for (Map.Entry> entry : fireworks.entrySet()) { - String tier = entry.getKey(); - ArrayList toSetList = new ArrayList<>(); - for (FireworkData fd : entry.getValue()) { - toSetList.add(fd.toString()); - } - - String path = "open." + (tier.equalsIgnoreCase("OPEN") ? "" : "crate-tiers." + tier + ".") + ".fireworks"; - getFileHandler().get().set(path, toSetList); - } - } - } - - public void addFireworks(String id, List list) { - for (String firework : list) { - FireworkData fd = new FireworkData(instance, getSettings()); - fd.load(firework); - addFirework(id, fd); - } - } - - public void removeFireworks(String tier, FireworkData fd) { - getFireworks().get(tier).remove(fd); - } - - public FireworkData getByItemStack(String tier, ItemStack stack) { - ItemBuilder ib = new ItemBuilder(stack); - - String lastLine = ""; - for (String line : ib.getItemMeta().getLore()) - lastLine = line; - - for (FireworkData fd : getFireworks().get(tier)) { - if (fd.getId().equalsIgnoreCase(lastLine)) { - return fd; - } - } - return null; - } - - public void addFirework(String id, FireworkData s) { - if (getFireworks().containsKey(id)) { - List list = getFireworks().get(id); - list.add(s); - getFireworks().put(id, list); - return; - } - - ArrayList list = new ArrayList<>(); - list.add(s); - - StatusLoggerEvent.FIREWORK_ADD.log(getCrate(), s.getFeType().name(), id); - getFireworks().put(id, list); - } - - public void runAll(Location location, List rewards) { - for (String tier : getFireworks().keySet()) { - if ((tier.equalsIgnoreCase("OPEN") && (!getSettings().isTiersOverrideDefaults() || rewards.isEmpty() || - !getFireworks().containsKey(rewards.get(0).getRarity().toUpperCase()))) || - (!rewards.isEmpty() && rewards.get(0).getRarity().equalsIgnoreCase(tier))) { - for (FireworkData fd : getFireworks().get(tier)) { - fd.play(LocationUtils.getLocationCentered(location)); - } - } - } - } - - public Map> getFireworks() { - return fireworks; - } - - public void setFireworks(Map> fireworks) { - this.fireworks = fireworks; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/CHologram.java b/src/main/java/me/ztowne13/customcrates/crates/options/CHologram.java deleted file mode 100644 index 94a2c4a..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/CHologram.java +++ /dev/null @@ -1,287 +0,0 @@ -package me.ztowne13.customcrates.crates.options; - -import me.ztowne13.customcrates.crates.*; -import me.ztowne13.customcrates.crates.options.holograms.DynamicHologram; -import me.ztowne13.customcrates.crates.options.holograms.animations.HoloAnimType; -import me.ztowne13.customcrates.interfaces.logging.StatusLoggerEvent; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.Location; -import org.bukkit.configuration.file.FileConfiguration; - -import java.util.ArrayList; -import java.util.List; - -public class CHologram extends CSetting { - private DynamicHologram dynamicHologram = null; - private List lines = new ArrayList<>(); - private int lineCount = 0; - - private String rewardHologram = ""; - private int rewardHoloDuration = 60; - private double rewardHoloYOffset = 0; - - private HoloAnimType holoAnimType = HoloAnimType.NONE; - private int speed = 20; - private List prefixes = new ArrayList<>(); - private double hologramOffset = -123.123; - - private boolean createdByPlayer = true; - - public CHologram(Crate crate) { - super(crate, crate.getInstance()); - } - - public static void deleteAll() { - for (PlacedCrate placedCrate : PlacedCrate.getPlacedCrates().values()) { - if (placedCrate.getHologram() != null) { - placedCrate.getHologram().getDynamicHologram().delete(); - } - } - - } - - public void loadFor(CrateSettingsBuilder crateSettingsBuilder, CrateState crateState) { - FileConfiguration fc = getCrate().getSettings().getFileConfiguration(); - - if (crateSettingsBuilder.hasValue("hologram.reward-hologram")) { - rewardHologram = fc.getString("hologram.reward-hologram"); - StatusLoggerEvent.HOLOGRAM_REWARD_HOLOGRAM.log(getCrate(), rewardHologram); - } - - if (crateSettingsBuilder.hasValue("hologram.reward-hologram-duration")) { - try { - rewardHoloDuration = Integer.parseInt(fc.getString("hologram.reward-hologram-duration")); - StatusLoggerEvent.HOLOGRAM_REWARD_HOLOGRAM_DURATION_SUCCESS.log(getCrate()); - } catch (Exception exc) { - StatusLoggerEvent.HOLOGRAM_REWARD_HOLOGRAM_DURATION_INVALID.log(getCrate()); - } - } - - if (crateSettingsBuilder.hasValue("hologram.reward-hologram-yoffset")) { - try { - rewardHoloYOffset = Double.parseDouble(fc.getString("hologram.reward-hologram-yoffset")); - StatusLoggerEvent.HOLOGRAM_REWARD_HOLOGRAM_YOFFSET_SUCCESS.log(getCrate()); - } catch (Exception exc) { - StatusLoggerEvent.HOLOGRAM_REWARD_HOLOGRAM_YOFFSET_INVALID.log(getCrate()); - } - } - - if (crateSettingsBuilder.hasValue("hologram.lines")) { - for (String s : fc.getStringList("hologram.lines")) { - setLineCount(getLineCount() + 1); - addLine(s); - } - } - - if (crateSettingsBuilder.hasValue("hologram.animation")) { - try { - HoloAnimType hat = HoloAnimType.valueOf(fc.getString("hologram.animation.type").toUpperCase()); - setHoloAnimType(hat); - } catch (Exception exc) { - if (!crateSettingsBuilder.hasValue("hologram.animation.type")) { - StatusLoggerEvent.HOLOGRAM_ANIMATION_TYPE_FAILURE_NONEXISTENT.log(getCrate()); - } else { - StatusLoggerEvent.HOLOGRAM_ANIMATION_TYPE_FAILURE_INVALID - .log(getCrate(), fc.getString("hologram.animation.type")); - } - return; - } - - try { - setSpeed(fc.getInt("hologram.animation.speed")); - } catch (Exception exc) { - setSpeed(10); - if (!crateSettingsBuilder.hasValue("hologram.animation.speed")) { - StatusLoggerEvent.HOLOGRAM_ANIMATION_SPEED_FAILURE_NONEXISTENT.log(getCrate()); - } else { - StatusLoggerEvent.HOLOGRAM_ANIMATION_SPEED_FAILURE_INVALID - .log(getCrate(), fc.getString("hologram.animation.speed")); - } - return; - } - - try { - for (String s : fc.getStringList("hologram.animation.prefixes")) { - getPrefixes().add(s); - } - } catch (Exception exc) { - setHoloAnimType(null); - StatusLoggerEvent.HOLOGRAM_ANIMATION_PREFIXES_DISABLED.log(getCrate()); - if (!crateSettingsBuilder.hasValue("hologram.animation.prefixes")) { - StatusLoggerEvent.HOLOGRAM_ANIMATION_PREFIXES_NONEXISTENT.log(getCrate()); - } else { - StatusLoggerEvent.HOLOGRAM_ANIMATION_PREFIXES_MISFORMATTED.log(getCrate()); - } - } - } - } - - public void saveToFile() { - for (int i = 0; i < lines.size(); i++) { - try { - lines.set(i, ChatUtils.fromChatColor(lines.get(i))); - } catch (Exception exc) { - // IGNORED - } - } - getFileHandler().get().set("hologram.lines", lines); - - for (int i = 0; i < prefixes.size(); i++) { - try { - prefixes.set(i, ChatUtils.fromChatColor(prefixes.get(i))); - } catch (Exception exc) { - // IGNORED - } - } - getFileHandler().get().set("hologram.animation.prefixes", prefixes); - getFileHandler().get().set("hologram.animation.type", getHoloAnimType().name()); - getFileHandler().get().set("hologram.animation.speed", getSpeed()); - - getFileHandler().get().set("hologram.reward-hologram", getRewardHologram()); - getFileHandler().get().set("hologram.reward-hologram-duration", getRewardHoloDuration()); - getFileHandler().get().set("hologram.reward-hologram-yoffset", getRewardHoloYOffset()); - } - - public double getHologramOffset() { - if (hologramOffset == -123.123) { - try { - hologramOffset = Double.parseDouble(instance.getSettings().getConfigValues().get("hologram-offset").toString()); - } catch (Exception exc) { - ChatUtils.log("hologram-offset in the config.yml file is not a valid double (number) value."); - hologramOffset = 0; - } - } - return hologramOffset + getCrate().getSettings().getHologramOffset(); - } - - public CHologram clone() { - CHologram ch = new CHologram(getCrate()); - ch.setLineCount(getLineCount()); - ch.setLines(getLines()); - ch.setHoloAnimType(getHoloAnimType()); - ch.setColors(getPrefixes()); - ch.setSpeed(getSpeed()); - return ch; - } - - public void addLine(String line) { - try { - lines.add(line); - } catch (Exception exc) { - StatusLoggerEvent.HOLOGRAM_ADDLINE_FAIL_TOMANY - .log(getCrate(), line, (getLines().size() + 1) + ""); - } - } - - public void removeLine(int lineNum) { - lines.remove(lineNum - 1); - } - - public DynamicHologram createHologram(Location location, DynamicHologram dynamicHologram) { - dynamicHologram.create(location); - - CrateSettings settings = getCrate().getSettings(); - // This is a dynamic hologram and doesn't need them created when placed - if (settings.getObtainType().equals(ObtainType.DYNAMIC) && !settings.isRequireKey() && createdByPlayer) { - return dynamicHologram; - } - - if (!lines.isEmpty()) { - for (String s : getLines()) { - try { - s = ChatUtils.toChatColor(s); - dynamicHologram.addLine(s); - } catch (Exception exc) { - break; - } - } - - dynamicHologram.teleport(location); - } - return dynamicHologram; - } - - public DynamicHologram createHologram(PlacedCrate placedCrate, Location location) { - return createHologram(location, getLoadedInstance(placedCrate)); - } - - public DynamicHologram getLoadedInstance(PlacedCrate placedCrate) { - return new DynamicHologram(instance, placedCrate); - } - - public List getLines() { - return lines; - } - - public void setLines(List lines) { - this.lines = lines; - } - - public int getRewardHoloDuration() { - return rewardHoloDuration; - } - - public void setRewardHoloDuration(int rewardHoloDuration) { - this.rewardHoloDuration = rewardHoloDuration; - } - - public double getRewardHoloYOffset() { - return rewardHoloYOffset; - } - - public void setRewardHoloYOffset(double rewardHoloYOffset) { - this.rewardHoloYOffset = rewardHoloYOffset; - } - - public HoloAnimType getHoloAnimType() { - return holoAnimType; - } - - public void setHoloAnimType(HoloAnimType holoAnimType) { - this.holoAnimType = holoAnimType; - } - - public int getSpeed() { - return speed; - } - - public void setSpeed(int speed) { - this.speed = speed; - } - - public List getPrefixes() { - return prefixes; - } - - public void setColors(List prefixes) { - this.prefixes = prefixes; - } - - public DynamicHologram getDynamicHologram() { - return dynamicHologram; - } - - public void setDynamicHologram(DynamicHologram dynamicHologram) { - this.dynamicHologram = dynamicHologram; - } - - public int getLineCount() { - return lineCount; - } - - public void setLineCount(int lineCount) { - this.lineCount = lineCount; - } - - public String getRewardHologram() { - return rewardHologram; - } - - public void setRewardHologram(String rewardHologram) { - this.rewardHologram = rewardHologram; - } - - public void setCreatedByPlayer(boolean createdByPlayer) { - this.createdByPlayer = createdByPlayer; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/CLuckyChest.java b/src/main/java/me/ztowne13/customcrates/crates/options/CLuckyChest.java deleted file mode 100644 index 9fc106e..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/CLuckyChest.java +++ /dev/null @@ -1,222 +0,0 @@ -package me.ztowne13.customcrates.crates.options; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.CrateSettingsBuilder; -import me.ztowne13.customcrates.crates.CrateState; -import me.ztowne13.customcrates.interfaces.logging.StatusLoggerEvent; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.block.Block; -import org.bukkit.configuration.file.FileConfiguration; - -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.Random; - -/** - * Created by ztowne13 on 8/3/15. - */ -public class CLuckyChest extends CSetting { - - private final Random random = new Random(); - private double chance; - private double outOfChance; - private boolean isBLWL; - private boolean requirePermission = true; - private List whiteList = new ArrayList<>(); - private List worlds = new ArrayList<>(); - private List worldsRaw = new ArrayList<>(); - private boolean allWorlds = true; - - public CLuckyChest(Crate crate) { - super(crate, crate.getInstance()); - } - - @Override - public void loadFor(CrateSettingsBuilder crateSettingsBuilder, CrateState crateState) { - FileConfiguration fc = getSettings().getFileConfiguration(); - - if (!crateSettingsBuilder.hasValue("lucky-chest")) { - StatusLoggerEvent.LUCKYCHEST_NOVALUES.log(getCrate()); - return; - } - - if (crateSettingsBuilder.hasValue("lucky-chest.chance")) { - String unParsedChance = fc.getString("lucky-chest.chance"); - String[] args = unParsedChance.split("/"); - try { - setChance(Integer.parseInt(args[0])); - setOutOfChance(Integer.parseInt(args[1])); - } catch (Exception exc) { - StatusLoggerEvent.LUCKYCHEST_CHANCE_MISFORMATTED.log(getCrate()); - } - } else { - chance = 1; - outOfChance = 100; - StatusLoggerEvent.LUCKYCHEST_CHANCE_NONEXISTENT.log(getCrate()); - } - - if (crateSettingsBuilder.hasValue("lucky-chest.is-block-list-whitelist")) { - try { - setBLWL(fc.getBoolean("lucky-chest.is-block-list-whitelist")); - } catch (Exception exc) { - StatusLoggerEvent.LUCKYCHEST_BLWL_INVALID.log(getCrate()); - } - } else { - setBLWL(true); - StatusLoggerEvent.LUCKYCHEST_BLWL_NONEXISTENT.log(getCrate()); - } - - if (crateSettingsBuilder.hasValue("lucky-chest.require-permission")) { - try { - requirePermission = fc.getBoolean("lucky-chest.require-permission"); - } catch (Exception exc) { - StatusLoggerEvent.LUCKYCHEST_REQUIRE_PERMISSION_INVALID.log(getCrate()); - } - } else { - requirePermission = true; - StatusLoggerEvent.LUCKYCHEST_REQUIRE_PERMISSION_NONEXISTENT.log(getCrate()); - } - - if (crateSettingsBuilder.hasValue("lucky-chest.worlds")) { - worldsRaw = fc.getStringList("lucky-chest.worlds"); - - for (String s : fc.getStringList("lucky-chest.worlds")) { - setAllWorlds(false); - World w = Bukkit.getWorld(s); - if (w != null) { - getWorlds().add(w); - } else { - StatusLoggerEvent.LUCKYCHEST_WORLD_INVALID.log(getCrate(), s); - } - } - } - - if (crateSettingsBuilder.hasValue("lucky-chest.block-list")) { - try { - for (String mat : fc.getStringList("lucky-chest.block-list")) { - Optional optional = XMaterial.matchXMaterial(mat); - if (optional.isPresent()) { - getWhiteList().add(optional.get().parseMaterial()); - } else { - StatusLoggerEvent.LUCKYCHEST_BLOCKLIST_INVALIDBLOCK.log(getCrate(), mat); - } - } - } catch (Exception exc) { - StatusLoggerEvent.LUCKYCHEST_BLOCKLIST_INVALID.log(getCrate()); - } - } else { - StatusLoggerEvent.LUCKYCHEST_BLOCKLIST_NONEXISTENT.log(getCrate()); - } - } - - public void saveToFile() { - getFileHandler().get().set("lucky-chest.chance", ((int) chance) + "/" + ((int) outOfChance)); - getFileHandler().get().set("lucky-chest.require-permission", isRequirePermission()); - if (!whiteList.isEmpty()) { - getFileHandler().get().set("lucky-chest.is-block-list-whitelist", isBLWL); - - ArrayList whiteListRaw = new ArrayList<>(); - for (Material mat : getWhiteList()) - whiteListRaw.add(mat.name()); - - getFileHandler().get().set("lucky-chest.block-list", whiteListRaw); - } else { - getFileHandler().get().set("lucky-chest.is-block-list-whitelist", null); - getFileHandler().get().set("lucky-chest.block-list", null); - } - if (!worldsRaw.isEmpty()) { - getFileHandler().get().set("lucky-chest.worlds", worldsRaw); - } else { - getFileHandler().get().set("lucky-chest.worlds", null); - } - } - - public boolean canRunForBlock(Block block) { - if (!isAllWorlds() && !getWorlds().contains(block.getWorld())) { - return false; - } - - if (getWhiteList().isEmpty()) { - return true; - } - - return isBLWL() == getWhiteList().contains(block.getType()); - } - - public boolean runChance() { - return (random.nextInt(((int) getOutOfChance())) + 1) <= getChance(); - } - - public boolean checkRun(Block b) { - return canRunForBlock(b) && runChance(); - } - - public double getChance() { - return chance; - } - - public void setChance(double chance) { - this.chance = chance; - } - - public double getOutOfChance() { - return outOfChance; - } - - public void setOutOfChance(double outOfChance) { - this.outOfChance = outOfChance; - } - - public boolean isBLWL() { - return isBLWL; - } - - public void setBLWL(boolean BLWL) { - isBLWL = BLWL; - } - - public List getWhiteList() { - return whiteList; - } - - public void setWhiteList(List whiteList) { - this.whiteList = whiteList; - } - - public List getWorlds() { - return worlds; - } - - public void setWorlds(List worlds) { - this.worlds = worlds; - } - - public boolean isAllWorlds() { - return allWorlds; - } - - public void setAllWorlds(boolean allWorlds) { - this.allWorlds = allWorlds; - } - - public List getWorldsRaw() { - return worldsRaw; - } - - public void setWorldsRaw(List worldsRaw) { - this.worldsRaw = worldsRaw; - } - - public boolean isRequirePermission() { - return requirePermission; - } - - public void setRequirePermission(boolean requirePermission) { - this.requirePermission = requirePermission; - } -} - diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/CMultiCrateInventory.java b/src/main/java/me/ztowne13/customcrates/crates/options/CMultiCrateInventory.java deleted file mode 100644 index dbb09bc..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/CMultiCrateInventory.java +++ /dev/null @@ -1,477 +0,0 @@ -package me.ztowne13.customcrates.crates.options; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.Messages; -import me.ztowne13.customcrates.SettingsValue; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.CrateSettingsBuilder; -import me.ztowne13.customcrates.crates.CrateState; -import me.ztowne13.customcrates.crates.PlacedCrate; -import me.ztowne13.customcrates.crates.crateaction.CrateAction; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.interfaces.items.SaveableItemBuilder; -import me.ztowne13.customcrates.interfaces.logging.StatusLoggerEvent; -import me.ztowne13.customcrates.players.PlayerManager; -import me.ztowne13.customcrates.players.data.VirtualCrateData; -import me.ztowne13.customcrates.players.data.events.CrateCooldownEvent; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.CrateUtils; -import org.bukkit.Bukkit; -import org.bukkit.GameMode; -import org.bukkit.Material; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.event.inventory.ClickType; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Created by ztowne13 on 6/14/16. - */ -public class CMultiCrateInventory extends CSetting { - private static final String AVAILABLE_SYMBOLS = "abcdefghijklmnopqrstuvwxyz123456789 "; - - private final HashMap crateSpots = new HashMap<>(); - private final HashMap items = new HashMap<>(); - private final HashMap materialsWithID = new HashMap<>(); - private final HashMap cratesWithID = new HashMap<>(); - - private InventoryBuilder inventoryBuilder; - - public CMultiCrateInventory(Crate crate) { - super(crate, crate.getInstance()); - } - - public void updateCrateSpots() { - for (int i = 0; i < getInventoryBuilder().getSize(); i++) { - if (crateSpots.containsKey(i)) { - Crate crateAtSpot = crateSpots.get(i); - ItemStack itemAtSlot = getInventoryBuilder().getInv().getItem(i); - if (itemAtSlot == null || itemAtSlot.getType().equals(Material.AIR) || - !(new ItemBuilder(itemAtSlot).equals(crateAtSpot.getSettings().getCrateItemHandler().getItem()))) { - crateSpots.remove(i); - } - } - } - } - - @Override - public void loadFor(CrateSettingsBuilder crateSettingsBuilder, CrateState crateState) { - FileConfiguration fc = getCrate().getSettings().getFileConfiguration(); - if (crateSettingsBuilder.hasValue("gui")) { - try { - for (String s : fc.getConfigurationSection("gui.objects").getValues(false).keySet()) { - s = s.toLowerCase(); - String cause = "The crate name is invalid"; - try { - String value = fc.getString("gui.objects." + s); - if (Crate.existsNotCaseSensitive(value)) { - cause = "The crate name to set the object to is invalid"; - cratesWithID.put(s, Crate.getCrate(instance, value)); - } else { - SaveableItemBuilder item = new SaveableItemBuilder(XMaterial.STONE, 1); - item.setDisplayName("&cThis item was configured improperly"); - item.loadItem(getFileHandler(), "gui.objects." + s, crateSettingsBuilder.getStatusLogger(), - StatusLoggerEvent.MULTICRATE_ITEM_FAILURE, - StatusLoggerEvent.MULTICRATE_ENCHANTMENT_ADD_FAILURE, - StatusLoggerEvent.MULTICRATE_POTION_ADD_FAILURE, - StatusLoggerEvent.MULTICRATE_GLOW_FAILURE, - StatusLoggerEvent.MULTICRATE_AMOUNT_FAILURE, - StatusLoggerEvent.MULTICRATE_FLAG_FAILURE); - materialsWithID.put(s, item); - } - } catch (Exception exc) { - StatusLoggerEvent.MULTICRATEINVENTORY_OBJECTS_INVALID.log(getCrate(), s, cause); - } - } - } catch (Exception exc) { - StatusLoggerEvent.MULTICRATEINVENTORY_OBJECTS_MISCONFIGURED.log(getCrate()); - } - - - try { - int row = 0; - int slot = 0; - for (String s : fc.getStringList("gui.rows")) { - s = s.toLowerCase(); - for (String character : s.split("")) { - if (character == null || character.replaceAll("\\s+", "").equalsIgnoreCase("")) { - continue; - } - for (String identifier : materialsWithID.keySet()) { - if (identifier.equalsIgnoreCase(character)) { - items.put((row * 9) + slot, materialsWithID.get(character)); - break; - } - } - - - for (String identifier : cratesWithID.keySet()) { - if (identifier.equalsIgnoreCase(character)) { - crateSpots.put((row * 9) + slot, cratesWithID.get(character)); - break; - } - } - slot++; - } - row++; - slot = 0; - } - - } catch (Exception exc) { - StatusLoggerEvent.MULTICRATEINVENTORY_ROW_MISCONFIGURED.log(getCrate()); - } - - return; - } - StatusLoggerEvent.MULTICRATEINVENTORY_NONEXISTENT.log(getCrate()); - } - - @Override - public void saveToFile() { - if (inventoryBuilder == null || inventoryBuilder.getInv() == null) - return; - - Inventory inv = inventoryBuilder.getInv(); - - // It looks like this updates the arrays that have the items in them - for (int i = 0; i < inv.getSize(); i++) { - SaveableItemBuilder stack = inv.getItem(i) == null - ? new SaveableItemBuilder(XMaterial.AIR) - : new SaveableItemBuilder(inv.getItem(i)); - - // If the item is not a crate - if (CrateUtils.searchByCrate(stack.getStack()) == null) { - boolean itemDoesntAlreadyExist = true; - for (ItemBuilder alreadyExistingItem : materialsWithID.values()) { - if (alreadyExistingItem.equals(stack)) { - itemDoesntAlreadyExist = false; - break; - } - } - - if (itemDoesntAlreadyExist) { - materialsWithID.put(getNextSymbol(), stack); - } - } - // The item is a crate - else { - Crate crate = CrateUtils.searchByCrate(stack.getStack()); - boolean createDoesntAlreadyExist = true; - for (Crate alreadyExistingCrate : cratesWithID.values()) { - if (alreadyExistingCrate.equals(crate)) { - createDoesntAlreadyExist = false; - break; - } - } - - if (createDoesntAlreadyExist) { - cratesWithID.put(getNextSymbol(), crate); - } - } - } - - ArrayList lines = new ArrayList<>(); - StringBuilder line = new StringBuilder(); - - for (int i = 0; i < inv.getSize(); i++) { - ItemBuilder stack; - if (inv.getItem(i) == null) { - stack = new ItemBuilder(XMaterial.AIR); - } else { - stack = new ItemBuilder(inv.getItem(i)); - } - - // The item isn't a crate - if (CrateUtils.searchByCrate(stack.getStack()) == null) { - - for (Map.Entry entry : materialsWithID.entrySet()) { - String s = entry.getKey(); - if (s.equalsIgnoreCase("")) { - s = "-"; - } - try { - SaveableItemBuilder s2 = entry.getValue(); - - if (s2.equals(stack)) { - line.append(s); - s2.saveItem(getFileHandler(), "gui.objects." + s, true); - break; - } - } catch (Exception exc) { - for (Player p : Bukkit.getOnlinePlayers()) { - if (p.isOp()) { - ChatUtils.msgError(p, - "Failed to save multicrate " + getCrate().getName() + " with value " + s); - } - } - exc.printStackTrace(); - } - } - } else { - Crate cs = CrateUtils.searchByCrate(stack.getStack()); - for (Map.Entry entry : cratesWithID.entrySet()) { - String s = entry.getKey(); - try { - if (s.equalsIgnoreCase("")) { - s = "-"; - } - Crate crate = entry.getValue(); - if (crate.equals(cs)) { - line.append(s); - getFileHandler().get().set("gui.objects." + s, crate.getName()); - break; - } - } catch (Exception exc) { - for (Player p : Bukkit.getOnlinePlayers()) { - if (p.isOp()) { - ChatUtils.msgError(p, "Failed to save multicrate " + crate.getName() + " with value " + s); - } - } - exc.printStackTrace(); - } - } - } - - if (line.length() == 9) { - lines.add(line.toString()); - line = new StringBuilder(); - } - } - - getFileHandler().get().set("gui.rows", lines); - } - - public InventoryBuilder getInventory(Player player, String invName, boolean toEdit) { - if (inventoryBuilder == null) { - int slots = items.size() + crateSpots.size() - 2; - int rows = (slots / 9) + (slots % 9 == 0 ? 0 : 1); - inventoryBuilder = new InventoryBuilder(player, rows * 9, invName); - - for (Map.Entry entry : items.entrySet()) { - try { - inventoryBuilder.setItem(entry.getKey(), entry.getValue()); - } catch (Exception exc) { - ChatUtils.msgError(player, "There are to many lines in the MultiCrate inventory"); - } - } - instance.getDebugUtils().log("CMultiCrateInventory.getInventory.if(ib == null)"); - - } else if (toEdit) { - InventoryBuilder newIb = new InventoryBuilder(player, inventoryBuilder.getInv().getSize(), invName); - for (int i = 0; i < newIb.getInv().getSize(); i++) { - Inventory oldInv = inventoryBuilder.getInv(); - if (oldInv.getItem(i) != null && !oldInv.getItem(i).getType().equals((Material.AIR))) { - newIb.getInv().setItem(i, oldInv.getItem(i)); - } - } - - inventoryBuilder = newIb; - instance.getDebugUtils().log("CMultiCrateInventory.getInventory.else"); - } - - for (Map.Entry entry : crateSpots.entrySet()) { - try { - Crate crate = entry.getValue(); - instance.getDebugUtils().log(crate.getName()); - VirtualCrateData vcd = PlayerManager.get(instance, player).getPlayerDataManager().getVCCrateData(crate); - instance.getDebugUtils().log(vcd.toString()); - ItemBuilder crateIb = new ItemBuilder(crate.getSettings().getCrateItemHandler().getItem(1)); - - if (instance.getSettings().getConfigValAsBoolean("virtual-crate-cratecount").equals(Boolean.TRUE)) { - String toAddLore = (String) SettingsValue.VIRTUAL_CRATE_LORE.getValue(instance); - if (!toAddLore.equalsIgnoreCase("") && !toAddLore.equalsIgnoreCase("none")) { - crateIb.addLore(""); - crateIb.addLore(toAddLore); - } - } - if (instance.getSettings().getConfigValAsBoolean("virtual-crate-keycount").equals(Boolean.TRUE)) { - String toAddLore = (String) SettingsValue.VIRTUAL_KEY_LORE.getValue(instance); - if (!toAddLore.equalsIgnoreCase("") && !toAddLore.equalsIgnoreCase("none")) { - crateIb.addLore(""); - crateIb.addLore(toAddLore); - } - } - - List lore = new ArrayList<>(crateIb.getLore()); - crateIb.clearLore(); - - for (String line : lore) { - line = line.replace("%keys%", vcd.getKeys() + ""); - line = line.replace("%crates%", vcd.getCrates() + ""); - - crateIb.addLore(line); - } - - inventoryBuilder.setItem(entry.getKey(), crateIb); - } catch (Exception exc) { - ChatUtils.msgError(player, "There are to many lines in the MultiCrate inventory"); - } - } - - inventoryBuilder.setPlayer(player); - return inventoryBuilder; - } - - public String getNextSymbol() { - ArrayList combined = new ArrayList<>(); - combined.addAll(materialsWithID.keySet()); - combined.addAll(cratesWithID.keySet()); - for (String s : AVAILABLE_SYMBOLS.split("")) { - if (!combined.contains(s) && !s.replaceAll("\\s+", "").equalsIgnoreCase("")) { - return s; - } - } - return "TOMANYSYMBOLS"; - } - - public void checkClick(PlayerManager playerManager, int slot, ClickType clickType) { - final Player player = playerManager.getPlayer(); - Crate crate = playerManager.getOpenCrate(); - - if (!crate.getSettings().getMultiCrateSettings().getCrateSpots().containsKey(slot) || playerManager.isInRewardMenu()) { - return; - } - - final Crate clickedCrate = crate.getSettings().getMultiCrateSettings().getCrateSpots().get(slot); - - // Usability check - if (!CrateUtils.isCrateUsable(clickedCrate)) { - Messages.CRATE_DISABLED.msgSpecified(instance, player); - if (player.hasPermission("customcrates.admin") || player.isOp()) { - Messages.CRATE_DISABLED_ADMIN.msgSpecified(instance, player); - } - return; - } - - if (clickType != ClickType.LEFT && clickType != ClickType.RIGHT) { - return; - } - - // Is preview menu - if (clickType.equals(Boolean - .parseBoolean(SettingsValue.MC_REWARD_DISPLAY_LEFTCLICK.getValue(instance).toString().toUpperCase()) ? - ClickType.LEFT : ClickType.RIGHT) && SettingsValue.REWARD_DISPLAY_ENABLED.getValue(instance).equals(Boolean.TRUE)) { - clickedCrate.getSettings().getDisplayer().openFor(player); - // Set last open crate back to multicrate so that closing the reward previewer reopens the multicrate - final Crate cachedMulticrate = this.crate; - Bukkit.getScheduler().runTaskLater(instance, () -> playerManager.openCrate(cachedMulticrate), 2); - return; - } - - // Virtual crates check - if (SettingsValue.REQUIRE_VIRTUAL_CRATE_AND_KEY.getValue(instance).equals(Boolean.TRUE) - && playerManager.getPlayerDataManager().getVCCrateData(clickedCrate).getCrates() <= 0) { - Messages.INSUFFICIENT_VIRTUAL_CRATES.msgSpecified(playerManager.getInstance(), player); - return; - } - - // Inventory check - if (!CrateAction.isInventoryTooEmpty(instance, player)) { - Messages.INVENTORY_TOO_FULL.msgSpecified(instance, player); - clickedCrate.getSettings().getCrateAnimation().playFailToOpen(player, false, true); - - invCheck(player, playerManager); - return; - } - - // Permission check - if (!player.hasPermission(clickedCrate.getSettings().getPermission()) && - !clickedCrate.getSettings().getPermission().equalsIgnoreCase("no permission")) { - Messages.NO_PERMISSION_CRATE.msgSpecified(instance, player); - clickedCrate.getSettings().getCrateAnimation().playFailToOpen(player, false, true); - invCheck(player, playerManager); - return; - } - - // Gamemode check - if (player.getGameMode().equals(GameMode.CREATIVE) && - instance.getSettings().getConfigValues().get("open-creative").equals(Boolean.FALSE)) { - Messages.DENY_CREATIVE_MODE.msgSpecified(instance, player); - return; - } - - // Cooldown check - CrateCooldownEvent cce = playerManager.getPlayerDataManager().getCrateCooldownEventByCrates(clickedCrate); - if (cce != null && !cce.isCooldownOverAsBoolean()) { - invCheck(player, playerManager); - cce.playFailure(playerManager.getPlayerDataManager()); - return; - } - - // Economy check - if (!instance.getEconomyHandler().handleCheck(player, clickedCrate.getSettings().getCost(), true)) { - crate.getSettings().getCrateAnimation().playFailToOpen(player, false, true); - invCheck(player, playerManager); - return; - } - - // Open crate - player.closeInventory(); - - if (clickedCrate.getSettings().isCanFastTrack()) { - clickedCrate.getSettings().setCanFastTrack(false); - Bukkit.getScheduler().runTaskLater(instance, () -> clickedCrate.getSettings().setCanFastTrack(true), 2L); - } - - if (!clickedCrate.getSettings().getCrateAnimation() - .startAnimation(player, playerManager.getLastOpenCrate(), false, false)) { - invCheck(player, playerManager); - instance.getEconomyHandler().failSoReturn(player, clickedCrate.getSettings().getCost()); - return; - } - - new CrateCooldownEvent(clickedCrate, System.currentTimeMillis(), true).addTo(playerManager.getPlayerDataManager()); - // Post Conditions - if (playerManager.isUseVirtualCrate()) { - playerManager.getPlayerDataManager().setVirtualCrateCrates(clickedCrate, - playerManager.getPlayerDataManager().getVCCrateData(clickedCrate).getCrates() - 1); - } else if (!this.crate.getSettings().getObtainType().equals(ObtainType.STATIC)) { - try { - PlacedCrate pc = PlacedCrate.get(instance, playerManager.getLastOpenCrate()); - pc.delete(); - } catch (Exception exc) { - // IGNORED - } - } - } - - public void openFor(Player player, PlacedCrate placedCrate) { - PlayerManager pm = PlayerManager.get(instance, player); - crate.getSettings().getMultiCrateSettings() - .getInventory(player, crate.getSettings().getCrateInventoryName() == null ? crate.getName() : - crate.getSettings().getCrateInventoryName(), true).open(); - pm.setLastOpenCrate(placedCrate.getLocation()); - pm.setLastOpenedPlacedCrate(placedCrate); - pm.openCrate(crate); - getCrate().getSettings().getSound().runAll(player, placedCrate.getLocation(), new ArrayList<>()); - } - - public void invCheck(Player player, PlayerManager playerManager) { - if (player.getLocation().distance(playerManager.getLastOpenCrate()) > 10) { - player.closeInventory(); - } - } - - public Map getCrateSpots() { - return crateSpots; - } - - public Map getItems() { - return items; - } - - public InventoryBuilder getInventoryBuilder() { - return inventoryBuilder; - } - - public void setInventoryBuilder(InventoryBuilder inventoryBuilder) { - this.inventoryBuilder = inventoryBuilder; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/CParticle.java b/src/main/java/me/ztowne13/customcrates/crates/options/CParticle.java deleted file mode 100644 index b0569f1..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/CParticle.java +++ /dev/null @@ -1,276 +0,0 @@ -package me.ztowne13.customcrates.crates.options; - -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.CrateSettingsBuilder; -import me.ztowne13.customcrates.crates.CrateState; -import me.ztowne13.customcrates.crates.SettingsConverter; -import me.ztowne13.customcrates.crates.options.particles.BukkitParticleEffect; -import me.ztowne13.customcrates.crates.options.particles.NMSParticleEffect; -import me.ztowne13.customcrates.crates.options.particles.ParticleData; -import me.ztowne13.customcrates.crates.options.particles.ParticleEffect; -import me.ztowne13.customcrates.crates.options.particles.effects.PEAnimationType; -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import me.ztowne13.customcrates.interfaces.logging.StatusLoggerEvent; -import me.ztowne13.customcrates.utils.VersionUtils; -import org.bukkit.Color; -import org.bukkit.Location; -import org.bukkit.Particle; -import org.bukkit.configuration.file.FileConfiguration; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class CParticle extends CSetting { - private Map> particles = new HashMap<>(); - - public CParticle(Crate crate) { - super(crate, crate.getInstance()); - } - - @Override - public void loadFor(CrateSettingsBuilder crateSettingsBuilder, CrateState crateState) { - if (crateSettingsBuilder.hasValue(crateState.name().toLowerCase() + ".particles")) { - parseAndAddParticles(crateState.name().toUpperCase(), - crateState.name().toLowerCase() + ".particles"); - } - - if (crateState.equals(CrateState.OPEN) && crateSettingsBuilder.hasValue("open.crate-tiers")) { - for (String id : getCrate().getSettings().getFileConfiguration().getConfigurationSection("open.crate-tiers").getKeys(false)) { - if (crateSettingsBuilder.hasValue("open.crate-tiers." + id + ".particles")) { - parseAndAddParticles(id, "open.crate-tiers." + id + ".particles"); - } - } - } - } - - public void saveToFile() { - if (!particles.isEmpty()) - for (Map.Entry> entry : particles.entrySet()) - for (ParticleData pd : entry.getValue()) - pd.save(getFileHandler(), getPath(entry.getKey())); - } - - public void deleteParticle(String tier, ParticleData particleData) { - getParticles().get(tier).remove(particleData); - getFileHandler().get().set(getPath(tier) + "." + particleData.getName(), null); - } - - public void addParticle(ParticleData particleData, String s) { - List plist = getParticles().getOrDefault(s, new ArrayList<>()); - plist.add(particleData); - StatusLoggerEvent.PARTICLE_ADD_SUCCESS.log(getCrate(), particleData.getParticleName()); - getParticles().put(s, plist); - } - - public void parseAndAddParticles(String id, String path) { - SettingsConverter.convertParticles(getFileHandler(), path); - - FileConfiguration fc = getFileHandler().get(); - - try { - for (String parent : getFileHandler().get().getConfigurationSection(path).getValues(false).keySet()) { - String particleTypeAS = getFileHandler().get().getString(path + "." + parent + ".type"); - String rangeXAS = fc.getString(path + "." + parent + ".range-x"); - String rangeYAS = fc.getString(path + "." + parent + ".range-y"); - String rangeZAS = fc.getString(path + "." + parent + ".range-z"); - String centerXAS = fc.getString(path + "." + parent + ".center-x"); - String centerYAS = fc.getString(path + "." + parent + ".center-y"); - String centerZAS = fc.getString(path + "." + parent + ".center-z"); - String speedAS = fc.getString(path + "." + parent + ".speed"); - String amountAS = fc.getString(path + "." + parent + ".amount"); - String animationAS = fc.getString(path + "." + parent + ".animation"); - String colorRed = fc.getString(path + "." + parent + ".color.red"); - String colorGreen = fc.getString(path + "." + parent + ".color.green"); - String colorBlue = fc.getString(path + "." + parent + ".color.blue"); - String colorEnabled = fc.getString(path + "." + parent + ".color.enabled"); - String redstoneSize = fc.getString(path + "." + parent + ".redstone-size"); - - try { - ParticleData pd; - - if (VersionUtils.Version.v1_9.isServerVersionOrEarlier()) { - ParticleEffect pe; - try { - pe = ParticleEffect.valueOf(particleTypeAS); - } catch (Exception exc) { - StatusLoggerEvent.PARTICLE_INVALID.log(getCrate(), parent, particleTypeAS); - continue; - } - pd = new NMSParticleEffect(instance, pe, parent, false); - } else { - try { - pd = new BukkitParticleEffect(instance, particleTypeAS, parent, false); - } catch (Exception exc) { - StatusLoggerEvent.PARTICLE_INVALID.log(getCrate(), parent, particleTypeAS); - continue; - } - } - - // Load default values - these must be correct for particles to work. - - pd.setRangeX(Float.parseFloat(rangeXAS)); - pd.setRangeY(Float.parseFloat(rangeYAS)); - pd.setRangeZ(Float.parseFloat(rangeZAS)); - pd.setSpeed(Float.parseFloat(speedAS)); - pd.setAmount(Integer.parseInt(amountAS)); - - // Loading option values - - // center x - try { - pd.setCenterX(Float.parseFloat(centerXAS)); - } catch (Exception exc) { - // IGNORED - } - - // center y - try { - pd.setCenterY(Float.parseFloat(centerYAS)); - } catch (Exception exc) { - // IGNORED - } - - // center z - try { - pd.setCenterZ(Float.parseFloat(centerZAS)); - } catch (Exception exc) { - // IGNORED - } - - // colors - try { - pd.setColorRed(Integer.parseInt(colorRed)); - } catch (Exception exc) { - pd.setColorRed(255); - } - - try { - pd.setColorBlue(Integer.parseInt(colorBlue)); - } catch (Exception exc) { - pd.setColorBlue(0); - } - - try { - pd.setColorGreen(Integer.parseInt(colorGreen)); - } catch (Exception exc) { - pd.setColorGreen(0); - } - - try { - pd.setColorEnabled(Boolean.parseBoolean(colorEnabled)); - } catch (Exception exc) { - pd.setColorEnabled(false); - } - - float size; - - try { - size = Float.parseFloat(redstoneSize); - - if (size <= 0) - size = 1; - } catch (Exception exc) { - size = 1; - } - - // Redstone info - try { - if (VersionUtils.Version.v1_13.isServerVersionOrLater() && particleTypeAS.equalsIgnoreCase("REDSTONE")) { - pd.setHasColor(true); - pd.setColorEnabled(true); - - pd.setSize(size); - - Color color = Color.fromBGR(pd.getColorBlue(), pd.getColorGreen(), pd.getColorRed()); - Particle.DustOptions dustOptions = new Particle.DustOptions(color, size); - - pd.setDustOptions(dustOptions); - } - } catch (Exception exc) { - exc.printStackTrace(); - } - - try { - PEAnimationType peAnimationType = PEAnimationType.valueOf(animationAS); - if (!peAnimationType.equals(PEAnimationType.NONE)) { - // This is to default the particle animation speed and particle count so it doesn't appear broken - if (pd.getSpeed() < 3) { - pd.setSpeed(20); - } - if (pd.getAmount() == 0) { - pd.setAmount(1); - } - - pd.setParticleAnimationEffect(peAnimationType.getAnimationEffectInstance(instance, pd)); - pd.setHasAnimation(true); - } - } catch (Exception exc) { - StatusLoggerEvent.PARTICLE_ANIMATION_INVALID.log(getCrate(), animationAS); - } - - addParticle(pd, id); - } catch (Exception exc) { - exc.printStackTrace(); - StatusLoggerEvent.PARTICLE_STRING_INVALID.log(getCrate(), parent); - } - } - } catch (Exception exc) { - exc.printStackTrace(); - } - } - - public void runAll(Location location, CrateState crateState, List rewards) { - List alreadyUpdatedAnimations = instance.getAlreadyUpdated(); - for (String id : getParticles().keySet()) { - if (crateState.equals(CrateState.PLAY)) { - if (crateState.name().toUpperCase().equalsIgnoreCase(id)) { - for (ParticleData pd : getParticles().get(id)) { - if (pd.isHasAnimation()) { - if (!alreadyUpdatedAnimations.contains(pd)) { - pd.getParticleAnimationEffect().update(); - alreadyUpdatedAnimations.add(pd); - } - pd.getParticleAnimationEffect().display(location); - } else { - pd.display(location); - } - } - } - continue; - } - - if ((id.equalsIgnoreCase(crateState.name().toUpperCase()) && (!getSettings().isTiersOverrideDefaults() || rewards.isEmpty() || - !getParticles().containsKey(rewards.get(0).getRarity().toUpperCase()))) || - (!rewards.isEmpty() && rewards.get(0).getRarity().equalsIgnoreCase(id))) { - for (ParticleData pd : getParticles().get(id)) { - if (pd.isHasAnimation()) { - if (!alreadyUpdatedAnimations.contains(pd)) { - pd.getParticleAnimationEffect().update(); - alreadyUpdatedAnimations.add(pd); - } - pd.getParticleAnimationEffect().display(location); - } else { - pd.display(location); - } - } - } - } - } - - public String getPath(String tier) { - return (tier.equalsIgnoreCase("PLAY") ? "play." : "open.") + - (tier.equalsIgnoreCase("open") || tier.equalsIgnoreCase("play") ? "" : "crate-tiers." + tier + ".") + - "particles"; - } - - public Map> getParticles() { - return particles; - } - - public void setParticles(Map> particles) { - this.particles = particles; - } - -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/CReward.java b/src/main/java/me/ztowne13/customcrates/crates/options/CReward.java deleted file mode 100644 index 03ccea1..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/CReward.java +++ /dev/null @@ -1,271 +0,0 @@ -package me.ztowne13.customcrates.crates.options; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.CrateSettingsBuilder; -import me.ztowne13.customcrates.crates.CrateState; -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import me.ztowne13.customcrates.interfaces.logging.StatusLoggerEvent; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.entity.Player; - -import java.util.*; - -public class CReward extends CSetting { - private static final Map allRewards = new HashMap<>(); - private final Random random = new Random(); - private Reward[] crateRewards; - - public CReward(Crate crate) { - super(crate, crate.getInstance()); - } - - public static void loadAll(SpecializedCrates instance, Player player) { - boolean newValues = false; - - for (String rName : instance.getRewardsFile().get().getKeys(false)) { - if (!getAllRewards().containsKey(rName)) { - if (!newValues) { - newValues = true; - ChatUtils.msgInfo(player, "It can take a while to load all of the rewards for the first time..."); - } - Reward reward = new Reward(instance, rName); - reward.loadFromConfig(); - reward.loadChance(); - allRewards.put(rName, reward); - } - } - } - - public static boolean rewardNameExists(SpecializedCrates instance, String name) { - for (String s : instance.getRewardsFile().get().getKeys(false)) { - if (s.equalsIgnoreCase(name)) { - return true; - } - } - return false; - } - - public static Map getAllRewards() { - return allRewards; - } - - public static Map getAllRewardsSorted(SpecializedCrates specializedCrates, RewardSortType rewardSortType) { - LinkedHashMap sortedRewards = new LinkedHashMap<>(); - switch (rewardSortType) { - case CREATED_ORDER: - for (String rewardName : specializedCrates.getRewardsFile().get().getKeys(false)) { - Reward reward = getAllRewards().get(rewardName); - if (reward != null) { - sortedRewards.put(rewardName, reward); - } - } - return sortedRewards; - case ALPHABETICAL: - ArrayList keys = new ArrayList<>(getAllRewards().keySet()); - keys.sort(String.CASE_INSENSITIVE_ORDER); - for (String key : keys) { - sortedRewards.put(key, getAllRewards().get(key)); - } - return sortedRewards; - case CHANCE: - ArrayList rewards = new ArrayList<>(getAllRewards().values()); - Collections.sort(rewards); - for (Reward reward : rewards) { - sortedRewards.put(reward.getRewardName(), reward); - } - return sortedRewards; - } - - return null; - } - - public Reward getByName(String s) { - for (Reward r : getCrateRewards()) { - if (r.getDisplayName(false).equals(s) || r.getRewardName().equals(s)) - return r; - } - return null; - } - - public void saveToFile() { - String[] displayNameRewards = new String[crateRewards.length]; - for (int i = 0; i < displayNameRewards.length; i++) { - displayNameRewards[i] = crateRewards[i].getRewardName(); - } - getFileHandler().get().set("rewards", Arrays.asList(displayNameRewards)); - } - - public void removeReward(String name) { - Reward toRemove = getByName(name); - Reward[] newRewards = new Reward[crateRewards.length - 1]; - - int i = 0; - boolean foundOne = false; - for (Reward r : crateRewards) { - if (!r.equals(toRemove) || foundOne) { - newRewards[i] = r; - i++; - } else { - foundOne = true; - } - } - - crateRewards = newRewards; - } - - public boolean addReward(String rName) { - if (allRewards.containsKey(rName)) { - Reward toAdd = allRewards.get(rName); - if (!toAdd.isNeedsMoreConfig()) { - Reward[] newRewards = - new Reward[(crateRewards == null || crateRewards.length == 0 ? 0 : crateRewards.length) + 1]; - - if (crateRewards != null) { - System.arraycopy(crateRewards, 0, newRewards, 0, newRewards.length - 1); - } - - newRewards[newRewards.length - 1] = toAdd; - - crateRewards = newRewards; - return true; - } - } - return false; - } - - public void loadFor(CrateSettingsBuilder crateSettingsBuilder, CrateState crateState) { - if (crateSettingsBuilder.hasValue("rewards")) { - int slot = 0; - - setCrateRewards(new Reward[getCrate().getSettings().getFileConfiguration().getStringList("rewards").size()]); - - List unparsedRewards = getCrate().getSettings().getFileConfiguration().getStringList("rewards"); - - for (String s : unparsedRewards) { - Reward reward = new Reward(getCrate().getInstance(), this, s); - - setReward(slot, reward); - - getAllRewards().put(s, reward); - StatusLoggerEvent.REWARD_ADD_SUCCESS.log(getCrate(), s); - - slot++; - } - - Reward[] updatedRewards = new Reward[getCrateRewards().length]; - int count = 0; - for (Reward reward : getCrateRewards().clone()) { - if (reward.loadFromConfig()) { - updatedRewards[count] = reward; - count++; - } - } - - Reward[] finalUpdate = new Reward[count]; - count = 0; - for (Reward r : updatedRewards) { - if (r != null) { - finalUpdate[count] = r; - count++; - } - } - - setCrateRewards(finalUpdate); - - if (finalUpdate.length == 0) { - StatusLoggerEvent.REWARDS_EMPTY.log(getCrate()); - getCrate().setDisabledByError(true); - } - - return; - } - StatusLoggerEvent.REWARDS_PATH_NONEXISTENT.log(getCrate()); - } - - public void setReward(Integer i, Reward reward) { - getCrateRewards()[i] = reward; - } - - public Reward getRandomReward() { - double totalOdds = getTotalOdds(); - - double randNum = getRandomNumber(totalOdds); - - double currentStackedOdds = 0; - - Reward[] crateRewardsClone = getCrateRewards(); - - for (Reward r : crateRewardsClone) { - double odds = r.getChance(); - currentStackedOdds += odds; - if (randNum <= currentStackedOdds) { - return r; - } - } - - return null; - } - - public Double getRandomNumber(double outOfOdds) { - return outOfOdds * random.nextDouble(); - } - - public Double getTotalOdds() { - double totalOdds = 0; - for (Reward r : getCrateRewards()) { - double odds = r.getChance(); - if (odds < 0) - odds = 0; - totalOdds += odds; - } - return totalOdds; - } - - public Reward[] getCrateRewards() { - return crateRewards; - } - - public void setCrateRewards(Reward[] crateRewards) { - this.crateRewards = crateRewards; - } - - public enum RewardSortType { - CREATED_ORDER("Created Order", "ALPHABETICAL", - new String[]{ - "The order in which the", - "rewards were created." - }), - ALPHABETICAL("Alphabetical Order", "CHANCE", - new String[]{ - "In order, from A-Z" - }), - CHANCE("Reward Chance Order", "CREATED_ORDER", - new String[]{ - "In order from the lowest", - "to highest chance" - }); - - String niceName; - String[] niceDescription; - String next; - - RewardSortType(String niceName, String next, String[] niceDescription) { - this.niceName = niceName; - this.niceDescription = niceDescription; - this.next = next; - } - - public RewardSortType getNext() { - return valueOf(next); - } - - public String getNiceName() { - return niceName; - } - - public String[] getNiceDescription() { - return niceDescription; - } - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/CSetting.java b/src/main/java/me/ztowne13/customcrates/crates/options/CSetting.java deleted file mode 100644 index c94ddbe..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/CSetting.java +++ /dev/null @@ -1,39 +0,0 @@ -package me.ztowne13.customcrates.crates.options; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.CrateSettings; -import me.ztowne13.customcrates.crates.CrateSettingsBuilder; -import me.ztowne13.customcrates.crates.CrateState; -import me.ztowne13.customcrates.interfaces.files.FileHandler; - -public abstract class CSetting { - protected final SpecializedCrates instance; - protected Crate crate; - - public CSetting(Crate crate, SpecializedCrates instance) { - this.crate = crate; - this.instance = instance; - } - - public abstract void loadFor(CrateSettingsBuilder crateSettingsBuilder, CrateState crateState); - - public abstract void saveToFile(); - - public FileHandler getFileHandler() { - return getCrate().getSettings().getFileHandler(); - } - - - public CrateSettings getSettings() { - return getCrate().getSettings(); - } - - public Crate getCrate() { - return crate; - } - - public void setCrate(Crate crate) { - this.crate = crate; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/CSound.java b/src/main/java/me/ztowne13/customcrates/crates/options/CSound.java deleted file mode 100644 index 801642a..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/CSound.java +++ /dev/null @@ -1,140 +0,0 @@ -package me.ztowne13.customcrates.crates.options; - -import com.cryptomorin.xseries.XSound; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.CrateSettingsBuilder; -import me.ztowne13.customcrates.crates.CrateState; -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import me.ztowne13.customcrates.crates.options.sounds.SoundData; -import me.ztowne13.customcrates.interfaces.logging.StatusLoggerEvent; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -import java.util.*; - -public class CSound extends CSetting { - private Map> sounds = new HashMap<>(); - - public CSound(Crate crate) { - super(crate, crate.getInstance()); - } - - @Override - public void loadFor(CrateSettingsBuilder crateSettingsBuilder, CrateState crateState) { - if (crateSettingsBuilder.hasValue("open.sounds")) { - addSoundsFromList("OPEN", crateSettingsBuilder.getSettings().getFileConfiguration().getStringList("open.sounds")); - } - if (crateSettingsBuilder.hasValue("open.crate-tiers")) { - for (String id : getSettings().getFileConfiguration().getConfigurationSection("open.crate-tiers").getKeys(false)) { - if (crateSettingsBuilder.hasValue("open.crate-tiers." + id + ".sounds")) { - addSoundsFromList(id.toUpperCase(), getSettings().getFileConfiguration().getStringList("open.crate-tiers." + id + ".sounds")); - } - } - } - } - - public void saveToFile() { - if (!sounds.isEmpty()) { - for (Map.Entry> entry : sounds.entrySet()) { - String tier = entry.getKey(); - ArrayList listToSet = new ArrayList<>(); - for (SoundData sd : entry.getValue()) { - String parsedSoundData = sd.getSound().name() + ", " + sd.getPitch() + ", " + sd.getVolume(); - listToSet.add(parsedSoundData); - } - - String path = "open." + (tier.equalsIgnoreCase("OPEN") ? "" : "crate-tiers." + tier) + "sounds"; - getFileHandler().get().set(path, listToSet); - } - } - } - - public void addSoundsFromList(String id, List list) { - for (String sound : list) { - try { - String[] args = sound.replace(" ", "").split(","); - - SoundData sd; - - Optional optional = XSound.matchXSound(args[0]); - if (optional.isPresent()) { - sd = new SoundData(optional.get()); - } else { - StatusLoggerEvent.SOUND_NONEXISTENT.log(getCrate(), sound, args[0]); - continue; - } - - try { - int pitch = Integer.parseInt(args[1]); - sd.setPitch(pitch); - } catch (Exception exc) { - if (args.length > 0) { - StatusLoggerEvent.SOUND_PITCH_INVALID.log(getCrate(), sd.getSound().name(), args[1]); - } else { - StatusLoggerEvent.SOUND_PITCH_NONEXISTENT.log(getCrate(), sd.getSound().name()); - } - continue; - } - - try { - int volume = Integer.parseInt(args[2]); - sd.setVolume(volume); - } catch (Exception exc) { - if (args.length > 1) { - StatusLoggerEvent.SOUND_VOLUME_INVALID - .log(getCrate(), sd.getSound().name(), args[2]); - } else { - StatusLoggerEvent.SOUND_VOLUME_NONEXISTENT.log(getCrate(), sd.getSound().name()); - } - continue; - } - - addSound(id, sd); - StatusLoggerEvent.SOUND_ADD_SUCCESS.log(getCrate(), sd.getSound().name()); - } catch (Exception exc) { - StatusLoggerEvent.SOUND_ADD_IMPROPER_SETUP.log(getCrate(), sound); - exc.printStackTrace(); - } - } - } - - public void addSound(String id, SoundData soundData) { - id = id.toUpperCase(); - List list = getSounds().getOrDefault(id, new ArrayList<>()); - list.add(soundData); - getSounds().put(id, list); - } - - public void runAll(Player player, Location location, List rewards) { - for (String tier : getSounds().keySet()) { - if ((tier.equalsIgnoreCase("OPEN") && (!getSettings().isTiersOverrideDefaults() || rewards.isEmpty() || - !getSounds().containsKey(rewards.get(0).getRarity().toUpperCase()))) || - (!rewards.isEmpty() && rewards.get(0).getRarity().equalsIgnoreCase(tier))) { - for (SoundData sd : getSounds().get(tier)) { - sd.playTo(player, location); - } - } - } - } - - public SoundData getSoundFromName(String tier, XSound sound) { - SoundData sd = null; - - for (SoundData soundData : getSounds().get(tier)) { - if (soundData.getSound().equals(sound)) { - sd = soundData; - break; - } - } - - return sd; - } - - public Map> getSounds() { - return sounds; - } - - public void setSounds(Map> sounds) { - this.sounds = sounds; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/CrateItemHandler.java b/src/main/java/me/ztowne13/customcrates/crates/options/CrateItemHandler.java deleted file mode 100644 index 7b5ec38..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/CrateItemHandler.java +++ /dev/null @@ -1,72 +0,0 @@ -package me.ztowne13.customcrates.crates.options; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.CrateSettingsBuilder; -import me.ztowne13.customcrates.crates.CrateState; -import me.ztowne13.customcrates.interfaces.items.SaveableItemBuilder; -import me.ztowne13.customcrates.interfaces.logging.StatusLoggerEvent; -import me.ztowne13.customcrates.utils.Utils; -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; - -public class CrateItemHandler extends CSetting { - - private SaveableItemBuilder crateItem; - - public CrateItemHandler(Crate crate) { - super(crate, crate.getInstance()); - - crateItem = new SaveableItemBuilder(XMaterial.RED_WOOL, 1); - crateItem.setDisplayName("&4Please set me!"); - } - - @Override - public void loadFor(CrateSettingsBuilder crateSettingsBuilder, CrateState crateState) { - boolean result = crateItem - .loadItem(getCrate().getSettings().getFileHandler(), "crate", crateSettingsBuilder.getStatusLogger(), - StatusLoggerEvent.SETTINGS_CRATE_FAILURE, - StatusLoggerEvent.SETTINGS_CRATE_ENCHANTMENT_ADD_FAILURE, - StatusLoggerEvent.SETTINGS_CRATE_POTION_ADD_FAILURE, StatusLoggerEvent.SETTINGS_CRATE_GLOW_FAILURE, - StatusLoggerEvent.SETTINGS_CRATE_AMOUNT_FAILURE, StatusLoggerEvent.SETTINGS_CRATE_FLAG_FAILURE); - if (!result) { - StatusLoggerEvent.SETTINGS_CRATE_FAILURE_DISABLE.log(crateSettingsBuilder.getStatusLogger()); - } - } - - @Override - public void saveToFile() { - crateItem.saveItem(getCrate().getSettings().getFileHandler(), "crate", false); - } - - public boolean crateMatchesToStack(ItemStack stack) { - ItemStack crate = getItem(1); - if (Utils.itemHasName(stack)) { - return crate.getType().equals(stack.getType()) && - crate.getItemMeta().getDisplayName().equals(stack.getItemMeta().getDisplayName()); - } - return false; - } - - public boolean crateMatchesBlock(Material blockType) { - if (blockType.equals(getItem(1).getType())) { - return true; - } - - return blockType.name().equalsIgnoreCase("SKULL") && getItem(1).getType().name().equalsIgnoreCase("SKULL_ITEM"); - } - - public ItemStack getItem(int amount) { - ItemStack stack = crateItem.getStack().clone(); - stack.setAmount(amount); - return stack; - } - - public SaveableItemBuilder getItem() { - return crateItem; - } - - public void setItem(SaveableItemBuilder crateItem) { - this.crateItem = crateItem; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/KeyItemHandler.java b/src/main/java/me/ztowne13/customcrates/crates/options/KeyItemHandler.java deleted file mode 100644 index 2ad19a1..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/KeyItemHandler.java +++ /dev/null @@ -1,180 +0,0 @@ -package me.ztowne13.customcrates.crates.options; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SettingsValue; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.CrateSettings; -import me.ztowne13.customcrates.crates.CrateSettingsBuilder; -import me.ztowne13.customcrates.crates.CrateState; -import me.ztowne13.customcrates.interfaces.items.SaveableItemBuilder; -import me.ztowne13.customcrates.interfaces.logging.StatusLoggerEvent; -import me.ztowne13.customcrates.players.PlayerDataManager; -import me.ztowne13.customcrates.players.PlayerManager; -import me.ztowne13.customcrates.utils.Utils; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - -public class KeyItemHandler extends CSetting { - - private SaveableItemBuilder keyItem; - - public KeyItemHandler(Crate crate) { - super(crate, crate.getInstance()); - - keyItem = new SaveableItemBuilder(XMaterial.REDSTONE_TORCH, 1); - keyItem.setDisplayName("&4Please set me!"); - } - - @Override - public void loadFor(CrateSettingsBuilder crateSettingsBuilder, CrateState crateState) { - //itemfail, improperenchamnt, improperpotion, improperglow - crateSettingsBuilder.setupRequireKey(); - boolean result = keyItem. - loadItem(getCrate().getSettings().getFileHandler(), "key", crateSettingsBuilder.getStatusLogger(), - StatusLoggerEvent.SETTINGS_KEY_FAILURE, - StatusLoggerEvent.SETTINGS_KEY_ENCHANTMENT_ADD_FAILURE, - StatusLoggerEvent.SETTINGS_KEY_POTION_ADD_FAILURE, StatusLoggerEvent.SETTINGS_KEY_GLOW_FAILURE, - StatusLoggerEvent.SETTINGS_KEY_AMOUNT_FAILURE, StatusLoggerEvent.SETTINGS_KEY_FLAG_FAILURE); - - if (!result) { - StatusLoggerEvent.SETTINGS_KEY_FAILURE_DISABLE.log(crateSettingsBuilder.getStatusLogger()); - } - } - - @Override - public void saveToFile() { - if (!getCrate().isMultiCrate()) { - keyItem.saveItem(getCrate().getSettings().getFileHandler(), "key", false); - } - } - - public ItemStack getItem(int amount) { - ItemStack stack = keyItem.getStack().clone(); - stack.setAmount(amount); - return stack; - } - - public boolean keyMatchesToStack(ItemStack stack, boolean checkLore) { - ItemStack crate = getItem(1); - if (stack != null && Utils.itemHasName(stack)) { - boolean matchesNormal = crate.getType().equals(stack.getType()) && - crate.getItemMeta().getDisplayName().equals(stack.getItemMeta().getDisplayName()); - - boolean matchesLore = !checkLore || keyLoreMatches(stack); - - return matchesNormal && matchesLore; - } - return false; - } - - public boolean hasKeyInInventory(Player player) { - for (ItemStack stack : player.getInventory().getContents()) { - if (keyMatchesToStack(stack, true)) { - instance.getDebugUtils().log("hasKeyInInventory() - return true", getClass()); - return true; - } - } - return false; - } - - private boolean keyLoreMatches(ItemStack stack) { - if (!getItem(1).hasItemMeta() || !getItem(1).getItemMeta().hasLore()) { - return true; - } - - if (SettingsValue.REQUIRE_KEY_LORE.getValue(instance).equals(Boolean.FALSE)) { - return true; - } - - if (!stack.hasItemMeta() || !stack.getItemMeta().hasLore()) { - return false; - } - - for (int i = 0; i < getItem(1).getItemMeta().getLore().size(); i++) { - try { - String stackLore = stack.getItemMeta().getLore().get(i); - String keyLore = getItem(1).getItemMeta().getLore().get(i); - if (!stackLore.equalsIgnoreCase(keyLore)) { - return false; - } - } catch (Exception exc) { - return false; - } - } - - return true; - } - - public boolean playerPassesKeyTest(Player player, boolean requireKeyInHand) { - if (player.getItemInHand() == null) { - return false; - } - - CrateSettings settings = getCrate().getSettings(); - boolean passesKeyTest = !settings.isRequireKey() || - (requireKeyInHand ? keyMatchesToStack(player.getItemInHand(), true) : hasKeyInInventory(player)) || - PlayerManager.get(instance, player).getPlayerDataManager().getVCCrateData(getCrate()).getKeys() > 0; - - instance.getDebugUtils().log("playerPasseysKeyTest() - return " + passesKeyTest); - return passesKeyTest; - } - - public void takeKeyFromPlayer(Player player, boolean fromInv) { - boolean prioritzePhysical = (boolean) instance.getSettings().getConfigValues().get("prioritize-physical-key"); - if (!takeKeyFromPlayer(player, fromInv, prioritzePhysical)) { - takeKeyFromPlayer(player, fromInv, !prioritzePhysical); - } - } - - public boolean takeKeyFromPlayer(Player player, boolean fromInv, boolean checkPhysical) { - if (!checkPhysical) { - PlayerDataManager pdm = PlayerManager.get(instance, player).getPlayerDataManager(); - if (pdm.getVCCrateData(getCrate()).getKeys() > 0) { - pdm.setVirtualCrateKeys(getCrate(), pdm.getVCCrateData(getCrate()).getKeys() - 1); - return true; - } - return false; - } - - if (fromInv) { - for (int i = 0; i < 36; i++) { - try { - if (player.getInventory().getItem(i) != null) { - ItemStack stack = player.getInventory().getItem(i); - if (getCrate().getSettings().getKeyItemHandler().keyMatchesToStack(stack, true)) { - if (stack.getAmount() == 1) { - player.getInventory().setItem(i, null); - } else { - stack.setAmount(stack.getAmount() - 1); - } - return true; - } - } - } catch (Exception exc) { - exc.printStackTrace(); - } - } - } else { - ItemStack stack = player.getItemInHand(); - if (getCrate().getSettings().getKeyItemHandler().keyMatchesToStack(stack, true)) { - if (player.getItemInHand().getAmount() == 1) { - player.setItemInHand(null); - } else { - ItemStack st = player.getItemInHand(); - st.setAmount(st.getAmount() - 1); - player.setItemInHand(st); - } - return true; - } - } - return false; - } - - public SaveableItemBuilder getItem() { - return keyItem; - } - - public void setItem(SaveableItemBuilder keyItem) { - this.keyItem = keyItem; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/ObtainType.java b/src/main/java/me/ztowne13/customcrates/crates/options/ObtainType.java deleted file mode 100644 index 2701f25..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/ObtainType.java +++ /dev/null @@ -1,45 +0,0 @@ -package me.ztowne13.customcrates.crates.options; - -import me.ztowne13.customcrates.crates.Crate; - -import java.util.ArrayList; -import java.util.List; - -public enum ObtainType { - STATIC(true, false, "The crate will always stay where it is, no matter how many times it's opened."), - - DYNAMIC(false, true, "The crate will disappear once it is used once."), - - LUCKYCHEST(false, false, "The crate will spawn randomly when a player is mining according to the lucky chest settings."); - - private final boolean isStatic; - private final boolean canPlace; - private final String descriptor; - - ObtainType(boolean isStatic, boolean canPlace, String descriptor) { - this.isStatic = isStatic; - this.canPlace = canPlace; - this.descriptor = descriptor; - } - - public static boolean getReqKey(Crate crates) { - return crates.getSettings().isRequireKey(); - } - - public static List descriptors() { - ArrayList descriptors = new ArrayList<>(); - - for (ObtainType val : values()) - descriptors.add(val.descriptor); - - return descriptors; - } - - public boolean isStatic() { - return isStatic; - } - - public boolean isCanPlace() { - return canPlace; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/actions/ActionEffect.java b/src/main/java/me/ztowne13/customcrates/crates/options/actions/ActionEffect.java deleted file mode 100644 index 63f9f04..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/actions/ActionEffect.java +++ /dev/null @@ -1,26 +0,0 @@ -package me.ztowne13.customcrates.crates.options.actions; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.options.actions.actionbar.ActionBar; -import org.bukkit.entity.Player; - -/** - * Created by ztown on 2/14/2017. - */ -public abstract class ActionEffect { - protected final SpecializedCrates instance; - - public ActionEffect(SpecializedCrates instance) { - this.instance = instance; - } - - public abstract ActionBar getActionBarExecutor(); - - public abstract void newTitle(); - - public abstract void playTitle(Player p); - - public abstract void setDisplayTitle(String title); - - public abstract void setDisplaySubtitle(String subtitle); -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/actions/BukkitActionEffect.java b/src/main/java/me/ztowne13/customcrates/crates/options/actions/BukkitActionEffect.java deleted file mode 100644 index dc78976..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/actions/BukkitActionEffect.java +++ /dev/null @@ -1,49 +0,0 @@ -package me.ztowne13.customcrates.crates.options.actions; - -import me.ztowne13.customcrates.SettingsValue; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.options.actions.actionbar.ActionBar; -import org.bukkit.entity.Player; - -/** - * Created by ztowne13 on 2/14/2017. - */ -public class BukkitActionEffect extends ActionEffect { - private String title; - private String subtitle; - private int fadeIn; - private int stay; - private int fadeOut; - - public BukkitActionEffect(SpecializedCrates instance) { - super(instance); - } - - public ActionBar getActionBarExecutor() { - return new ActionBar(); - } - - public void newTitle() { - fadeIn = Integer.parseInt(SettingsValue.CA_FADE_IN.getValue(instance).toString()); - stay = Integer.parseInt(SettingsValue.CA_STAY.getValue(instance).toString()); - fadeOut = Integer.parseInt(SettingsValue.CA_FADE_OUT.getValue(instance).toString()); - } - - public void playTitle(Player p) { - p.sendTitle(title, subtitle, fadeIn * 20, stay * 20, fadeOut * 20); - resetData(); - } - - public void setDisplayTitle(String title) { - this.title = title; - } - - public void setDisplaySubtitle(String subtitle) { - this.subtitle = subtitle; - } - - public void resetData() { - title = ""; - subtitle = ""; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/actions/NMSActionEffect.java b/src/main/java/me/ztowne13/customcrates/crates/options/actions/NMSActionEffect.java deleted file mode 100644 index 068fbf6..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/actions/NMSActionEffect.java +++ /dev/null @@ -1,59 +0,0 @@ -package me.ztowne13.customcrates.crates.options.actions; - -import me.ztowne13.customcrates.SettingsValue; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.options.actions.actionbar.ActionBar; -import me.ztowne13.customcrates.crates.options.actions.actionbar.ActionBarV1_7_8; -import me.ztowne13.customcrates.crates.options.actions.actionbar.ActionBarV1_9_10_11; -import me.ztowne13.customcrates.crates.options.actions.title.Title; -import me.ztowne13.customcrates.crates.options.actions.title.TitleV1_11; -import me.ztowne13.customcrates.crates.options.actions.title.TitleV1_7_8_9_10; -import me.ztowne13.customcrates.utils.VersionUtils; -import org.bukkit.entity.Player; - -/** - * Created by ztowne13 on 2/14/2017. - */ -public class NMSActionEffect extends ActionEffect { - private Title title; - - public NMSActionEffect(SpecializedCrates instance) { - super(instance); - } - - public ActionBar getActionBarExecutor() { - if (VersionUtils.Version.v1_8.isServerVersionOrEarlier()) - return new ActionBarV1_7_8(); - else - return new ActionBarV1_9_10_11(); - } - - public void newTitle() { - if (VersionUtils.Version.v1_10.isServerVersionOrEarlier()) { - title = new TitleV1_7_8_9_10("", "", - (Integer.parseInt(SettingsValue.CA_FADE_IN.getValue(instance).toString())), - (Integer.parseInt(SettingsValue.CA_STAY.getValue(instance).toString())), - (Integer.parseInt(SettingsValue.CA_FADE_OUT.getValue(instance).toString()))); - } else { - title = new TitleV1_11("", "", - (Integer.parseInt(SettingsValue.CA_FADE_IN.getValue(instance).toString())), - (Integer.parseInt(SettingsValue.CA_STAY.getValue(instance).toString())), - (Integer.parseInt(SettingsValue.CA_FADE_OUT.getValue(instance).toString()))); - } - } - - public void playTitle(Player p) { - if (title != null) { - title.send(p); - title = null; - } - } - - public void setDisplayTitle(String titleMsg) { - title.setTitle(titleMsg); - } - - public void setDisplaySubtitle(String subtitleMsg) { - title.setSubtitle(subtitleMsg); - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/actions/actionbar/ActionBar.java b/src/main/java/me/ztowne13/customcrates/crates/options/actions/actionbar/ActionBar.java deleted file mode 100644 index 6abd720..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/actions/actionbar/ActionBar.java +++ /dev/null @@ -1,10 +0,0 @@ -package me.ztowne13.customcrates.crates.options.actions.actionbar; - -import org.bukkit.entity.Player; - -public class ActionBar { - public void play(Player player, String msg) { - player.spigot().sendMessage(net.md_5.bungee.api.ChatMessageType.ACTION_BAR, - net.md_5.bungee.api.chat.TextComponent.fromLegacyText(msg)); - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/actions/actionbar/ActionBarV1_7_8.java b/src/main/java/me/ztowne13/customcrates/crates/options/actions/actionbar/ActionBarV1_7_8.java deleted file mode 100644 index 4cff580..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/actions/actionbar/ActionBarV1_7_8.java +++ /dev/null @@ -1,41 +0,0 @@ -package me.ztowne13.customcrates.crates.options.actions.actionbar; - -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.ReflectionUtilities; -import org.bukkit.entity.Player; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; - -public class ActionBarV1_7_8 extends ActionBar { - @Override - public void play(Player player, String msg) { - try { - Class c1 = ReflectionUtilities.getOBCClass("entity.CraftPlayer"); - Object p = c1.cast(player); - - Class c4 = ReflectionUtilities.getNMSClass("PacketPlayOutChat"); - Class c5 = ReflectionUtilities.getNMSClass("Packet"); - - Method m3 = ReflectionUtilities.getNMSClass("IChatBaseComponent$ChatSerializer") - .getDeclaredMethod("a", String.class); - Object cbc = ReflectionUtilities.getNMSClass("IChatBaseComponent") - .cast(m3.invoke(ReflectionUtilities.getNMSClass("IChatBaseComponent$ChatSerializer"), - "{\"text\": \"" + msg + "\"}")); - Object ppoc = c4.getConstructor(ReflectionUtilities.getNMSClass("IChatBaseComponent"), Byte.TYPE) - .newInstance(cbc, (byte) 2); - - - Method m1 = c1.getDeclaredMethod("getHandle"); - Object h = m1.invoke(p); - Field f1 = h.getClass().getDeclaredField("playerConnection"); - Object pc = f1.get(h); - Method m5 = pc.getClass().getDeclaredMethod("sendPacket", c5); - m5.invoke(pc, ppoc); - } catch (Exception ex) { - ChatUtils - .log("The ACTIONBAR method has failed to run, please make sure you are on the latest version on the plugin and latest version of spigot / bukkit."); - ex.printStackTrace(); - } - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/actions/actionbar/ActionBarV1_9_10_11.java b/src/main/java/me/ztowne13/customcrates/crates/options/actions/actionbar/ActionBarV1_9_10_11.java deleted file mode 100644 index b50dee5..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/actions/actionbar/ActionBarV1_9_10_11.java +++ /dev/null @@ -1,37 +0,0 @@ -package me.ztowne13.customcrates.crates.options.actions.actionbar; - -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.ReflectionUtilities; -import org.bukkit.entity.Player; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; - -public class ActionBarV1_9_10_11 extends ActionBar { - @Override - public void play(Player player, String msg) { - try { - Class c1 = ReflectionUtilities.getOBCClass("entity.CraftPlayer"); - Object p = c1.cast(player); - - Class c4 = ReflectionUtilities.getNMSClass("PacketPlayOutChat"); - Class c5 = ReflectionUtilities.getNMSClass("Packet"); - - Object o = ReflectionUtilities.getNMSClass("ChatComponentText").getConstructor(String.class) - .newInstance(msg); - Object ppoc = c4.getConstructor(ReflectionUtilities.getNMSClass("IChatBaseComponent"), Byte.TYPE) - .newInstance(o, (byte) 2); - - Method m1 = c1.getDeclaredMethod("getHandle"); - Object h = m1.invoke(p); - Field f1 = h.getClass().getDeclaredField("playerConnection"); - Object pc = f1.get(h); - Method m5 = pc.getClass().getDeclaredMethod("sendPacket", c5); - m5.invoke(pc, ppoc); - } catch (Exception ex) { - ChatUtils - .log("The ACTIONBAR method has failed to run, please make sure you are on the latest version on the plugin and latest version of spigot / bukkit."); - ex.printStackTrace(); - } - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/actions/title/Title.java b/src/main/java/me/ztowne13/customcrates/crates/options/actions/title/Title.java deleted file mode 100644 index 4ae39fe..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/actions/title/Title.java +++ /dev/null @@ -1,52 +0,0 @@ -package me.ztowne13.customcrates.crates.options.actions.title; - -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; - -public interface Title { - String getTitle(); - - void setTitle(String title); - - String getSubtitle(); - - void setSubtitle(String subtitle); - - void setTimingsToTicks(); - - void setTimingsToSeconds(); - - void send(Player player); - - void updateTimes(Player player); - - void updateTitle(Player player); - - void updateSubtitle(Player player); - - void broadcast(); - - void clearTitle(Player player); - - ChatColor getTitleColor(); - - void setTitleColor(ChatColor color); - - ChatColor getSubtitleColor(); - - void setSubtitleColor(ChatColor color); - - int getFadeInTime(); - - void setFadeInTime(int time); - - int getFadeOutTime(); - - void setFadeOutTime(int time); - - int getStayTime(); - - void setStayTime(int time); - - boolean isTicks(); -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/actions/title/TitleV1_11.java b/src/main/java/me/ztowne13/customcrates/crates/options/actions/title/TitleV1_11.java deleted file mode 100644 index bb90c77..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/actions/title/TitleV1_11.java +++ /dev/null @@ -1,403 +0,0 @@ -package me.ztowne13.customcrates.crates.options.actions.title; - -import me.ztowne13.customcrates.utils.ReflectionUtilities; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; - -/** - * Minecraft 1.8 TitleV1_7_8_9_10 - * For 1.11 - * - * @author Maxim Van de Wynckel - * @version 1.1.0 - */ -public class TitleV1_11 implements Title { - /* TitleV1_7_8_9_10 packet */ - private static Class packetTitle; - /* TitleV1_7_8_9_10 packet actions ENUM */ - private static Class packetActions; - /* Chat serializer */ - private static Class nmsChatSerializer; - private static Class chatBaseComponent; - private static Field playerConnection; - private static Method sendPacket; - /* TitleV1_7_8_9_10 text and color */ - private String title; - private ChatColor titleColor = ChatColor.WHITE; - /* Subtitle text and color */ - private String subtitle; - private ChatColor subtitleColor = ChatColor.WHITE; - /* TitleV1_7_8_9_10 timings */ - private int fadeInTime; - private int stayTime; - private int fadeOutTime; - private boolean ticks = false; - - public TitleV1_11() { - this("", ""); - } - - /** - * Create a new 1.8 title - * - * @param title TitleV1_7_8_9_10 - */ - public TitleV1_11(String title) { - this(title, ""); - } - - /** - * Create a new 1.8 title - * - * @param title TitleV1_7_8_9_10 text - * @param subtitle Subtitle text - */ - public TitleV1_11(String title, String subtitle) { - this(title, subtitle, -1, -1, -1); - } - - /** - * Copy 1.8 title - * - * @param title TitleV1_7_8_9_10 - */ - public TitleV1_11(TitleV1_11 title) { - // Copy title - this.title = title.getTitle(); - this.subtitle = title.getSubtitle(); - this.titleColor = title.getTitleColor(); - this.subtitleColor = title.getSubtitleColor(); - this.fadeInTime = title.getFadeInTime(); - this.fadeOutTime = title.getFadeOutTime(); - this.stayTime = title.getStayTime(); - this.ticks = title.isTicks(); - loadClasses(); - } - - /** - * Create a new 1.8 title - * - * @param title TitleV1_7_8_9_10 text - * @param subtitle Subtitle text - * @param fadeInTime Fade in time - * @param stayTime Stay on screen time - * @param fadeOutTime Fade out time - */ - public TitleV1_11(String title, String subtitle, int fadeInTime, int stayTime, - int fadeOutTime) { - this.title = title; - this.subtitle = subtitle; - this.fadeInTime = fadeInTime; - this.stayTime = stayTime; - this.fadeOutTime = fadeOutTime; - loadClasses(); - } - - /** - * Load spigot and NMS classes - */ - private void loadClasses() { - if (packetTitle == null) { - packetTitle = ReflectionUtilities.getNMSClass("PacketPlayOutTitle"); - packetActions = ReflectionUtilities.getNMSClass("PacketPlayOutTitle$EnumTitleAction"); - chatBaseComponent = ReflectionUtilities.getNMSClass("IChatBaseComponent"); - nmsChatSerializer = ReflectionUtilities.getNMSClass("ChatComponentText"); - /* NMS player and connection */ - Class nmsPlayer = ReflectionUtilities.getNMSClass("EntityPlayer"); - Class nmsPlayerConnection = ReflectionUtilities.getNMSClass("PlayerConnection"); - playerConnection = ReflectionUtilities.getField(nmsPlayer, "playerConnection"); - sendPacket = ReflectionUtilities.getMethod(nmsPlayerConnection, "sendPacket"); - } - } - - /** - * Get title text - * - * @return TitleV1_7_8_9_10 text - */ - public String getTitle() { - return this.title; - } - - /** - * Set title text - * - * @param title TitleV1_7_8_9_10 - */ - public void setTitle(String title) { - this.title = title; - } - - /** - * Get subtitle text - * - * @return Subtitle text - */ - public String getSubtitle() { - return this.subtitle; - } - - /** - * Set subtitle text - * - * @param subtitle Subtitle text - */ - public void setSubtitle(String subtitle) { - this.subtitle = subtitle; - } - - /** - * Set timings to ticks - */ - public void setTimingsToTicks() { - ticks = true; - } - - /** - * Set timings to seconds - */ - public void setTimingsToSeconds() { - ticks = false; - } - - /** - * Send the title to a player - * - * @param player Player - */ - public void send(Player player) { - if (packetTitle != null) { - // First reset previous settings - resetTitle(player); - try { - // Send timings first - Object handle = ReflectionUtilities.getHandle(player); - Object connection = playerConnection.get(handle); - Object[] actions = packetActions.getEnumConstants(); - Object packet = packetTitle.getConstructor(packetActions, - chatBaseComponent, Integer.TYPE, Integer.TYPE, - Integer.TYPE).newInstance(actions[3], null, - fadeInTime * (ticks ? 1 : 20), - stayTime * (ticks ? 1 : 20), - fadeOutTime * (ticks ? 1 : 20)); - // Send if set - if (fadeInTime != -1 && fadeOutTime != -1 && stayTime != -1) - sendPacket.invoke(connection, packet); - Object serialized; - if (!subtitle.equals("")) { - // Send subtitle if present - serialized = nmsChatSerializer.getConstructor(String.class) - .newInstance(subtitleColor + - ChatColor.translateAlternateColorCodes('&', - subtitle)); - packet = packetTitle.getConstructor(packetActions, - chatBaseComponent).newInstance(actions[1], - serialized); - sendPacket.invoke(connection, packet); - } - // Send title - serialized = nmsChatSerializer.getConstructor( - String.class).newInstance(titleColor + - ChatColor.translateAlternateColorCodes('&', title)); - packet = packetTitle.getConstructor(packetActions, - chatBaseComponent).newInstance(actions[0], serialized); - sendPacket.invoke(connection, packet); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - public void updateTimes(Player player) { - if (TitleV1_11.packetTitle != null) { - try { - Object handle = ReflectionUtilities.getHandle(player); - Object connection = playerConnection.get(handle); - Object[] actions = TitleV1_11.packetActions.getEnumConstants(); - Object packet = TitleV1_11.packetTitle.getConstructor( - TitleV1_11.packetActions, chatBaseComponent, - Integer.TYPE, Integer.TYPE, Integer.TYPE) - .newInstance( - actions[3], - null, - this.fadeInTime - * (this.ticks ? 1 : 20), - this.stayTime - * (this.ticks ? 1 : 20), - this.fadeOutTime - * (this.ticks ? 1 : 20)); - if ((this.fadeInTime != -1) && (this.fadeOutTime != -1) - && (this.stayTime != -1)) { - sendPacket.invoke(connection, packet); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - public void updateTitle(Player player) { - if (TitleV1_11.packetTitle != null) { - try { - Object handle = ReflectionUtilities.getHandle(player); - Object connection = playerConnection.get(handle); - Object[] actions = TitleV1_11.packetActions.getEnumConstants(); - Object serialized = nmsChatSerializer.getConstructor( - String.class) - .newInstance(titleColor + - ChatColor.translateAlternateColorCodes('&', - this.title)); - Object packet = TitleV1_11.packetTitle - .getConstructor( - TitleV1_11.packetActions, - chatBaseComponent).newInstance( - actions[0], serialized); - sendPacket.invoke(connection, packet); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - public void updateSubtitle(Player player) { - if (TitleV1_11.packetTitle != null) { - try { - Object handle = ReflectionUtilities.getHandle(player); - Object connection = playerConnection.get(handle); - Object[] actions = packetActions.getEnumConstants(); - Object serialized = nmsChatSerializer.getConstructor( - String.class) - .newInstance(subtitleColor + - ChatColor.translateAlternateColorCodes('&', - this.subtitle)); - Object packet = packetTitle.getConstructor( - packetActions, - chatBaseComponent).newInstance( - actions[1], serialized); - sendPacket.invoke(connection, packet); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - /** - * Broadcast the title to all players - */ - public void broadcast() { - for (Player p : Bukkit.getOnlinePlayers()) { - send(p); - } - } - - /** - * Clear the title - * - * @param player Player - */ - public void clearTitle(Player player) { - try { - // Send timings first - Object handle = ReflectionUtilities.getHandle(player); - Object connection = playerConnection.get(handle); - Object[] actions = packetActions.getEnumConstants(); - Object packet = packetTitle.getConstructor(packetActions, - chatBaseComponent).newInstance(actions[4], null); - sendPacket.invoke(connection, packet); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Reset the title settings - * - * @param player Player - */ - public void resetTitle(Player player) { - try { - // Send timings first - Object handle = ReflectionUtilities.getHandle(player); - Object connection = playerConnection.get(handle); - Object[] actions = packetActions.getEnumConstants(); - Object packet = packetTitle.getConstructor(packetActions, - chatBaseComponent).newInstance(actions[5], null); - sendPacket.invoke(connection, packet); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public ChatColor getTitleColor() { - return titleColor; - } - - /** - * Set the title color - * - * @param color Chat color - */ - public void setTitleColor(ChatColor color) { - this.titleColor = color; - } - - public ChatColor getSubtitleColor() { - return subtitleColor; - } - - /** - * Set the subtitle color - * - * @param color Chat color - */ - public void setSubtitleColor(ChatColor color) { - this.subtitleColor = color; - } - - public int getFadeInTime() { - return fadeInTime; - } - - /** - * Set title fade in time - * - * @param time Time - */ - public void setFadeInTime(int time) { - this.fadeInTime = time; - } - - public int getFadeOutTime() { - return fadeOutTime; - } - - /** - * Set title fade out time - * - * @param time Time - */ - public void setFadeOutTime(int time) { - this.fadeOutTime = time; - } - - public int getStayTime() { - return stayTime; - } - - /** - * Set title stay time - * - * @param time Time - */ - public void setStayTime(int time) { - this.stayTime = time; - } - - public boolean isTicks() { - return ticks; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/actions/title/TitleV1_7_8_9_10.java b/src/main/java/me/ztowne13/customcrates/crates/options/actions/title/TitleV1_7_8_9_10.java deleted file mode 100644 index 70961af..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/actions/title/TitleV1_7_8_9_10.java +++ /dev/null @@ -1,400 +0,0 @@ -package me.ztowne13.customcrates.crates.options.actions.title; - -import me.ztowne13.customcrates.utils.ReflectionUtilities; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; - -/** - * Minecraft 1.8 (1.9) TitleV1_7_8_9_10 - * - * @author Maxim Van de Wynckel - * @version 1.0.5 - */ -public class TitleV1_7_8_9_10 implements Title { - /* TitleV1_7_8_9_10 packet */ - private static Class packetTitle; - /* TitleV1_7_8_9_10 packet actions ENUM */ - private static Class packetActions; - /* Chat serializer */ - private static Class nmsChatSerializer; - private static Class chatBaseComponent; - private static Field playerConnection; - private static Method sendPacket; - /* TitleV1_7_8_9_10 text and color */ - private String title; - private ChatColor titleColor = ChatColor.WHITE; - /* Subtitle text and color */ - private String subtitle; - private ChatColor subtitleColor = ChatColor.WHITE; - /* TitleV1_7_8_9_10 timings */ - private int fadeInTime; - private int stayTime; - private int fadeOutTime; - private boolean ticks = false; - - public TitleV1_7_8_9_10() { - this("", ""); - } - - /** - * Create a new 1.8 title - * - * @param title TitleV1_7_8_9_10 - */ - public TitleV1_7_8_9_10(String title) { - this(title, ""); - } - - /** - * Create a new 1.8 title - * - * @param title TitleV1_7_8_9_10 text - * @param subtitle Subtitle text - */ - public TitleV1_7_8_9_10(String title, String subtitle) { - this(title, subtitle, -1, -1, -1); - } - - /** - * Copy 1.8 title - * - * @param title TitleV1_7_8_9_10 - */ - public TitleV1_7_8_9_10(TitleV1_7_8_9_10 title) { - // Copy title - this.title = title.getTitle(); - this.subtitle = title.getSubtitle(); - this.titleColor = title.getTitleColor(); - this.subtitleColor = title.getSubtitleColor(); - this.fadeInTime = title.getFadeInTime(); - this.fadeOutTime = title.getFadeOutTime(); - this.stayTime = title.getStayTime(); - this.ticks = title.isTicks(); - loadClasses(); - } - - /** - * Create a new 1.8 title - * - * @param title TitleV1_7_8_9_10 text - * @param subtitle Subtitle text - * @param fadeInTime Fade in time - * @param stayTime Stay on screen time - * @param fadeOutTime Fade out time - */ - public TitleV1_7_8_9_10(String title, String subtitle, int fadeInTime, int stayTime, - int fadeOutTime) { - this.title = title; - this.subtitle = subtitle; - this.fadeInTime = fadeInTime; - this.stayTime = stayTime; - this.fadeOutTime = fadeOutTime; - loadClasses(); - } - - /** - * Load spigot and NMS classes - */ - private void loadClasses() { - if (packetTitle == null) { - packetTitle = ReflectionUtilities.getNMSClass("PacketPlayOutTitle"); - packetActions = ReflectionUtilities.getNMSClass("PacketPlayOutTitle$EnumTitleAction"); - chatBaseComponent = ReflectionUtilities.getNMSClass("IChatBaseComponent"); - nmsChatSerializer = ReflectionUtilities.getNMSClass("ChatComponentText"); - /* NMS player and connection */ - Class nmsPlayer = ReflectionUtilities.getNMSClass("EntityPlayer"); - Class nmsPlayerConnection = ReflectionUtilities.getNMSClass("PlayerConnection"); - playerConnection = ReflectionUtilities.getField(nmsPlayer, "playerConnection"); - sendPacket = ReflectionUtilities.getMethod(nmsPlayerConnection, "sendPacket"); - } - } - - /** - * Get title text - * - * @return TitleV1_7_8_9_10 text - */ - public String getTitle() { - return this.title; - } - - /** - * Set title text - * - * @param title TitleV1_7_8_9_10 - */ - public void setTitle(String title) { - this.title = title; - } - - /** - * Get subtitle text - * - * @return Subtitle text - */ - public String getSubtitle() { - return this.subtitle; - } - - /** - * Set subtitle text - * - * @param subtitle Subtitle text - */ - public void setSubtitle(String subtitle) { - this.subtitle = subtitle; - } - - /** - * Set timings to ticks - */ - public void setTimingsToTicks() { - ticks = true; - } - - /** - * Set timings to seconds - */ - public void setTimingsToSeconds() { - ticks = false; - } - - /** - * Send the title to a player - * - * @param player Player - */ - public void send(Player player) { - if (packetTitle != null) { - // First reset previous settings - resetTitle(player); - try { - // Send timings first - Object handle = ReflectionUtilities.getHandle(player); - Object connection = playerConnection.get(handle); - Object[] actions = packetActions.getEnumConstants(); - Object packet = packetTitle.getConstructor(packetActions, - chatBaseComponent, Integer.TYPE, Integer.TYPE, - Integer.TYPE).newInstance(actions[2], null, - fadeInTime * (ticks ? 1 : 20), - stayTime * (ticks ? 1 : 20), - fadeOutTime * (ticks ? 1 : 20)); - // Send if set - if (fadeInTime != -1 && fadeOutTime != -1 && stayTime != -1) - sendPacket.invoke(connection, packet); - - // Send title - Object serialized = nmsChatSerializer.getConstructor( - String.class).newInstance( - ChatColor.translateAlternateColorCodes('&', title)); - packet = packetTitle.getConstructor(packetActions, - chatBaseComponent).newInstance(actions[0], serialized); - sendPacket.invoke(connection, packet); - if (!subtitle.equals("")) { - // Send subtitle if present - serialized = nmsChatSerializer.getConstructor(String.class) - .newInstance( - ChatColor.translateAlternateColorCodes('&', - subtitle)); - packet = packetTitle.getConstructor(packetActions, - chatBaseComponent).newInstance(actions[1], - serialized); - sendPacket.invoke(connection, packet); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - public void updateTimes(Player player) { - if (TitleV1_7_8_9_10.packetTitle != null) { - try { - Object handle = ReflectionUtilities.getHandle(player); - Object connection = playerConnection.get(handle); - Object[] actions = TitleV1_7_8_9_10.packetActions.getEnumConstants(); - Object packet = TitleV1_7_8_9_10.packetTitle.getConstructor( - TitleV1_7_8_9_10.packetActions, chatBaseComponent, - Integer.TYPE, Integer.TYPE, Integer.TYPE) - .newInstance( - actions[2], - null, - this.fadeInTime * (this.ticks ? 1 : 20), - this.stayTime * (this.ticks ? 1 : 20), - this.fadeOutTime * (this.ticks ? 1 : 20)); - if ((this.fadeInTime != -1) && (this.fadeOutTime != -1) - && (this.stayTime != -1)) { - sendPacket.invoke(connection, packet); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - public void updateTitle(Player player) { - if (TitleV1_7_8_9_10.packetTitle != null) { - try { - Object handle = ReflectionUtilities.getHandle(player); - Object connection = playerConnection.get(handle); - Object[] actions = TitleV1_7_8_9_10.packetActions.getEnumConstants(); - Object serialized = nmsChatSerializer.getConstructor( - String.class) - .newInstance( - ChatColor.translateAlternateColorCodes('&', - this.title)); - Object packet = TitleV1_7_8_9_10.packetTitle - .getConstructor( - TitleV1_7_8_9_10.packetActions, - chatBaseComponent).newInstance( - actions[0], serialized); - sendPacket.invoke(connection, packet); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - public void updateSubtitle(Player player) { - if (TitleV1_7_8_9_10.packetTitle != null) { - try { - Object handle = ReflectionUtilities.getHandle(player); - Object connection = playerConnection.get(handle); - Object[] actions = TitleV1_7_8_9_10.packetActions.getEnumConstants(); - Object serialized = nmsChatSerializer.getConstructor( - String.class) - .newInstance( - ChatColor.translateAlternateColorCodes('&', - this.subtitle)); - Object packet = TitleV1_7_8_9_10.packetTitle - .getConstructor( - TitleV1_7_8_9_10.packetActions, - chatBaseComponent).newInstance( - actions[1], serialized); - sendPacket.invoke(connection, packet); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - /** - * Broadcast the title to all players - */ - public void broadcast() { - for (Player p : Bukkit.getOnlinePlayers()) { - send(p); - } - } - - /** - * Clear the title - * - * @param player Player - */ - public void clearTitle(Player player) { - try { - // Send timings first - Object handle = ReflectionUtilities.getHandle(player); - Object connection = playerConnection.get(handle); - Object[] actions = packetActions.getEnumConstants(); - Object packet = packetTitle.getConstructor(packetActions, - chatBaseComponent).newInstance(actions[3], null); - sendPacket.invoke(connection, packet); - } catch (Exception e) { - e.printStackTrace(); - } - } - - /** - * Reset the title settings - * - * @param player Player - */ - public void resetTitle(Player player) { - try { - // Send timings first - Object handle = ReflectionUtilities.getHandle(player); - Object connection = playerConnection.get(handle); - Object[] actions = packetActions.getEnumConstants(); - Object packet = packetTitle.getConstructor(packetActions, - chatBaseComponent).newInstance(actions[4], null); - sendPacket.invoke(connection, packet); - } catch (Exception e) { - e.printStackTrace(); - } - } - - public ChatColor getTitleColor() { - return titleColor; - } - - /** - * Set the title color - * - * @param color Chat color - */ - public void setTitleColor(ChatColor color) { - this.titleColor = color; - } - - public ChatColor getSubtitleColor() { - return subtitleColor; - } - - /** - * Set the subtitle color - * - * @param color Chat color - */ - public void setSubtitleColor(ChatColor color) { - this.subtitleColor = color; - } - - public int getFadeInTime() { - return fadeInTime; - } - - /** - * Set title fade in time - * - * @param time Time - */ - public void setFadeInTime(int time) { - this.fadeInTime = time; - } - - public int getFadeOutTime() { - return fadeOutTime; - } - - /** - * Set title fade out time - * - * @param time Time - */ - public void setFadeOutTime(int time) { - this.fadeOutTime = time; - } - - public int getStayTime() { - return stayTime; - } - - /** - * Set title stay time - * - * @param time Time - */ - public void setStayTime(int time) { - this.stayTime = time; - } - - public boolean isTicks() { - return ticks; - } -} \ No newline at end of file diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/holograms/DynamicHologram.java b/src/main/java/me/ztowne13/customcrates/crates/options/holograms/DynamicHologram.java deleted file mode 100644 index d577b28..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/holograms/DynamicHologram.java +++ /dev/null @@ -1,92 +0,0 @@ -package me.ztowne13.customcrates.crates.options.holograms; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.PlacedCrate; -import me.ztowne13.customcrates.crates.options.holograms.animations.HoloAnimType; -import me.ztowne13.customcrates.crates.options.holograms.animations.HoloAnimation; -import me.ztowne13.customcrates.interfaces.externalhooks.holograms.Hologram; -import me.ztowne13.customcrates.utils.LocationUtils; -import org.bukkit.Location; - -import java.util.UUID; - -public class DynamicHologram { - private final UUID uuid; - - private final SpecializedCrates instance; - private PlacedCrate placedCrate; - - private Hologram hologram; - private HoloAnimation holoAnimation; - - private boolean displayingRewardHologram = false; - - public DynamicHologram(SpecializedCrates instance, PlacedCrate placedCrate) { - this.uuid = UUID.randomUUID(); - - this.instance = instance; - this.placedCrate = placedCrate; - - if (placedCrate.getHologram().getHoloAnimType() != null && placedCrate.getHologram().getHoloAnimType() != HoloAnimType.NONE) { - setHoloAnimation(placedCrate.getHologram().getHoloAnimType().getAsHoloAnimation(instance, this)); - } - } - - public void create(Location location) { - location.setY(location.getY() + getPlacedCrate().getHologram().getHologramOffset() - 1); - location = LocationUtils.getLocationCentered(location); - this.hologram = instance.getHologramManager().createHologram(location); - } - - public void addLine(String line) { - this.hologram.addLine(line); - } - - public void setLine(int lineNum, String line) { - this.hologram.setLine(lineNum, line); - } - - public void delete() { - instance.getHologramManager().deleteHologram(this.hologram); - this.hologram = null; - } - - public void teleport(Location location) { - location.setY(location.getY() + getPlacedCrate().getHologram().getHologramOffset()); - this.hologram.setLocation(LocationUtils.getLocationCentered(location)); - } - - public void tick() { - if (getHoloAnimation() != null && !placedCrate.getHologram().getPrefixes().isEmpty()) { - getHoloAnimation().tick(); - } - } - - public PlacedCrate getPlacedCrate() { - return placedCrate; - } - - public void setPlacedCrate(PlacedCrate placedCrate) { - this.placedCrate = placedCrate; - } - - public HoloAnimation getHoloAnimation() { - return holoAnimation; - } - - public void setHoloAnimation(HoloAnimation holoAnimation) { - this.holoAnimation = holoAnimation; - } - - public boolean getDisplayingRewardHologram() { - return displayingRewardHologram; - } - - public void setDisplayingRewardHologram(boolean displayingRewardHologram) { - this.displayingRewardHologram = displayingRewardHologram; - } - - public UUID getUuid() { - return uuid; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/holograms/animations/Animation.java b/src/main/java/me/ztowne13/customcrates/crates/options/holograms/animations/Animation.java deleted file mode 100644 index 01f7c58..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/holograms/animations/Animation.java +++ /dev/null @@ -1,22 +0,0 @@ -package me.ztowne13.customcrates.crates.options.holograms.animations; - -import me.ztowne13.customcrates.SpecializedCrates; - -/** - * Class that is the superclass to all non-crate open animations eg. holograms / particles - */ -public abstract class Animation { - protected final SpecializedCrates instance; - - public Animation(SpecializedCrates instance) { - this.instance = instance; - } - - public abstract void update(boolean force); - - public abstract void update(); - - public abstract void stop(); - - public abstract void tick(); -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/holograms/animations/HoloAnimType.java b/src/main/java/me/ztowne13/customcrates/crates/options/holograms/animations/HoloAnimType.java deleted file mode 100644 index aabdc7c..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/holograms/animations/HoloAnimType.java +++ /dev/null @@ -1,44 +0,0 @@ -package me.ztowne13.customcrates.crates.options.holograms.animations; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.options.holograms.DynamicHologram; - -import java.util.ArrayList; -import java.util.List; - -public enum HoloAnimType { - NONE("No hologram animation, use the normal hologram."), - - SINGLELINE_CHANGE( - "The hologram will update on whatever interval specified to all of the frames set. This is the same as TEXT_CHANGE."), - - TEXT_CHANGE( - "The hologram will update on whatever interval specified to all of the frames set. This is the same as SINGLELINE_CHANGE."); - - //MULTILINE_CHANGE; - - private final String descriptor; - - HoloAnimType(String descriptor) { - this.descriptor = descriptor; - } - - public static List descriptors() { - ArrayList descriptors = new ArrayList<>(); - - for (HoloAnimType types : values()) - descriptors.add(types.descriptor); - - return descriptors; - } - - public HoloAnimation getAsHoloAnimation(SpecializedCrates cc, DynamicHologram dh) { - switch (this) { - case SINGLELINE_CHANGE: - case TEXT_CHANGE: - return new TextChangeAnimation(cc, dh); - default: - return null; - } - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/holograms/animations/HoloAnimation.java b/src/main/java/me/ztowne13/customcrates/crates/options/holograms/animations/HoloAnimation.java deleted file mode 100644 index 2f4b345..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/holograms/animations/HoloAnimation.java +++ /dev/null @@ -1,46 +0,0 @@ -package me.ztowne13.customcrates.crates.options.holograms.animations; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.options.CHologram; -import me.ztowne13.customcrates.crates.options.holograms.DynamicHologram; - -/** - * Hologram, Animation subtype - */ -public abstract class HoloAnimation extends Animation { - protected DynamicHologram dynamicHologram; - protected CHologram holograms; - private int intTicks = 0; - - public HoloAnimation(SpecializedCrates instance, DynamicHologram dynamicHologram) { - super(instance); - this.dynamicHologram = dynamicHologram; - this.holograms = dynamicHologram.getPlacedCrate().getHologram(); - } - - public int getIntTicks() { - return intTicks; - } - - public void setIntTicks(int intTicks) { - this.intTicks = intTicks; - } - - public DynamicHologram getDynamicHologram() { - return dynamicHologram; - } - - public void setDynamicHologram(DynamicHologram dynamicHologram) { - this.dynamicHologram = dynamicHologram; - } - - public CHologram getHolograms() { - return holograms; - } - - public void setHolograms(CHologram holograms) { - this.holograms = holograms; - } - - -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/holograms/animations/MultiLineChangeAnimation.java b/src/main/java/me/ztowne13/customcrates/crates/options/holograms/animations/MultiLineChangeAnimation.java deleted file mode 100644 index 2d89e28..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/holograms/animations/MultiLineChangeAnimation.java +++ /dev/null @@ -1,70 +0,0 @@ -package me.ztowne13.customcrates.crates.options.holograms.animations; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.options.holograms.DynamicHologram; -import me.ztowne13.customcrates.utils.ChatUtils; - -/** - * Created by ztowne13 on 1/16/17. - */ -public class MultiLineChangeAnimation extends HoloAnimation { - private String last = ""; - private int count = 0; - - public MultiLineChangeAnimation(SpecializedCrates instance, DynamicHologram dynamicHologram) { - super(instance, dynamicHologram); - } - - @Override - public void tick() { - setIntTicks(getIntTicks() + 1); - if (getIntTicks() == getHolograms().getSpeed()) { - setIntTicks(0); - if (!getDynamicHologram().getDisplayingRewardHologram()) { - update(); - } - } - } - - public void update() { - update(false); - } - - @Override - public void update(boolean force) { - if (count >= getHolograms().getPrefixes().size()) { - count = 0; - } - - String s = getHolograms().getPrefixes().get(count); - - - for (int i = 0; i < getHolograms().getLines().size(); i++) { - try { - String currentLine = getHolograms().getLines().get(i); - currentLine = s + currentLine; - if (!getLast().equals(s)) { - getDynamicHologram().setLine(i, ChatUtils.toChatColor(currentLine)); - } - } catch (Exception exc) { - break; - } - } - - setLast(s); - count++; - } - - @Override - public void stop() { - // EMPTY - } - - public String getLast() { - return last; - } - - public void setLast(String last) { - this.last = last; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/holograms/animations/TextChangeAnimation.java b/src/main/java/me/ztowne13/customcrates/crates/options/holograms/animations/TextChangeAnimation.java deleted file mode 100644 index c1c2d8e..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/holograms/animations/TextChangeAnimation.java +++ /dev/null @@ -1,67 +0,0 @@ -package me.ztowne13.customcrates.crates.options.holograms.animations; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.options.holograms.DynamicHologram; -import me.ztowne13.customcrates.utils.ChatUtils; - -/** - * Animation that modifies the hologram text directly to what was configured in the config - */ -public class TextChangeAnimation extends HoloAnimation { - private String last = ""; - private int count = 0; - - public TextChangeAnimation(SpecializedCrates instance, DynamicHologram dynamicHologram) { - super(instance, dynamicHologram); - } - - @Override - public void tick() { - // One line is needed to be replaced, if it doesn't exist: add it. - if (dynamicHologram.getPlacedCrate().getHologram().getLineCount() == 0) { - dynamicHologram.getPlacedCrate().getHologram().setLineCount(dynamicHologram.getPlacedCrate().getHologram().getLineCount() + 1); - dynamicHologram.getPlacedCrate().getHologram().addLine(""); - } - - setIntTicks(getIntTicks() + 1); - if (getIntTicks() == getHolograms().getSpeed()) { - setIntTicks(0); - if (!getDynamicHologram().getDisplayingRewardHologram()) { - update(); - } - } - } - - public void update() { - update(false); - } - - @Override - public void update(boolean force) { - if (count >= getHolograms().getPrefixes().size()) { - count = 0; - } - - String s = getHolograms().getPrefixes().get(count); - - if (!getLast().equals(s) || force) { - getDynamicHologram().setLine(0, ChatUtils.toChatColor(s)); - } - - setLast(s); - count++; - } - - @Override - public void stop() { - // EMPTY - } - - public String getLast() { - return last; - } - - public void setLast(String last) { - this.last = last; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/particles/BukkitParticleEffect.java b/src/main/java/me/ztowne13/customcrates/crates/options/particles/BukkitParticleEffect.java deleted file mode 100644 index 3100d8c..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/particles/BukkitParticleEffect.java +++ /dev/null @@ -1,97 +0,0 @@ -package me.ztowne13.customcrates.crates.options.particles; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.utils.LocationUtils; -import me.ztowne13.customcrates.utils.Utils; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Particle; -import org.bukkit.entity.Player; - -import java.util.Random; - -/** - * Created by ztowne13 on 6/24/16. - */ -public class BukkitParticleEffect extends ParticleData { - private final Random random; - private Particle particle; - - public BukkitParticleEffect(SpecializedCrates sc, String particleName, String name, boolean hasAnimation) { - this(sc, Particle.valueOf(particleName.toUpperCase()), name, hasAnimation); - } - - public BukkitParticleEffect(SpecializedCrates sc, Particle particle, String name, boolean hasAnimation) { - super(sc, name, hasAnimation); - this.particle = particle; - random = new Random(); - } - - @Override - public void display(Location l) { - Location centered; - int amnt; - float offX; - float offY; - float offZ; - float speed; - - if (isHasAnimation()) { - centered = LocationUtils.getLocationCentered(l); - amnt = 1; - offX = offY = offZ = 0; - speed = 0; - } else { - centered = LocationUtils.getLocationCentered(l).add(getCenterX(), getCenterY(), getCenterZ()); - amnt = getAmount(); - offX = getRangeX(); - offY = getRangeY(); - offZ = getRangeZ(); - speed = getSpeed(); - } - - if ((particle.equals(Particle.SPELL_MOB) || particle.equals(Particle.SPELL_MOB_AMBIENT) || - particle.equals(Particle.NOTE)) && isHasColor() && isColorEnabled()) { - // Artificial 'offset' - if (!isHasAnimation()) { - float randX = (random.nextFloat() >= .5 ? 1 : -1) * random.nextFloat() * offX; - float randY = (random.nextFloat() >= .5 ? 1 : -1) * random.nextFloat() * offY; - float randZ = (random.nextFloat() >= .5 ? 1 : -1) * random.nextFloat() * offZ; - - centered.add(randX, randY, randZ); - } - - for (int i = 0; i < amnt; i++) - spawnParticle(centered, 0, getColorRed() / 255.0, getColorGreen() / 255.0, getColorBlue() / 255.0, 1); - } else - spawnParticle(centered, amnt, offX, offY, offZ, speed); - } - - @Override - public boolean setParticle(String particleName) { - try { - particle = Particle.valueOf(particleName.toUpperCase()); - return true; - } catch (Exception exc) { - return false; - } - } - - @Override - public String getParticleName() { - return particle.name(); - } - - public void spawnParticle(Location centeredLoc, int amnt, double offX, double offY, double offZ, float speed) { - - for (Player player : Bukkit.getOnlinePlayers()) { - if (Utils.isPlayerInRange(instance, player, centeredLoc)) { - if (particle.equals(Particle.REDSTONE)) { - player.spawnParticle(particle, centeredLoc, amnt, offX, offY, offZ, speed, getDustOptions()); - } else { - player.spawnParticle(particle, centeredLoc, amnt, offX, offY, offZ, speed); - } - } - } - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/particles/FireworkData.java b/src/main/java/me/ztowne13/customcrates/crates/options/particles/FireworkData.java deleted file mode 100644 index 5f7e9cf..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/particles/FireworkData.java +++ /dev/null @@ -1,287 +0,0 @@ -package me.ztowne13.customcrates.crates.options.particles; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.CrateSettings; -import me.ztowne13.customcrates.interfaces.files.FileSettings; -import me.ztowne13.customcrates.interfaces.logging.StatusLoggerEvent; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.Utils; -import org.bukkit.Bukkit; -import org.bukkit.Color; -import org.bukkit.FireworkEffect; -import org.bukkit.FireworkEffect.Builder; -import org.bukkit.Location; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Firework; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.FireworkMeta; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -public class FireworkData { - private final SpecializedCrates instance; - private CrateSettings crateSettings; - - private String unLoaded; - private String id; - - private Builder effect; - private int power = 1; - - private List colors = new ArrayList<>(); - private List fadeColors = new ArrayList<>(); - private boolean trail = false; - private boolean flicker = false; - private FireworkEffect.Type feType = FireworkEffect.Type.BALL_LARGE; - - public FireworkData(SpecializedCrates instance, CrateSettings crateSettings) { - this.instance = instance; - this.crateSettings = crateSettings; - this.id = UUID.randomUUID().toString().substring(0, 8); - } - - public boolean loadFromFirework(ItemStack stack) { - FireworkMeta fm = (FireworkMeta) stack.getItemMeta(); - setEffect(FireworkEffect.builder()); - power = fm.getPower(); - for (FireworkEffect ef : fm.getEffects()) { - flicker = ef.hasFlicker(); - effect.flicker(flicker); - - trail = ef.hasTrail(); - effect.trail(trail); - - for (Color c : ef.getColors()) { - colors.add(c.asRGB() + ""); - effect.withColor(c); - } - - for (Color c : ef.getFadeColors()) { - fadeColors.add(c.asRGB() + ""); - effect.withFade(c); - } - - if (ef.getType() != null) { - feType = ef.getType(); - } - effect.with(feType); - } - - if (colors.isEmpty()) { - return false; - } - - unLoaded = asString(); - return true; - } - - public void load(String s) { - String[] args = ChatUtils.stripFromWhitespace(s).split(FileSettings.SPLITTER_1); - setEffect(FireworkEffect.builder()); - - unLoaded = s; - - try { - String[] splitArgs0 = args[0].split(FileSettings.SPLITTER_2); - for (String colorUnParsed : splitArgs0) { - if (colorUnParsed.equalsIgnoreCase("")) { - continue; - } - - try { - if (Utils.getColorFromString(colorUnParsed) != null) { - Color c = Utils.getColorFromString(colorUnParsed); - colors.add(colorUnParsed); - getEffect().withColor(c); - } else { - Color c = Color.fromRGB(Integer.parseInt(colorUnParsed)); - colors.add(colorUnParsed); - getEffect().withColor(c); - } - } catch (Exception exc) { - StatusLoggerEvent.FIREWORK_DATA_INVALIDCOLOR - .log(getCrateSettings().getCrate(), s, colorUnParsed, "color"); - } - } - - for (String colorUnParsed : args[1].split(";")) { - if (colorUnParsed.equalsIgnoreCase("")) { - continue; - } - - try { - if (Utils.getColorFromString(colorUnParsed) != null) { - Color c = Utils.getColorFromString(colorUnParsed); - fadeColors.add(colorUnParsed); - getEffect().withFade(c); - } else { - Color c = Color.fromRGB(Integer.parseInt(colorUnParsed)); - fadeColors.add(colorUnParsed); - getEffect().withFade(c); - } - } catch (Exception exc) { - StatusLoggerEvent.FIREWORK_DATA_INVALIDCOLOR - .log(getCrateSettings().getCrate(), s, colorUnParsed, "fade"); - } - } - - String cause = args[2] + " is not true / false."; - - try { - Boolean b = Boolean.valueOf(args[2].toLowerCase()); - getEffect().trail(b); - trail = b; - - cause = "Improperly formatted FLICKER"; - cause = args[3] + " is not true / false."; - - b = Boolean.valueOf(args[3].toLowerCase()); - getEffect().flicker(b); - flicker = b; - - cause = "Improperly formatted TYPE"; - cause = args[4] + " is not a valid Firework Effect Type."; - - FireworkEffect.Type ft = FireworkEffect.Type.valueOf(args[4].toUpperCase()); - getEffect().with(ft); - feType = ft; - - cause = "Improperly formatted POWER"; - cause = args[5] + " is not a valid number / power."; - setPower(Integer.valueOf(args[5])); - - StatusLoggerEvent.FIREWORK_DATA_SUCCESS.log(getCrateSettings().getCrate(), s); - } catch (Exception exc) { - StatusLoggerEvent.FIREWORK_DATA_PARTIALSUCCESS.log(getCrateSettings().getCrate(), s, cause); - } - } catch (Exception exc) { - StatusLoggerEvent.FIREWORK_DATA_FAILURE.log(getCrateSettings().getCrate(), s); - } - - } - - public void play(Location l) { - final Firework fw = (Firework) l.getWorld().spawnEntity(l, EntityType.FIREWORK); - FireworkMeta fm = fw.getFireworkMeta(); - fw.setCustomName("scf"); - fw.setCustomNameVisible(false); - fm.addEffect(getEffect().build()); - fm.setPower(getPower()); - fw.setFireworkMeta(fm); - - if (getPower() == 0) { - Bukkit.getScheduler().scheduleSyncDelayedTask(instance, fw::detonate, 2); - } - } - - // Formatted color;color, fade color;fade color, trail?, flicker?, effect type, power - public String asString() { - String serializedFw = ""; - for (String color : getColors()) { - serializedFw = color + ";"; - } - - if (getColors().isEmpty()) { - serializedFw += ";"; - } - serializedFw = serializedFw.substring(0, serializedFw.length() - 1) + ", "; - - for (String color : getFadeColors()) { - serializedFw = color + ";"; - } - - if (getFadeColors().isEmpty()) { - serializedFw += ";"; - } - - serializedFw = serializedFw.substring(0, serializedFw.length() - 1); - serializedFw += ", " + isTrail(); - serializedFw += ", " + isFlicker(); - serializedFw += ", " + getFeType().name(); - serializedFw += ", " + getPower(); - - return serializedFw; - } - - public boolean equals(FireworkData fd) { - return fd.toString().equalsIgnoreCase(toString()); - } - - public String toString() { - return unLoaded; - } - - public CrateSettings getCrateSettings() { - return crateSettings; - } - - public void setCrateSettings(CrateSettings crateSettings) { - this.crateSettings = crateSettings; - } - - public Builder getEffect() { - return effect; - } - - public void setEffect(Builder effect) { - this.effect = effect; - } - - public int getPower() { - return power; - } - - public void setPower(int power) { - this.power = power; - } - - public boolean isTrail() { - return trail; - } - - public void setTrail(boolean trail) { - this.trail = trail; - } - - public boolean isFlicker() { - return flicker; - } - - public void setFlicker(boolean flicker) { - this.flicker = flicker; - } - - public FireworkEffect.Type getFeType() { - return feType; - } - - public void setFeType(FireworkEffect.Type feType) { - this.feType = feType; - } - - public List getColors() { - return colors; - } - - public void setColors(List colors) { - this.colors = colors; - } - - public List getFadeColors() { - return fadeColors; - } - - public void setFadeColors(List fadeColors) { - this.fadeColors = fadeColors; - } - - public String getId() { - return id; - } - - public void setId(String id) { - this.id = id; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/particles/NMSParticleEffect.java b/src/main/java/me/ztowne13/customcrates/crates/options/particles/NMSParticleEffect.java deleted file mode 100644 index 81632d1..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/particles/NMSParticleEffect.java +++ /dev/null @@ -1,62 +0,0 @@ -package me.ztowne13.customcrates.crates.options.particles; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.LocationUtils; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -/** - * Created by ztowne13 on 6/24/16. - */ -public class NMSParticleEffect extends ParticleData { - private ParticleEffect particleEffect; - - public NMSParticleEffect(SpecializedCrates instance, ParticleEffect particleEffect, String name, boolean hasAnimation) { - super(instance, name, hasAnimation); - this.particleEffect = particleEffect; - } - - @Override - public void display(Location l) { - try { - Location centered; - int amnt = getAmount(); - float offX, offY, offZ, speed; - - if (isHasAnimation()) { - centered = LocationUtils.getLocationCentered(l); - offX = offY = offZ = 0; - speed = 0; - } else { - centered = LocationUtils.getLocationCentered(l).add(getCenterX(), getCenterY(), getCenterZ()); - offX = getRangeX(); - offY = getRangeY(); - offZ = getRangeZ(); - speed = getSpeed(); - } - - for (Player p : Bukkit.getOnlinePlayers()) { - particleEffect.sendToPlayer(instance, p, centered, offX, offY, offZ, speed, amnt); - } - } catch (IllegalArgumentException e) { - ChatUtils.log(new String[]{"Error loading particle: " + particleEffect.name()}); - } - } - - @Override - public boolean setParticle(String particleName) { - try { - particleEffect = ParticleEffect.valueOf(particleName); - return true; - } catch (Exception exc) { - return false; - } - } - - @Override - public String getParticleName() { - return particleEffect.name(); - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/particles/ParticleData.java b/src/main/java/me/ztowne13/customcrates/crates/options/particles/ParticleData.java deleted file mode 100644 index 776a7d1..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/particles/ParticleData.java +++ /dev/null @@ -1,220 +0,0 @@ -package me.ztowne13.customcrates.crates.options.particles; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.options.particles.effects.PEAnimationType; -import me.ztowne13.customcrates.crates.options.particles.effects.ParticleAnimationEffect; -import me.ztowne13.customcrates.interfaces.files.FileHandler; -import org.bukkit.Location; -import org.bukkit.Particle; -import org.bukkit.configuration.file.FileConfiguration; - -public abstract class ParticleData { - protected final SpecializedCrates instance; - - private String name; - private float rangeX; - private float rangeY; - private float rangeZ; - private float centerX; - private float centerY; - private float centerZ; - private float speed; - private boolean hasAnimation; - private boolean hasColor; - private int amount; - private int colorRed; - private int colorGreen; - private int colorBlue; - private float size; - private boolean colorEnabled; - - private Particle.DustOptions dustOptions; - - private ParticleAnimationEffect particleAnimationEffect; - - public ParticleData(SpecializedCrates instance, String name, boolean hasAnimation) { - this.instance = instance; - this.name = name; - this.hasAnimation = hasAnimation; - - this.rangeX = this.rangeY = this.rangeZ = 1; - this.centerX = this.centerY = this.centerZ = 0; - this.amount = 1; - this.speed = isHasAnimation() ? 20 : 0; - } - - public abstract void display(Location l); - - public abstract String getParticleName(); - - public abstract boolean setParticle(String particleName); - - public float getRangeX() { - return rangeX; - } - - public void setRangeX(float rangeX) { - this.rangeX = rangeX; - } - - public void save(FileHandler fileHandler, String path) { - FileConfiguration fc = fileHandler.get(); - fc.set(path + "." + getName() + ".type", getParticleName()); - fc.set(path + "." + getName() + ".range-x", getRangeX()); - fc.set(path + "." + getName() + ".range-y", getRangeY()); - fc.set(path + "." + getName() + ".range-z", getRangeZ()); - fc.set(path + "." + getName() + ".center-x", getCenterX()); - fc.set(path + "." + getName() + ".center-y", getCenterY()); - fc.set(path + "." + getName() + ".center-z", getCenterZ()); - fc.set(path + "." + getName() + ".speed", getSpeed()); - fc.set(path + "." + getName() + ".amount", getAmount()); - - if (getParticleAnimationEffect() != null) - fileHandler.get().set(path + "." + getName() + ".animation", - PEAnimationType.getFromParticleAnimationEffect(getParticleAnimationEffect()).name()); - else - fileHandler.get().set(path + "." + getName() + ".animation", "NONE"); - - fc.set(path + "." + getName() + ".color.enabled", isColorEnabled()); - fc.set(path + "." + getName() + ".color.red", getColorRed()); - fc.set(path + "." + getName() + ".color.green", getColorGreen()); - fc.set(path + "." + getName() + ".color.blue", getColorBlue()); - fc.set(path + "." + getName() + ".redstone-size", getSize() == 0 ? null : getSize()); - } - - public float getRangeY() { - return rangeY; - } - - public void setRangeY(float rangeY) { - this.rangeY = rangeY; - } - - public float getRangeZ() { - return rangeZ; - } - - public void setRangeZ(float rangeZ) { - this.rangeZ = rangeZ; - } - - public float getSpeed() { - return speed; - } - - public void setSpeed(float speed) { - this.speed = speed; - } - - public int getAmount() { - return amount; - } - - public void setAmount(int amount) { - this.amount = amount; - } - - public boolean isHasAnimation() { - return hasAnimation; - } - - public void setHasAnimation(boolean hasAnimation) { - this.hasAnimation = hasAnimation; - } - - public ParticleAnimationEffect getParticleAnimationEffect() { - return particleAnimationEffect; - } - - public void setParticleAnimationEffect(ParticleAnimationEffect particleAnimationEffect) { - this.particleAnimationEffect = particleAnimationEffect; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public float getCenterX() { - return centerX; - } - - public void setCenterX(float centerX) { - this.centerX = centerX; - } - - public float getCenterY() { - return centerY; - } - - public void setCenterY(float centerY) { - this.centerY = centerY; - } - - public float getCenterZ() { - return centerZ; - } - - public void setCenterZ(float centerZ) { - this.centerZ = centerZ; - } - - public Particle.DustOptions getDustOptions() { - return dustOptions; - } - - public void setDustOptions(Particle.DustOptions dustOptions) { - this.dustOptions = dustOptions; - } - - public int getColorRed() { - return colorRed; - } - - public void setColorRed(int colorRed) { - this.colorRed = colorRed; - } - - public int getColorGreen() { - return colorGreen; - } - - public void setColorGreen(int colorGreen) { - this.colorGreen = colorGreen; - } - - public int getColorBlue() { - return colorBlue; - } - - public void setColorBlue(int colorBlue) { - this.colorBlue = colorBlue; - } - - public float getSize() { - return size; - } - - public void setSize(float size) { - this.size = size; - } - - public boolean isHasColor() { - return hasColor; - } - - public void setHasColor(boolean hasColor) { - this.hasColor = hasColor; - } - - public boolean isColorEnabled() { - return colorEnabled; - } - - public void setColorEnabled(boolean colorEnabled) { - this.colorEnabled = colorEnabled; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/particles/ParticleEffect.java b/src/main/java/me/ztowne13/customcrates/crates/options/particles/ParticleEffect.java deleted file mode 100644 index 51ca5da..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/particles/ParticleEffect.java +++ /dev/null @@ -1,203 +0,0 @@ -package me.ztowne13.customcrates.crates.options.particles; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.utils.ReflectionUtilities; -import me.ztowne13.customcrates.utils.Utils; -import me.ztowne13.customcrates.utils.VersionUtils; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; - -public enum ParticleEffect { - - HUGE_EXPLOSION("hugeexplosion", "EXPLOSION_HUGE"), - - LARGE_EXPLODE("largeexplode", "EXPLOSION_LARGE"), - - BUBBLE("bubble", "WATER_BUBBLE"), - - SUSPEND("suspend", "SUSPENDED"), - - DEPTH_SUSPEND("depthSuspend", "SUSPENDED_DEPTH"), - - MAGIC_CRIT("magicCrit", "CRIT_MAGIC"), - - MOB_SPELL("mobSpell", "SPELL_MOB"), - - MOB_SPELL_AMBIENT("mobSpellAmbient", "SPELL_MOB_AMBIENT"), - - INSTANT_SPELL("instantSpell", "SPELL_INSTANT"), - - WITCH_MAGIC("witchMagic", "SPELL_WITCH"), - - EXPLODE("explode", "EXPLOSION_NORMAL"), - - SPLASH("splash", "WATER_SPLASH"), - - LARGE_SMOKE("largesmoke", "SMOKE_LARGE"), - - RED_DUST("reddust", "REDSTONE"), - - SNOWBALL_POOF("snowballpoof", "SNOWBALL"), - - ANGRY_VILLAGER("angryVillager", "VILLAGER_ANGRY"), - - HAPPY_VILLAGER("happerVillager", "VILLAGER_HAPPY"), - - EXPLOSION_NORMAL(EXPLODE.getName()), - - EXPLOSION_LARGE(LARGE_EXPLODE.getName()), - - EXPLOSION_HUGE(HUGE_EXPLOSION.getName()), - - FIREWORKS_SPARK("fireworksSpark"), - - WATER_BUBBLE(BUBBLE.getName()), - - WATER_SPLASH(SPLASH.getName()), - - WATER_WAKE, - - SUSPENDED(SUSPEND.getName()), - - SUSPENDED_DEPTH(DEPTH_SUSPEND.getName()), - - CRIT("crit"), - - CRIT_MAGIC(MAGIC_CRIT.getName()), - - SMOKE_NORMAL, - - SMOKE_LARGE(LARGE_SMOKE.getName()), - - SPELL("spell"), - - SPELL_INSTANT(INSTANT_SPELL.getName()), - - SPELL_MOB(MOB_SPELL.getName()), - - SPELL_MOB_AMBIENT(MOB_SPELL_AMBIENT.getName()), - - SPELL_WITCH(WITCH_MAGIC.getName()), - - DRIP_WATER("dripWater"), - - DRIP_LAVA("dripLava"), - - VILLAGER_ANGRY(ANGRY_VILLAGER.getName()), - - VILLAGER_HAPPY(HAPPY_VILLAGER.getName()), - - TOWN_AURA("townaura"), - - NOTE("note"), - - PORTAL("portal"), - - ENCHANTMENT_TABLE("enchantmenttable"), - - FLAME("flame"), - - LAVA("lave"), - - FOOTSTEP("footstep"), - - CLOUD("cloud"), - - REDSTONE("reddust"), - - SNOWBALL("snowballpoof"), - - SNOW_SHOVEL("snowshovel"), - - SLIME("slime"), - - HEART("heart"), - - BARRIER, - - DRAGON_BREATH("dragonbreath"), - - DAMAGE_INDICATOR("damageIndicator"), - - SWEEP_ATTACK("sweepAttack"), - - END_ROD("endRod"), - - FALLING_DUST("fallingDust"), - - ITEM_CRACK, - - BLOCK_CRACK, - - BLOCK_DUST, - - WATER_DROP, - - ITEM_TAKE, - - MOB_APPEARANCE; - - private static final Class nmsPacketPlayOutParticle; - private static final Class nmsEnumParticle; - private static final Method nmsEnumParticleMethod; - private static Constructor cachedConstructor = null; - - static { - nmsEnumParticle = ReflectionUtilities.getNMSClass("EnumParticle"); - nmsPacketPlayOutParticle = ReflectionUtilities.getNMSClass("PacketPlayOutWorldParticles"); - nmsEnumParticleMethod = ReflectionUtilities.getMethod(nmsEnumParticle, "valueOf", String.class); - try { - cachedConstructor = nmsPacketPlayOutParticle.getConstructor( - nmsEnumParticle, Boolean.TYPE, Float.TYPE, Float.TYPE, Float.TYPE, Float.TYPE, - Float.TYPE, Float.TYPE, Float.TYPE, Integer.TYPE, int[].class); - } catch (NoSuchMethodException e) { - // IGNORED - } - } - - private final String particleName; - private final String enumValue; - private Object cachedEnum; - - ParticleEffect(String particleName, String enumValue) { - this.particleName = particleName; - this.enumValue = enumValue; - } - - ParticleEffect(String particleName) { - this(particleName, null); - } - - ParticleEffect() { - this(null, null); - } - - public String getName() { - return this.particleName; - } - - public void sendToPlayer(SpecializedCrates sc, Player player, Location location, float offsetX, float offsetY, float offsetZ, float speed, - int count) { - if (!Utils.isPlayerInRange(sc, player, location)) { - return; - } - if (!VersionUtils.getServerVersion().contains("v1_7")) { - try { - if (cachedEnum != null) { - cachedEnum = nmsEnumParticleMethod.invoke(null, this.enumValue != null ? this.enumValue : name()); - } - Object packet = cachedConstructor.newInstance(cachedEnum, true, - (float) location.getX(), (float) location.getY(), (float) location.getZ(), offsetX, offsetY, - offsetZ, speed, count, new int[0]); - Object handle = ReflectionUtilities.getHandle(player); - Object connection = ReflectionUtilities.getField(handle.getClass(), "playerConnection").get(handle); - ReflectionUtilities.getMethod(connection.getClass(), "sendPacket").invoke(connection, packet); - } catch (Exception e) { - throw new IllegalArgumentException("Unable to send Particle " + name() + ". (Version 1.8 / 1.9)"); - } - } - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/particles/effects/CirclePA.java b/src/main/java/me/ztowne13/customcrates/crates/options/particles/effects/CirclePA.java deleted file mode 100644 index 65b54b4..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/particles/effects/CirclePA.java +++ /dev/null @@ -1,50 +0,0 @@ -package me.ztowne13.customcrates.crates.options.particles.effects; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.options.particles.ParticleData; -import org.bukkit.Location; - -/** - * Created by ztowne13 on 6/25/16. - */ -public class CirclePA extends ParticleAnimationEffect { - private final int updatesPerSec; - - public CirclePA(SpecializedCrates instance, ParticleData particleData) { - super(instance, particleData); - this.updatesPerSec = (int) particleData.getSpeed(); - } - - @Override - public void update() { - toDisplay.clear(); - - totalTick += updatesPerSec; - tick += updatesPerSec; - - double radius = particleData.getRangeX(); - double yOffset = particleData.getRangeY(); - double height = particleData.getRangeZ(); - - int i = tick; - while (i < tick + updatesPerSec) { - if (i % (2 + particleData.getAmount()) == 0) { - double toX = Math.sin(Math.toRadians(i)) * radius; - double toY = Math.cos(Math.toRadians(i)) * radius; - - double formattedHeight = height / 10; - for (double add = 0; add < formattedHeight; add += .1) { - Location newL = new Location(null, toX, add + yOffset, toY); - toDisplay.add(newL); - } - - if (i > 360) { - i = 1; - tick = 0; - } - } - i++; - } - - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/particles/effects/DoubleSpiralPA.java b/src/main/java/me/ztowne13/customcrates/crates/options/particles/effects/DoubleSpiralPA.java deleted file mode 100644 index aeb8b1a..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/particles/effects/DoubleSpiralPA.java +++ /dev/null @@ -1,64 +0,0 @@ -package me.ztowne13.customcrates.crates.options.particles.effects; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.options.particles.ParticleData; -import org.bukkit.Location; - -/** - * Created by ztowne13 on 6/25/16. - */ -public class DoubleSpiralPA extends ParticleAnimationEffect { - private final int updatesPerSec; - - private int extraTick = 0; - private double toChangeHeight = 0; - private double currentYOffset = 0; - - public DoubleSpiralPA(SpecializedCrates instance, ParticleData particleData) { - super(instance, particleData); - this.updatesPerSec = (int) particleData.getSpeed(); - } - - @Override - public void update() { - - toDisplay.clear(); - - totalTick += updatesPerSec; - tick += updatesPerSec; - - double radius = particleData.getRangeX(); - double yOffset = particleData.getRangeY(); - double height = particleData.getRangeZ(); - - int degrees = 360; // MODIFY THIS - if (toChangeHeight == 0 && height != 0) { - toChangeHeight = height / degrees; - } - - int i = tick; - while (i < tick + updatesPerSec) { - currentYOffset += toChangeHeight; - if (i % (2 + particleData.getAmount()) == 0) { - double toX = Math.sin(Math.toRadians(i)) * radius; - double toY = Math.cos(Math.toRadians(i)) * radius; - - Location newL = new Location(null, toX, currentYOffset + yOffset, toY); - toDisplay.add(newL); - Location newL2 = new Location(null, -toX, currentYOffset + yOffset, -toY); - toDisplay.add(newL2); - - if (i > degrees + extraTick) { - extraTick = 0; //extraTick == 180 ? 0 : 180; - i = extraTick + 1; - tick = extraTick; - } - - if ((currentYOffset > height && toChangeHeight > 0) || (currentYOffset < 0 && toChangeHeight < 0)) { - toChangeHeight = -toChangeHeight; - } - } - i++; - } - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/particles/effects/GrowingSpiralPA.java b/src/main/java/me/ztowne13/customcrates/crates/options/particles/effects/GrowingSpiralPA.java deleted file mode 100644 index 07b0009..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/particles/effects/GrowingSpiralPA.java +++ /dev/null @@ -1,71 +0,0 @@ -package me.ztowne13.customcrates.crates.options.particles.effects; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.options.particles.ParticleData; -import org.bukkit.Location; - -/** - * Created by ztowne13 on 6/26/16. - */ -public class GrowingSpiralPA extends ParticleAnimationEffect { - private final int updatesPerSec; - - private double toChangeHeight = 0; - private double currentYOffset = 0; - private double toChangeRadius = 0; - private double currentRadius = 0; - - public GrowingSpiralPA(SpecializedCrates instance, ParticleData particleData) { - super(instance, particleData); - this.updatesPerSec = (int) particleData.getSpeed(); - } - - @Override - public void update() { - toDisplay.clear(); - - totalTick += updatesPerSec; - tick += updatesPerSec; - - double radius = particleData.getRangeX(); - double yOffset = particleData.getRangeY(); - double height = particleData.getRangeZ(); - - int degrees = 540; // MODIFY THIS - if (toChangeHeight == 0 && height != 0) { - toChangeHeight = height / degrees; - } - - if (toChangeRadius == 0) { - currentRadius = radius; - toChangeRadius = -(radius / degrees); - } - - int i = tick; - while (i < tick + updatesPerSec) { - currentYOffset += toChangeHeight; - currentRadius += toChangeRadius; - if (i % (2 + particleData.getAmount()) == 0) { - double toX = Math.sin(Math.toRadians(i)) * currentRadius; - double toY = Math.cos(Math.toRadians(i)) * currentRadius; - - Location newL = new Location(null, toX, currentYOffset + yOffset, toY); - Location newL2 = new Location(null, -toX, currentYOffset + yOffset, -toY); - - toDisplay.add(newL); - toDisplay.add(newL2); - - if (i > degrees) { - i = 1; - tick = 0; - } - - if ((currentYOffset > height && toChangeHeight > 0) || (currentYOffset < 0 && toChangeHeight < 0)) { - toChangeHeight = -toChangeHeight; - toChangeRadius = -toChangeRadius; - } - } - i++; - } - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/particles/effects/OffsetTiltedRingsPA.java b/src/main/java/me/ztowne13/customcrates/crates/options/particles/effects/OffsetTiltedRingsPA.java deleted file mode 100644 index 04dae0f..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/particles/effects/OffsetTiltedRingsPA.java +++ /dev/null @@ -1,69 +0,0 @@ -package me.ztowne13.customcrates.crates.options.particles.effects; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.options.particles.ParticleData; -import org.bukkit.Location; - -/** - * Created by ztowne13 on 6/27/16. - */ -public class OffsetTiltedRingsPA extends ParticleAnimationEffect { - private final int updatesPerSec; - - public OffsetTiltedRingsPA(SpecializedCrates instance, ParticleData particleData) { - super(instance, particleData); - this.updatesPerSec = (int) particleData.getSpeed(); - } - - @Override - public void update() { - toDisplay.clear(); - - totalTick += updatesPerSec; - tick += updatesPerSec; - - double radius = particleData.getRangeX(); - double yOffset = particleData.getRangeY(); - double rotation = particleData.getRangeZ(); - - double rotateInRadians = Math.toRadians(rotation); - - for (int i = tick; i < tick + updatesPerSec; i++) { - int iTemp = i; - if (i % (2 + particleData.getAmount()) == 0) { - i = iTemp; - double x = Math.sin(Math.toRadians(i)) * radius; - double y = Math.cos(Math.toRadians(i)) * radius; - - double toX = (x * Math.cos(rotateInRadians)) - (y * Math.sin(rotateInRadians)); - double toY = (x * Math.sin(rotateInRadians)) + (y * Math.cos(rotateInRadians)); - - double tilt = Math.cos(Math.toRadians(i)) * radius; - - Location newL = new Location(null, toX, yOffset + tilt, -toY); - toDisplay.add(newL); - - i = -iTemp; - - x = Math.sin(Math.toRadians(i)) * radius; - y = Math.cos(Math.toRadians(i)) * radius; - - toX = (x * Math.cos(rotateInRadians)) - (y * Math.sin(rotateInRadians)); - toY = (x * Math.sin(rotateInRadians)) + (y * Math.cos(rotateInRadians)); - - tilt = Math.cos(Math.toRadians(i)) * radius; - - newL = new Location(null, toX, yOffset - tilt, -toY); - toDisplay.add(newL); - - if (i > 360) { - i = 1; - tick = 0; - } - - } - - i = iTemp; - } - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/particles/effects/PEAnimationType.java b/src/main/java/me/ztowne13/customcrates/crates/options/particles/effects/PEAnimationType.java deleted file mode 100644 index c629e75..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/particles/effects/PEAnimationType.java +++ /dev/null @@ -1,58 +0,0 @@ -package me.ztowne13.customcrates.crates.options.particles.effects; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.options.particles.ParticleData; - -/** - * Created by ztowne13 on 6/25/16. - */ -public enum PEAnimationType { - CIRCLE(CirclePA.class), - - SPIRAL(SpiralPA.class), - - DOUBLE_SPIRAL(DoubleSpiralPA.class), - - GROWING_SPIRAL(GrowingSpiralPA.class), - - TILTED_RINGS(TiltedRingsPA.class), - - OFFSET_TILTED_RINGS(OffsetTiltedRingsPA.class), - - NONE(null); - - - private final Class particleAnimationEffect; - - PEAnimationType(Class particleAnimationEffect) { - this.particleAnimationEffect = particleAnimationEffect; - } - - public static PEAnimationType getFromParticleAnimationEffect(ParticleAnimationEffect particleAnimationEffect) { - for (PEAnimationType peAnimationType : values()) { - if (particleAnimationEffect.getClass() == peAnimationType.particleAnimationEffect) { - return peAnimationType; - } - } - return null; - } - - public ParticleAnimationEffect getAnimationEffectInstance(SpecializedCrates cc, ParticleData particleData) { - switch (this) { - case CIRCLE: - return new CirclePA(cc, particleData); - case SPIRAL: - return new SpiralPA(cc, particleData); - case DOUBLE_SPIRAL: - return new DoubleSpiralPA(cc, particleData); - case GROWING_SPIRAL: - return new GrowingSpiralPA(cc, particleData); - case TILTED_RINGS: - return new TiltedRingsPA(cc, particleData); - case OFFSET_TILTED_RINGS: - return new OffsetTiltedRingsPA(cc, particleData); - default: - return null; - } - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/particles/effects/ParticleAnimationEffect.java b/src/main/java/me/ztowne13/customcrates/crates/options/particles/effects/ParticleAnimationEffect.java deleted file mode 100644 index 47e8fbc..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/particles/effects/ParticleAnimationEffect.java +++ /dev/null @@ -1,39 +0,0 @@ -package me.ztowne13.customcrates.crates.options.particles.effects; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.options.particles.ParticleData; -import org.bukkit.Location; - -import java.util.ArrayList; - - -/** - * Created by ztowne13 on 6/25/16. - */ -public abstract class ParticleAnimationEffect { - protected final SpecializedCrates instance; - protected final ParticleData particleData; - - protected final ArrayList toDisplay = new ArrayList<>(); - - protected int totalTick = 0; - protected int tick = 0; - - public ParticleAnimationEffect(SpecializedCrates instance, ParticleData particleData) { - this.instance = instance; - this.particleData = particleData; - } - - public abstract void update(); - - public void display(Location location) { - for (Location toDisplayLocation : toDisplay) { - toDisplayLocation.setWorld(location.getWorld()); - - Location modifiedL = location.clone().add(toDisplayLocation); - modifiedL.setY(modifiedL.getY() - 1); - - particleData.display(modifiedL); - } - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/particles/effects/SpiralPA.java b/src/main/java/me/ztowne13/customcrates/crates/options/particles/effects/SpiralPA.java deleted file mode 100644 index d6bbe08..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/particles/effects/SpiralPA.java +++ /dev/null @@ -1,58 +0,0 @@ -package me.ztowne13.customcrates.crates.options.particles.effects; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.options.particles.ParticleData; -import org.bukkit.Location; - -/** - * Created by ztowne13 on 6/25/16. - */ -public class SpiralPA extends ParticleAnimationEffect { - private final int updatesPerSec; - - private double toChangeHeight = 0; - private double currentYOffset = 0; - - public SpiralPA(SpecializedCrates instance, ParticleData particleData) { - super(instance, particleData); - this.updatesPerSec = (int) particleData.getSpeed(); - } - - @Override - public void update() { - toDisplay.clear(); - - totalTick += updatesPerSec; - tick += updatesPerSec; - - double radius = particleData.getRangeX(); - double yOffset = particleData.getRangeY(); - double height = particleData.getRangeZ(); - - if (toChangeHeight == 0 && height != 0) { - toChangeHeight = height / 360; - } - - int i = tick; - while (i < tick + updatesPerSec) { - if (i % (2 + particleData.getAmount()) == 0) { - currentYOffset += toChangeHeight; - double toX = Math.sin(Math.toRadians(i)) * radius; - double toY = Math.cos(Math.toRadians(i)) * radius; - - Location newL = new Location(null, toX, currentYOffset + yOffset, toY); - toDisplay.add(newL); - - if (i > 360) { - i = 1; - tick = 0; - } - - if ((currentYOffset > height && toChangeHeight > 0) || (currentYOffset < 0 && toChangeHeight < 0)) { - toChangeHeight = -toChangeHeight; - } - } - i++; - } - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/particles/effects/TiltedRingsPA.java b/src/main/java/me/ztowne13/customcrates/crates/options/particles/effects/TiltedRingsPA.java deleted file mode 100644 index 072c53c..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/particles/effects/TiltedRingsPA.java +++ /dev/null @@ -1,69 +0,0 @@ -package me.ztowne13.customcrates.crates.options.particles.effects; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.options.particles.ParticleData; -import org.bukkit.Location; - -/** - * Created by ztowne13 on 6/26/16. - */ -public class TiltedRingsPA extends ParticleAnimationEffect { - private final int updatesPerSec; - - public TiltedRingsPA(SpecializedCrates instance, ParticleData particleData) { - super(instance, particleData); - this.updatesPerSec = (int) particleData.getSpeed(); - } - - @Override - public void update() { - toDisplay.clear(); - - totalTick += updatesPerSec; - tick += updatesPerSec; - - double radius = particleData.getRangeX(); - double yOffset = particleData.getRangeY(); - double rotation = particleData.getRangeZ(); - - double rotateInRadians = Math.toRadians(rotation); - - for (int i = tick; i < tick + updatesPerSec; i++) { - int iTemp = i; - if (i % (2 + particleData.getAmount()) == 0) { - i = iTemp; - double x = Math.sin(Math.toRadians(i)) * radius; - double y = Math.cos(Math.toRadians(i)) * radius; - - double toX = (x * Math.cos(rotateInRadians)) - (y * Math.sin(rotateInRadians)); - double toY = (x * Math.sin(rotateInRadians)) + (y * Math.cos(rotateInRadians)); - - double tilt = Math.cos(Math.toRadians(i)) * radius; - - Location newL = new Location(null, toX, yOffset + tilt, -toY); - toDisplay.add(newL); - - i = 180 - iTemp; - - x = Math.sin(Math.toRadians(i)) * radius; - y = Math.cos(Math.toRadians(i)) * radius; - - toX = (x * Math.cos(rotateInRadians)) - (y * Math.sin(rotateInRadians)); - toY = (x * Math.sin(rotateInRadians)) + (y * Math.cos(rotateInRadians)); - - tilt = Math.cos(Math.toRadians(i)) * radius; - - newL = new Location(null, toX, yOffset - tilt, -toY); - toDisplay.add(newL); - - if (i > 360) { - i = 1; - tick = 0; - } - - } - - i = iTemp; - } - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/rewards/Reward.java b/src/main/java/me/ztowne13/customcrates/crates/options/rewards/Reward.java deleted file mode 100644 index 571db99..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/rewards/Reward.java +++ /dev/null @@ -1,567 +0,0 @@ -package me.ztowne13.customcrates.crates.options.rewards; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.Messages; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.options.CReward; -import me.ztowne13.customcrates.interfaces.files.FileHandler; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.interfaces.items.SaveableItemBuilder; -import me.ztowne13.customcrates.interfaces.logging.StatusLoggerEvent; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.Utils; -import org.bukkit.Bukkit; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.inventory.meta.ItemMeta; - -import java.math.BigDecimal; -import java.text.DecimalFormat; -import java.util.ArrayList; -import java.util.List; -import java.util.Random; - -public class Reward implements Comparable { - private final SpecializedCrates instance; - private final Random random; - private FileConfiguration fileConfiguration; - private CReward rewards; - private String rewardName; - private String rarity = "default"; - private boolean giveDisplayItem; - private boolean giveDisplayItemLore = true; - private boolean giveDisplayItemName = true; - - private ItemBuilder displayBuilder; - private SaveableItemBuilder saveBuilder; - - private double chance; - private List commands; - private int totalUses; - private boolean needsMoreConfig; - - private String fallbackRewardName = ""; - private String fallbackPermission = ""; - - private boolean toLog; - - public Reward(SpecializedCrates instance, String rewardName) { - init(); - needsMoreConfig = true; - this.instance = instance; - setRewardName(rewardName); - saveBuilder = new SaveableItemBuilder(XMaterial.STONE, 1); - saveBuilder.setDisplayName(rewardName); - displayBuilder = new ItemBuilder(saveBuilder); - giveDisplayItem = true; - this.random = new Random(); - } - - public Reward(SpecializedCrates instance, CReward rewards, String rewardName) { - this(instance, rewardName); - init(); - this.rewards = rewards; - toLog = true; - loadChance(); - } - - @Override - public int compareTo(Reward otherReward) { - return (int) (getChance() * 10000 - otherReward.getChance() * 10000); - } - - public void init() { - commands = new ArrayList<>(); - needsMoreConfig = false; - toLog = false; - chance = -1; - } - - public void giveRewardToPlayer(Player p) { - // Fallback reward - if (!fallbackRewardName.equalsIgnoreCase("") && !fallbackPermission.equalsIgnoreCase("") && - p.hasPermission(fallbackPermission)) { - if (!p.hasPermission("customcrates.admin") && !p.hasPermission("specializedcrates.admin")) { - Reward fallbackReward = CReward.getAllRewards().get(fallbackRewardName); - if (fallbackReward == null) { - ChatUtils.msgError(p, "The reward " + rewardName + " has the fallback reward " + fallbackRewardName + - ", but that reward does not exist. This message is not configurable. If you would like there to be no reward" + - " as a fallback reward, please set the fallback reward to a new reward that has no commands and does not give" + - " the player any items. A reward must have a fallback reward IF it has a fallback permission."); - } else { - fallbackReward.giveRewardToPlayer(p); - Messages.GIVEN_FALLBACK_REWARD.msgSpecified(instance, p, new String[]{"%reward%", "%fallbackreward%"}, - new String[]{getDisplayBuilder().getDisplayName(true), - fallbackReward.getDisplayBuilder().getDisplayName(true)}); - } - - return; - } else { - ChatUtils.msgInfo(p, "Normally, you would have won the fallback reward " + rewardName + - " instead, but since you have the customcrates.admin permission, you've bypassed that."); - } - } - - if (isGiveDisplayItem()) { - ItemBuilder stack = new ItemBuilder(displayBuilder); - - try { - if (!isGiveDisplayItemLore()) { - ItemMeta im = stack.getItemMeta(); - im.setLore(null); - stack.setItemMeta(im); - } - } catch (Exception exc) { - } - - if (!isGiveDisplayItemName()) { - stack.removeDisplayName(); - } - - Utils.addItemAndDropRest(p, stack.getStack()); - } - - for (String command : getCommands()) { - try { - Bukkit.dispatchCommand(Bukkit.getConsoleSender(), applyCommandPlaceHolders(p, command)); - } catch (Exception exc) { - ChatUtils - .log("PLEASE READ THIS: Specialized Crates has attempted to run a command for a reward that has produced an error. " + - "Please contact the author of the plugin who's command is run to fix the issue because THIS IS NOT A SPECIALIZED" + - "CRATES ISSUE, it is the issue of the plugin who's command was run. Command: " + command); - } - } - - //new RewardLimitEvent(this, PlayerManager.get(cc, p).getPdm().getCurrentRewardLimitUses(this), 1).addTo(PlayerManager.get(cc, p).getPdm()); - } - - public String applyCommandPlaceHolders(Player p, String cmd) { - cmd = cmd.replace("%player%", p.getName()); - cmd = cmd.replace("%name%", p.getName()); - cmd = cmd.replace("%playername%", p.getName()); - cmd = cmd.replace("{name}", p.getName()); - - if (cmd.contains("%amount")) { - String[] args = cmd.split("%amount"); - - for (int i = 1; i < args.length; i++) { - boolean firstVal = true; - StringBuilder firstNum = new StringBuilder(); - StringBuilder secondNum = new StringBuilder(); - - for (String letter : args[i].split("")) { - if (letter.equalsIgnoreCase("-")) { - firstVal = false; - } else if (letter.equalsIgnoreCase("%")) { - break; - } else if (Utils.isInt(letter)) { - if (firstVal) - firstNum.append(letter); - else - secondNum.append(letter); - } - } - - int first = Integer.parseInt(firstNum.toString()); - int second = Integer.parseInt(secondNum.toString()); - - try { - if (second - first == 0) { - second = second + 1; - } else if (second - first < 0) { - int temp = second; - second = first; - first = temp; - } - int random = this.random.nextInt(second - first) + first; - String toReplace = "%amount" + firstNum + "-" + secondNum + "%"; - cmd = cmd.replaceAll(toReplace, random + ""); - } catch (Exception exc) { - ChatUtils - .log("The %amountX-X% placeholder is improperly formatted. Please use %amountX-Y where X is the starting value and Y is the ending (X is LESS THAN Y)"); - } - } - } - - return cmd; - } - - public void writeToFile() { - FileHandler fu = getInstance().getRewardsFile(); - FileConfiguration fc = fu.get(); - fc.set(getPath("commands"), getCommands()); - fc.set(getPath("chance"), getChance()); - fc.set(getPath("rarity"), getRarity()); - fc.set(getPath("receive-limit"), /*getTotalUses()*/null); - fc.set(getPath("give-display-item.value"), giveDisplayItem); - fc.set(getPath("give-display-item.with-lore"), giveDisplayItemLore); - fc.set(getPath("give-display-item.with-name"), giveDisplayItemName); - fc.set(getPath("fallback-reward.reward-name"), fallbackRewardName); - fc.set(getPath("fallback-reward.permission"), fallbackPermission); - - saveBuilder.saveItem(getInstance().getRewardsFile(), getPath("display-item"), false); - - fu.save(); - } - - public String delete(boolean forSure) { - if (!forSure) { - ArrayList cratesThatUse = new ArrayList<>(); - for (Crate crate : Crate.getLoadedCrates().values()) { - if (!crate.isMultiCrate() && crate.isLoadedProperly()) { - for (Reward r : crate.getSettings().getReward().getCrateRewards()) { - if (r.equals(this)) { - cratesThatUse.add(crate.getName()); - break; - } - } - } - } - - return cratesThatUse.toString(); - } else { - for (Crate crate : Crate.getLoadedCrates().values()) { - if (!crate.isMultiCrate() && crate.isLoadedProperly()) { - for (Reward r : crate.getSettings().getReward().getCrateRewards()) { - if (r.equals(this)) { - crate.getSettings().getReward().removeReward(r.getRewardName()); - crate.getSettings().getReward().saveToFile(); - crate.getSettings().getFileHandler().save(); - break; - } - } - } - } - - getInstance().getRewardsFile().get().set(getRewardName(), null); - getInstance().getRewardsFile().save(); - CReward.getAllRewards().remove(getRewardName()); - } - return ""; - } - - public String applyVariablesTo(String s) { - return ChatUtils.toChatColor(s.replace("%rewardname%", getRewardName()). - replace("%displayname%", saveBuilder.getDisplayName(true)). - replace("%writtenchance%", getChance() + ""). - replace("%rarity%", rarity)). - replace("%chance%", getFormattedChance()); - } - - public String getFormattedChance() { - if (toLog) { - double ch = getChance() / rewards.getTotalOdds(); - ch = ch * 100; - - // If a chance is really small, this is so it doesn't show as 0. - if (ch < 1) { - String chanceAsDub = BigDecimal.valueOf(ch).toPlainString(); - String littleNumberFormat = "#."; - boolean foundDot = false; - for (int i = 0; i < chanceAsDub.length(); i++) { - char val = chanceAsDub.charAt(i); - - if (foundDot) { - littleNumberFormat += "#"; - if (val != '0') { - break; - } - } - - if (val == '.') { - foundDot = true; - } - } - return new DecimalFormat(littleNumberFormat + "#").format(ch); - } - - return new DecimalFormat("#.##").format(ch); - } else { - return "-1"; - } - } - - public void loadChance() { - try { - setChance(getInstance().getRewardsFile().get().getDouble(getPath("chance"))); - } catch (Exception exc) { - needsMoreConfig = true; - if (toLog) { - setChance(-1); - StatusLoggerEvent.REWARD_CHANCE_NONEXISTENT.log(getRewards().getCrate(), this.toString()); - } - } - } - - @Deprecated - public boolean loadFromConfig() { - setFileConfiguration(getInstance().getRewardsFile().get()); - boolean success = true; - needsMoreConfig = false; - - if (fileConfiguration.contains(getPath("item"))) { - ChatUtils.log("Converting " + getRewardName() + " to new reward format."); - RewardConverter rewardConverter = new RewardConverter(this); - rewardConverter.loadFromConfig(); - rewardConverter.saveAllAsNull(); - - saveBuilder.saveItem(instance.getRewardsFile(), getPath("display-item"), false); - instance.getRewardsFile().save(); - } else { - if (toLog) - saveBuilder.loadItem(getInstance().getRewardsFile(), getRewardName() + ".display-item", - getRewards().getCrate().getSettings().getStatusLogger(), - StatusLoggerEvent.REWARD_ITEM_FAILURE, StatusLoggerEvent.REWARD_ENCHANT_INVALID, - StatusLoggerEvent.REWARD_POTION_INVALID, StatusLoggerEvent.REWARD_GLOW_FAILURE, - StatusLoggerEvent.REWARD_AMOUNT_INVALID, StatusLoggerEvent.REWARD_FLAG_FAILURE); - else - saveBuilder.loadItem(getInstance().getRewardsFile(), getRewardName() + ".display-item"); - } - - if (!loadNonItemValsFromConfig()) - success = false; - - if (getRarity() == null) - rarity = "default"; - - displayBuilder = new ItemBuilder(saveBuilder); - if (displayBuilder.hasDisplayName()) { - displayBuilder.setDisplayName(applyVariablesTo(saveBuilder.getDisplayName(true))); - } - - displayBuilder.clearLore(); - for (String loreLine : saveBuilder.getLore()) - displayBuilder.addLore(applyVariablesTo(loreLine)); - - return success; - } - - public boolean loadNonItemValsFromConfig() { - boolean success = true; - try { - setRarity(getFileConfiguration().getString(getPath("rarity"))); - } catch (Exception exc) { - //needsMoreConfig = true; - if (toLog) { - StatusLoggerEvent.REWARD_RARITY_NONEXISTENT.log(getRewards().getCrate(), this.toString()); - success = false; - } - } - - try { - setGiveDisplayItem(getFileConfiguration().getBoolean(getPath("give-display-item.value"))); - } catch (Exception exc) { - setGiveDisplayItem(false); - } - - try { - setGiveDisplayItemLore(getFileConfiguration().getBoolean(getPath("give-display-item.with-lore"))); - } catch (Exception exc) { - setGiveDisplayItemLore(true); - } - - try { - if (getFileConfiguration().contains(getPath("give-display-item.with-name"))) - setGiveDisplayItemName(getFileConfiguration().getBoolean(getPath("give-display-item.with-name"))); - } catch (Exception exc) { - setGiveDisplayItemName(true); - } - - try { - setCommands(getFileConfiguration().getStringList(getPath("commands"))); - } catch (Exception exc) { - if (toLog) { - StatusLoggerEvent.REWARD_COMMAND_INVALID.log(getRewards().getCrate(), this.toString()); - success = false; - } - } - - if (getFileConfiguration().contains(getPath("fallback-reward.reward-name"))) { - fallbackRewardName = getFileConfiguration().getString(getPath("fallback-reward.reward-name")); - } else { - fallbackRewardName = ""; - } - - if (getFileConfiguration().contains(getPath("fallback-reward.permission"))) { - fallbackPermission = getFileConfiguration().getString(getPath("fallback-reward.permission")); - } else { - fallbackPermission = ""; - } - - try { - setTotalUses(getFileConfiguration().getInt(getPath("receive-limit"))); - } catch (Exception exc) { - setTotalUses(-1); - } - - return success; - } - - public String getDisplayName(boolean useMaterialIfNull) { - if (!useMaterialIfNull && (displayBuilder == null || !displayBuilder.hasDisplayName())) { - return rewardName; - } - - String displayName = displayBuilder.getDisplayName(true); - if (displayName.equalsIgnoreCase("")) { - displayBuilder.setDisplayName(null); - return displayBuilder.getDisplayName(true); - } - return displayName; - } - - public void checkIsNeedMoreConfig() { - needsMoreConfig = - !(chance != -1 && /*saveBuilder.getDisplayName(false) != null &&*/ rarity != null && saveBuilder != null); - } - - public boolean equals(Reward r) { - return r.getRewardName().equalsIgnoreCase(getRewardName()); - } - - public String toString() { - return getRewardName(); - } - - public String getPath(String s) { - return getRewardName() + "." + s; - } - - public boolean isGiveDisplayItemName() { - return giveDisplayItemName; - } - - public void setGiveDisplayItemName(boolean giveDisplayItemName) { - this.giveDisplayItemName = giveDisplayItemName; - } - - public List getCommands() { - return commands; - } - - public void setCommands(List list) { - this.commands = list; - } - - public String getRewardName() { - return rewardName; - } - - public void setRewardName(String rewardName) { - this.rewardName = rewardName; - } - - public String getRarity() { - return rarity; - } - - public void setRarity(String rarity) { - this.rarity = rarity; - } - - public Double getChance() { - return chance; - } - - public void setChance(Integer chance) { - this.chance = chance; - } - - public void setChance(double chance) { - this.chance = chance; - } - - public SpecializedCrates getInstance() { - return instance; - } - - public int getTotalUses() { - return totalUses; - } - - public void setTotalUses(int totalUses) { - this.totalUses = totalUses; - } - - public FileConfiguration getFileConfiguration() { - return fileConfiguration; - } - - public void setFileConfiguration(FileConfiguration fileConfiguration) { - this.fileConfiguration = fileConfiguration; - } - - public CReward getRewards() { - return rewards; - } - - public void setRewards(CReward rewards) { - this.rewards = rewards; - } - - public boolean isNeedsMoreConfig() { - return needsMoreConfig; - } - - public void setNeedsMoreConfig(boolean needsMoreConfig) { - this.needsMoreConfig = needsMoreConfig; - } - - public boolean isGiveDisplayItem() { - return giveDisplayItem; - } - - public void setGiveDisplayItem(boolean giveDisplayItem) { - this.giveDisplayItem = giveDisplayItem; - } - - public boolean isGiveDisplayItemLore() { - return giveDisplayItemLore; - } - - public void setGiveDisplayItemLore(boolean giveDisplayItemLore) { - this.giveDisplayItemLore = giveDisplayItemLore; - } - - public ItemBuilder getDisplayBuilder() { - return displayBuilder; - } - - public void setDisplayBuilder(ItemBuilder displayBuilder) { - this.displayBuilder = displayBuilder; - } - - public ItemBuilder getSaveBuilder() { - return saveBuilder; - } - - public void setSaveBuilder(SaveableItemBuilder saveBuilder) { - this.saveBuilder = saveBuilder; - } - - public void setBuilder(ItemBuilder setBuilder) { - this.saveBuilder = new SaveableItemBuilder(setBuilder); - this.displayBuilder = new ItemBuilder(setBuilder); - } - - public String getFallbackRewardName() { - return fallbackRewardName; - } - - public void setFallbackRewardName(String fallbackRewardName) { - this.fallbackRewardName = fallbackRewardName; - } - - public String getFallbackPermission() { - return fallbackPermission; - } - - public void setFallbackPermission(String fallbackPermission) { - this.fallbackPermission = fallbackPermission; - } - - public boolean isToLog() { - return toLog; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/rewards/RewardConverter.java b/src/main/java/me/ztowne13/customcrates/crates/options/rewards/RewardConverter.java deleted file mode 100644 index bcd7f4a..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/rewards/RewardConverter.java +++ /dev/null @@ -1,182 +0,0 @@ -package me.ztowne13.customcrates.crates.options.rewards; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.interfaces.files.FileHandler; -import me.ztowne13.customcrates.interfaces.items.CompressedPotionEffect; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.interfaces.items.SaveableItemBuilder; -import me.ztowne13.customcrates.interfaces.logging.StatusLoggerEvent; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.enchantments.Enchantment; - -import java.util.Collection; -import java.util.Optional; - -public class RewardConverter { - private final Reward reward; - - public RewardConverter(Reward reward) { - this.reward = reward; - } - - public void saveAllAsNull() { - FileHandler rewardsFile = reward.getInstance().getRewardsFile(); - FileConfiguration fc = rewardsFile.get(); - - fc.set(reward.getPath("name"), null); - fc.set(reward.getPath("item"), null); - fc.set(reward.getPath("glow"), null); - fc.set(reward.getPath("amount"), null); - fc.set(reward.getPath("head-player-name"), null); - fc.set(reward.getPath("enchantments"), null); - fc.set(reward.getPath("potion-effects"), null); - fc.set(reward.getPath("lore"), null); - fc.set(reward.getPath("nbt-tags"), null); - } - - @Deprecated - public boolean loadFromConfig() { - reward.setFileConfiguration(reward.getInstance().getRewardsFile().get()); - boolean success = true; - reward.setNeedsMoreConfig(false); - - String unsplitMat = reward.getFileConfiguration().getString(reward.getPath("item")); - Optional optional = unsplitMat != null ? XMaterial.matchXMaterial(unsplitMat) : Optional.empty(); - - if (optional.isPresent()) { - XMaterial m = optional.get(); - - if (m.equals(XMaterial.AIR)) { - StatusLoggerEvent.REWARD_ITEM_AIR.log(reward.getRewards().getCrate(), this.toString()); - return false; - } - - reward.setSaveBuilder(new SaveableItemBuilder(m, 1)); - } else { - // TODO: Something here to indicate that the material is invalid - return false; - } - - try { - reward.getSaveBuilder().setDisplayName(reward.getFileConfiguration().getString(reward.getPath("name"))); - } catch (Exception exc) { - reward.getSaveBuilder().setDisplayName(reward.getSaveBuilder().getStack().getType().name().toLowerCase()); - reward.setNeedsMoreConfig(true); - if (reward.isToLog()) { - StatusLoggerEvent.REWARD_NAME_NONEXISTENT.log(reward.getRewards().getCrate(), this.toString()); - success = false; - } - } - - if (!reward.loadNonItemValsFromConfig()) - success = false; - - try { - reward.getSaveBuilder().setGlowing(reward.getFileConfiguration().getBoolean(reward.getPath("glow"))); - } catch (Exception exc) { - reward.getSaveBuilder().setGlowing(false); - } - - try { - buildDisplayItemFromConfig(); - } catch (Exception exc) { - reward.setNeedsMoreConfig(true); - if (reward.isToLog()) { - StatusLoggerEvent.REWARD_ITEM_NONEXISTENT.log(reward.getRewards().getCrate(), this.toString()); - success = false; - } - } - - if (!reward.getSaveBuilder().hasDisplayName()) - reward.getSaveBuilder().setDisplayName(reward.getRewardName()); - - if (reward.getRarity() == null) - reward.setRarity("default"); - - reward.setDisplayBuilder(new ItemBuilder(reward.getSaveBuilder().getStack())); - reward.getDisplayBuilder().setDisplayName(reward.applyVariablesTo(reward.getSaveBuilder().getDisplayName(false))); - - reward.getDisplayBuilder().clearLore(); - for (String loreLine : reward.getSaveBuilder().getLore()) { - reward.getDisplayBuilder().addLore(reward.applyVariablesTo(loreLine)); - } - - return success; - } - - @Deprecated - public void buildDisplayItemFromConfig() { - reward.getSaveBuilder().setDisplayName(reward.applyVariablesTo(reward.getInstance().getSettings().getConfigValues().get("inv-reward-item-name").toString())); - - // If an item has a custom lore, apply that. Otherwise apply the general lore. - if (reward.getFileConfiguration().contains(reward.getPath("lore"))) { - - for (String s : reward.getFileConfiguration().getStringList(reward.getPath("lore"))) { - reward.getSaveBuilder().addLore(s); - } - } else { - for (Object s : (Collection) reward.getInstance().getSettings().getConfigValues().get("inv-reward-item-lore")) { - reward.getSaveBuilder().addLore(s.toString()); - } - } - - if (reward.getFileConfiguration().contains(reward.getPath("head-player-name"))) { - reward.getSaveBuilder().setPlayerHeadName(reward.getFileConfiguration().getString(reward.getPath("head-player-name"))); - } - - if (reward.getFileConfiguration().contains(reward.getPath("amount"))) { - try { - int amnt = Integer.parseInt(reward.getFileConfiguration().getString(reward.getPath("amount"))); - reward.getSaveBuilder().getStack().setAmount(amnt); - } catch (Exception exc) { - StatusLoggerEvent.REWARD_AMOUNT_INVALID.log(reward.getRewards().getCrate(), reward.getSaveBuilder().getDisplayName(true)); - } - } - - - if (reward.getFileConfiguration().contains(reward.getPath("nbt-tags"))) { - for (String s : reward.getFileConfiguration().getStringList(reward.getPath("nbt-tags"))) { - reward.getSaveBuilder().addNBTTag(s); - } - } - - if (reward.getFileConfiguration().contains(reward.getPath("potion-effects"))) { - for (String unparsedPot : reward.getFileConfiguration().getStringList(reward.getPath("potion-effects"))) { - try { - CompressedPotionEffect compressedPotionEffect = CompressedPotionEffect.fromString(unparsedPot); - - reward.getSaveBuilder().addPotionEffect(compressedPotionEffect); - } catch (Exception exc) { - StatusLoggerEvent.REWARD_POTION_INVALID - .log(reward.getRewards().getCrate(), reward.getSaveBuilder().getDisplayName(true), unparsedPot); - } - } - } - - if (reward.getFileConfiguration().contains(reward.getPath("enchantments"))) { - String cause = reward.getPath("enchantments") + " value is not a valid list of enchantments."; - try { - for (String s : reward.getFileConfiguration().getStringList(reward.getPath("enchantments"))) { - cause = "Enchantment " + s + " is not formatted ENCHANTMENT;LEVEL"; - String[] args = s.split(";"); - - cause = args[0] + " is not a valid enchantment."; - Enchantment ench = Enchantment.getByName(args[0].toUpperCase()); - - if (ench == null) { - throw new NullPointerException(cause); - } - - cause = "Enchantment " + s + " is not formatted ENCHANTMENT;LEVEL"; - cause = args[1] + " is not a valid Integer."; - int level = Integer.parseInt(args[1]); - - reward.getSaveBuilder().addEnchantment(ench, level); - } - } catch (Exception exc) { - StatusLoggerEvent.REWARD_ENCHANT_INVALID - .log(reward.getRewards().getCrate(), reward.getSaveBuilder().getDisplayName(true), cause); - } - } - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/rewards/displaymenu/RewardDisplayType.java b/src/main/java/me/ztowne13/customcrates/crates/options/rewards/displaymenu/RewardDisplayType.java deleted file mode 100644 index 80e9b72..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/rewards/displaymenu/RewardDisplayType.java +++ /dev/null @@ -1,29 +0,0 @@ -package me.ztowne13.customcrates.crates.options.rewards.displaymenu; - -import java.util.ArrayList; -import java.util.List; - -public enum RewardDisplayType { - IN_ORDER("Fills the preview menu with all the rewards in a random order."), - - SORTED_LOW_TO_HIGH("Fills the preview menu with the rewards sorted from the lowest to highest chance."), - - SORTED_HIGH_TO_LOW("Fills the preview menu with the rewards sorted from the highest to lowest chance."), - - CUSTOM("You custom design the entire reward preview menu with any items and any rewards. This supports multiple pages of rewards too!"); - - private final String description; - - RewardDisplayType(String description) { - this.description = description; - } - - public static List descriptions() { - ArrayList list = new ArrayList<>(); - for (RewardDisplayType rewardDisplayType : values()) { - list.add(rewardDisplayType.description); - } - - return list; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/rewards/displaymenu/RewardDisplayer.java b/src/main/java/me/ztowne13/customcrates/crates/options/rewards/displaymenu/RewardDisplayer.java deleted file mode 100644 index 68f7643..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/rewards/displaymenu/RewardDisplayer.java +++ /dev/null @@ -1,99 +0,0 @@ -package me.ztowne13.customcrates.crates.options.rewards.displaymenu; - -import me.ztowne13.customcrates.Messages; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.options.rewards.displaymenu.custom.CustomRewardDisplayer; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.files.FileHandler; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; - -public abstract class RewardDisplayer { - private final Crate crate; - private final FileHandler fileHandler; - private String name = null; - private boolean requirePermForPreview = false; - - public RewardDisplayer(Crate crate) { - this.crate = crate; - this.fileHandler = crate.getSettings().getFileHandler(); - } - - public abstract void open(Player player); - - public abstract InventoryBuilder createInventory(Player player); - - public abstract void load(); - - public void openFor(Player player) { - if (isRequirePermForPreview() && !player.hasPermission(getCrate().getSettings().getPermission())) { - Messages.NO_PERMISSION_CRATE.msgSpecified(crate.getInstance(), player); - return; - } - - if (!(this instanceof CustomRewardDisplayer) && crate.getSettings().getReward().getCrateRewards().length > 54 - && (player.hasPermission("customcrates.admin") || player.hasPermission("specializedcrates.admin"))) { - ChatUtils.msgHey(player, - "Just a heads up: you have more than 54 rewards in this crate, but only the &lCUSTOM &ereward display" + - " type supports multiple pages, so not all rewards are shown &o(note: only admins can see this message)."); - } - - open(player); - } - - public String getInvName() { - if (name == null) - return ChatUtils.toChatColor( - getCrate().getInstance().getSettings().getConfigValues().get("inv-reward-display-name").toString() - .replace("%crate%", getCrate().getDisplayName())); - else - return ChatUtils.toChatColor(name); - } - - public void loadDefaults() { - FileConfiguration fc = fileHandler.get(); - - if (fc.contains("reward-display.name")) { - this.name = fc.getString("reward-display.name"); - } - - if (fc.contains("reward-display.require-permission")) { - try { - this.requirePermForPreview = fc.getBoolean("reward-display.require-permission"); - } catch (Exception exc) { - // IGNORED - } - } - } - - public void saveToFile() { - getFileHandler().get().set("reward-display.type", getCrate().getSettings().getRewardDisplayType().name()); - getFileHandler().get().set("reward-display.name", name); - getFileHandler().get().set("reward-display.require-permission", requirePermForPreview); - } - - public Crate getCrate() { - return crate; - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public FileHandler getFileHandler() { - return fileHandler; - } - - public boolean isRequirePermForPreview() { - return requirePermForPreview; - } - - public void setRequirePermForPreview(boolean requirePermForPreview) { - this.requirePermForPreview = requirePermForPreview; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/rewards/displaymenu/SimpleRewardDisplayer.java b/src/main/java/me/ztowne13/customcrates/crates/options/rewards/displaymenu/SimpleRewardDisplayer.java deleted file mode 100644 index a4aaa87..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/rewards/displaymenu/SimpleRewardDisplayer.java +++ /dev/null @@ -1,44 +0,0 @@ -package me.ztowne13.customcrates.crates.options.rewards.displaymenu; - -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.options.CReward; -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.players.PlayerManager; -import org.bukkit.entity.Player; - -public class SimpleRewardDisplayer extends RewardDisplayer { - public SimpleRewardDisplayer(Crate crate) { - super(crate); - } - - @Override - public void open(Player player) { - player.openInventory(createInventory(player).getInv()); - PlayerManager.get(getCrate().getInstance(), player).setInRewardMenu(true); - } - - @Override - public InventoryBuilder createInventory(Player player) { - CReward rewards = getCrate().getSettings().getReward(); - int amount = rewards.getCrateRewards().length; - int rows = amount % 9 == 0 ? amount / 9 : (amount / 9) + 1; - InventoryBuilder inventoryBuilder = new InventoryBuilder(player, rows * 9, getInvName()); - Reward[] crateRewards = rewards.getCrateRewards(); - int i = 0; - for (Reward reward : crateRewards) { - if (i >= 54) { - break; - } - - inventoryBuilder.setItem(i, reward.getDisplayBuilder()); - i++; - } - return inventoryBuilder; - } - - @Override - public void load() { - loadDefaults(); - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/rewards/displaymenu/SortedRewardDisplayer.java b/src/main/java/me/ztowne13/customcrates/crates/options/rewards/displaymenu/SortedRewardDisplayer.java deleted file mode 100644 index cbfbdb0..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/rewards/displaymenu/SortedRewardDisplayer.java +++ /dev/null @@ -1,61 +0,0 @@ -package me.ztowne13.customcrates.crates.options.rewards.displaymenu; - -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.options.CReward; -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.players.PlayerManager; -import org.bukkit.entity.Player; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -public class SortedRewardDisplayer extends RewardDisplayer { - private final boolean lowToHigh; - - public SortedRewardDisplayer(Crate crate, boolean lowToHigh) { - super(crate); - this.lowToHigh = lowToHigh; - } - - @Override - public void open(Player player) { - player.openInventory(createInventory(player).getInv()); - PlayerManager.get(getCrate().getInstance(), player).setInRewardMenu(true); - } - - @Override - public InventoryBuilder createInventory(Player player) { - CReward rewards = getCrate().getSettings().getReward(); - int amount = rewards.getCrateRewards().length; - int rows = amount % 9 == 0 ? amount / 9 : (amount / 9) + 1; - InventoryBuilder inventoryBuilder = new InventoryBuilder(player, rows * 9, getInvName()); - Reward[] crateRewards = rewards.getCrateRewards(); - int i = 0; - for (Reward reward : sortedRewards(crateRewards)) { - if (i >= 54) { - break; - } - inventoryBuilder.setItem(i, reward.getDisplayBuilder()); - i++; - } - return inventoryBuilder; - } - - public List sortedRewards(Reward[] rewards) { - List sortedRewards = Arrays.asList(rewards); - - if (lowToHigh) - Collections.sort(sortedRewards); - else - sortedRewards.sort(Collections.reverseOrder()); - - return sortedRewards; - } - - @Override - public void load() { - loadDefaults(); - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/rewards/displaymenu/custom/CustomRewardDisplayer.java b/src/main/java/me/ztowne13/customcrates/crates/options/rewards/displaymenu/custom/CustomRewardDisplayer.java deleted file mode 100644 index 3feb618..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/rewards/displaymenu/custom/CustomRewardDisplayer.java +++ /dev/null @@ -1,158 +0,0 @@ -package me.ztowne13.customcrates.crates.options.rewards.displaymenu.custom; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.options.rewards.displaymenu.RewardDisplayer; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.files.FileHandler; -import me.ztowne13.customcrates.interfaces.items.SaveableItemBuilder; -import me.ztowne13.customcrates.interfaces.logging.StatusLoggerEvent; -import me.ztowne13.customcrates.players.PlayerManager; -import me.ztowne13.customcrates.utils.Utils; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class CustomRewardDisplayer extends RewardDisplayer { - public static final String PREFIX = "reward-display.custom-display.items"; - - private final HashMap pages = new HashMap<>(); - private final HashMap items = new HashMap<>(); - private String nextPageItem; - private String prevPageItem; - - public CustomRewardDisplayer(Crate crate) { - super(crate); - } - - @Override - public void open(Player player) { - createInventory(player); - PlayerManager.get(getCrate().getInstance(), player).setInRewardMenu(true); - } - - @Override - public InventoryBuilder createInventory(Player player) { - if (pages.containsKey(1)) - return pages.get(1).buildInventoryBuilder(player); - return null; - } - - @Override - public void load() { - loadDefaults(); - - FileHandler fileHandler = getCrate().getSettings().getFileHandler(); - FileConfiguration fc = fileHandler.get(); - - ConfigurationSection configSection; - - if (fc.isConfigurationSection(PREFIX)) { - configSection = fc.getConfigurationSection(PREFIX); - - for (String key : configSection.getKeys(false)) { - SaveableItemBuilder itemBuilder = new SaveableItemBuilder(XMaterial.STONE, 1); - boolean successLoadItem = - itemBuilder.loadItem( - getCrate().getSettings().getFileHandler(), PREFIX + "." + key, getCrate().getSettings().getStatusLogger(), - StatusLoggerEvent.SETTINGS_REWARD_DISPLAYER_ITEM_FAILURE, - StatusLoggerEvent.SETTINGS_REWARD_DISPLAYER_ENCHANTMENT_ADD_FAILURE, - StatusLoggerEvent.SETTINGS_REWARD_DISPLAYER_POTION_ADD_FAILURE, - StatusLoggerEvent.SETTINGS_REWARD_DISPLAYER_GLOW_FAILURE, - StatusLoggerEvent.SETTINGS_REWARD_DISPLAYER_AMOUNT_FAILURE, - StatusLoggerEvent.SETTINGS_REWARD_DISPLAYER_FLAG_FAILURE); - if (successLoadItem) - items.put(key, itemBuilder); - } - } - - if (fc.isConfigurationSection("reward-display.custom-display")) { - configSection = fc.getConfigurationSection("reward-display.custom-display"); - - if (configSection.contains("nextpageitem")) - nextPageItem = configSection.getString("nextpageitem"); - if (configSection.contains("lastpageitem")) - prevPageItem = configSection.getString("lastpageitem"); - } - - if (fc.isConfigurationSection(DisplayPage.PREFIX)) { - - configSection = fc.getConfigurationSection(DisplayPage.PREFIX); - - for (String key : configSection.getKeys(false)) { - if (Utils.isInt(key)) { - int pageNum = Integer.parseInt(key); - DisplayPage displayPage = new DisplayPage(this, pageNum); - boolean successLoadPage = displayPage.load(); - - if (successLoadPage) - pages.put(pageNum, displayPage); - } - } - } - } - - public void saveAllPages() { - for (DisplayPage page : getPages().values()) { - page.save(); - } - - FileConfiguration fc = getFileHandler().get(); - fc.set(PREFIX, null); - - for (String symbol : getItems().keySet()) { - SaveableItemBuilder builder = getItems().get(symbol); - String path = PREFIX + "." + symbol; - - builder.saveItem(getFileHandler(), path, true); - } - } - - public String getNextSymbol() { - for (int i = 0; i < 1000; i++) { - if (!getItems().containsKey(i + "")) - return i + ""; - } - - return "-1"; - } - - public List getDescriptors() { - ArrayList descriptors = new ArrayList<>(); - - for (SaveableItemBuilder item : getItems().values()) { - descriptors.add("&fItem Name: " + item.getDisplayName(true)); - } - - return descriptors; - } - - public Map getItems() { - return items; - } - - public String getNextPageItem() { - return nextPageItem; - } - - public void setNextPageItem(String nextPageItem) { - this.nextPageItem = nextPageItem; - } - - public String getPrevPageItem() { - return prevPageItem; - } - - public void setPrevPageItem(String prevPageItem) { - this.prevPageItem = prevPageItem; - } - - public Map getPages() { - return pages; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/rewards/displaymenu/custom/DisplayPage.java b/src/main/java/me/ztowne13/customcrates/crates/options/rewards/displaymenu/custom/DisplayPage.java deleted file mode 100644 index 6980b70..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/rewards/displaymenu/custom/DisplayPage.java +++ /dev/null @@ -1,276 +0,0 @@ -package me.ztowne13.customcrates.crates.options.rewards.displaymenu.custom; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.files.FileHandler; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.interfaces.items.SaveableItemBuilder; -import me.ztowne13.customcrates.players.PlayerManager; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.Bukkit; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; -import org.bukkit.inventory.Inventory; - -import java.util.ArrayList; -import java.util.List; - -public class DisplayPage { - public static final String PREFIX = "reward-display.custom-display.pages"; - - private final CustomRewardDisplayer customRewardDisplayer; - private final int pageNum; - private int slots; - - private String[][] unformattedInv; - private Reward[][] rewards; - private SaveableItemBuilder[][] builders; - - public DisplayPage(CustomRewardDisplayer customRewardDisplayer, int pageNum) { - this.customRewardDisplayer = customRewardDisplayer; - this.pageNum = pageNum; - } - - public void save() { - - if (builders == null) - buildFormat(); - - FileHandler fileHandler = customRewardDisplayer.getCrate().getSettings().getFileHandler(); - FileConfiguration fc = fileHandler.get(); - - ArrayList format = new ArrayList<>(); - - for (int x = 0; x < 6; x++) { - StringBuilder lineFormat = new StringBuilder(); - - for (int y = 0; y < 9; y++) { - if (builders[x][y] == null) { - Reward reward = rewards[x][y]; - - if (reward == null) - lineFormat.append(","); - else - lineFormat.append(reward.getRewardName()).append(","); - - continue; - } - - SaveableItemBuilder stack = builders[x][y]; - - boolean found = false; - for (String symbol : customRewardDisplayer.getItems().keySet()) { - SaveableItemBuilder checkBuilder = customRewardDisplayer.getItems().get(symbol); - if (checkBuilder.equals(stack)) { - lineFormat.append(symbol).append(","); - found = true; - break; - } - } - - if (!found) { - String symbol = customRewardDisplayer.getNextSymbol(); - customRewardDisplayer.getItems().put(symbol, stack); - lineFormat.append(symbol).append(","); - } - } - format.add(lineFormat.substring(0, lineFormat.length() - 1)); - } - - // Trip uneccessary lines off the end. - - for (int i = 5; i >= 0; i--) { - if (format.get(i).equals(",,,,,,,,")) - format.remove(i); - else - break; - } - - fc.set(PREFIX + "." + pageNum, format); - } - - public boolean load() { - FileHandler fileHandler = customRewardDisplayer.getCrate().getSettings().getFileHandler(); - FileConfiguration fc = fileHandler.get(); - - if (!fc.contains(PREFIX + "." + pageNum)) { - unformattedInv = new String[6][9]; - return false; - } - - List values = fc.getStringList(PREFIX + "." + pageNum); - - slots = values.size() * 9; - - unformattedInv = new String[values.size()][9]; - - for (int i = 0; i < values.size(); i++) { - String line = values.get(i).replace(", ", ","); - String[] args = line.split(","); - - for (int j = 0; j < 9; j++) { - if (args.length <= j) - unformattedInv[i][j] = null; - else - unformattedInv[i][j] = args[j]; - } - } - - return true; - } - - public InventoryBuilder buildInventoryBuilder(Player player) { - return buildInventoryBuilder(player, false); - } - - public InventoryBuilder buildInventoryBuilder(Player player, boolean forceMaxSlots) { - return buildInventoryBuilder(player, forceMaxSlots, "", null, true); - } - - public InventoryBuilder buildInventoryBuilder(Player player, boolean forceMaxSlots, String invNameOverride, InventoryBuilder builder, boolean open) { - InventoryBuilder ib; - - if (builder == null) - ib = new InventoryBuilder(player, forceMaxSlots ? 54 : slots, - invNameOverride.equals("") ? customRewardDisplayer.getInvName() : invNameOverride); - else - ib = builder; - - if (rewards == null || builders == null) { - buildFormat(); - return buildInventoryBuilder(player, forceMaxSlots, invNameOverride, builder, open); - } - - for (int x = 0; x < (forceMaxSlots ? 6 : unformattedInv.length); x++) { - for (int y = 0; y < (forceMaxSlots ? 9 : unformattedInv[0].length); y++) { - int slot = (x * 9) + y; - - if (builders[x][y] == null) { - if (rewards[x][y] != null) - ib.setItem(slot, rewards[x][y].getDisplayBuilder()); - } else { - ib.setItem(slot, builders[x][y]); - } - } - } - - if (builder == null && open) { - final PlayerManager pm = PlayerManager.get(customRewardDisplayer.getCrate().getInstance(), player); - pm.setNextPageInventoryCloseGrace(pm.getInstance().getTotalTicks() + 2L); - - final Inventory inv = ib.getInv(); - final DisplayPage thisPage = this; - Bukkit.getScheduler().runTaskLater(pm.getInstance(), () -> { - player.openInventory(inv); - pm.setLastPage(thisPage); - pm.setInRewardMenu(true); - }, 2); - } - - return ib; - } - - public void buildFormat() { - rewards = new Reward[6][9]; - builders = new SaveableItemBuilder[6][9]; - - for (int x = 0; x < unformattedInv.length; x++) { - for (int y = 0; y < unformattedInv[0].length; y++) { - if (unformattedInv[x][y] != null) { - String symbol = unformattedInv[x][y]; - - if (customRewardDisplayer.getItems().containsKey(symbol)) { - builders[x][y] = customRewardDisplayer.getItems().get(symbol); - } else { - Reward reward = customRewardDisplayer.getCrate().getSettings().getReward().getByName(symbol); - if (reward != null) - rewards[x][y] = reward; - } - } - } - } - } - - public void handleInput(Player player, int slot) { - SpecializedCrates sc = customRewardDisplayer.getCrate().getInstance(); - int x = slot / 9; - sc.getDebugUtils().log("handleInput() - x: " + x, getClass()); - int y = slot % 9; - sc.getDebugUtils().log("handleInput() - y: " + y, getClass()); - String symbolAt = unformattedInv[x][y]; - sc.getDebugUtils().log("handleInput() - symbolAt: " + symbolAt, getClass()); - sc.getDebugUtils().log("handleInput() - nextPageItem: " + customRewardDisplayer.getNextPageItem(), getClass()); - sc.getDebugUtils().log("handleInput() - backpageitem: " + customRewardDisplayer.getPrevPageItem(), getClass()); - - // There's no item in the display at the spot. - if (symbolAt == null) - return; - - if (symbolAt.equalsIgnoreCase(customRewardDisplayer.getNextPageItem())) { - if (customRewardDisplayer.getPages().containsKey(pageNum + 1)) - customRewardDisplayer.getPages().get(pageNum + 1).buildInventoryBuilder(player); - else - ChatUtils.msgError(player, "Page " + (pageNum + 1) + " does not exist. Please contact an administrator" + - "to create the next page of the reward-preview menu OR remove this 'next page arrow' because there" + - "is no next page."); - } else if (symbolAt.equalsIgnoreCase(customRewardDisplayer.getPrevPageItem())) { - if (customRewardDisplayer.getPages().containsKey(pageNum - 1)) - customRewardDisplayer.getPages().get(pageNum - 1).buildInventoryBuilder(player); - else - ChatUtils.msgError(player, "Page " + (pageNum - 1) + " does not exist. Please contact an administrator" + - "to create the previous page of the reward-preview menu OR remove this 'previous page arrow' because there" + - "is no previous page."); - } - } - - public List rewardsAsList() { - ArrayList rewardsList = new ArrayList<>(); - - if (rewards == null) - buildFormat(); - - for (Reward[] rewardList : rewards) { - for (int i = 0; i < 9; i++) { - if (rewardList[i] != null) - rewardsList.add(rewardList[i]); - } - } - - return rewardsList; - } - - public int getSlots() { - return slots; - } - - public void setSlots(int slots) { - this.slots = slots; - } - - public Reward[][] getRewards() { - return rewards; - } - - public void setRewards(Reward[][] rewards) { - this.rewards = rewards; - } - - public String[][] getUnformattedInv() { - return unformattedInv; - } - - public void setUnformattedInv(String[][] unformattedInv) { - this.unformattedInv = unformattedInv; - } - - public ItemBuilder[][] getBuilders() { - return builders; - } - - public void setBuilders(SaveableItemBuilder[][] builders) { - this.builders = builders; - } - - -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/options/sounds/SoundData.java b/src/main/java/me/ztowne13/customcrates/crates/options/sounds/SoundData.java deleted file mode 100644 index 79f67c6..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/options/sounds/SoundData.java +++ /dev/null @@ -1,54 +0,0 @@ -package me.ztowne13.customcrates.crates.options.sounds; - -import com.cryptomorin.xseries.XSound; -import org.bukkit.Location; -import org.bukkit.Sound; -import org.bukkit.entity.Player; - -public class SoundData { - private XSound sound; - private int volume; - private int pitch = 5; - - public SoundData(XSound sound) { - this(sound, 5); - } - - public SoundData(XSound sound, int volume) { - setSound(sound); - this.volume = volume; - } - - public void playTo(Player player, Location location) { - Sound parsedSound = getSound().parseSound(); - if (parsedSound != null) { - player.playSound(location, parsedSound, volume, pitch); - } - } - - public XSound getSound() { - return sound; - } - - public void setSound(XSound sound) { - this.sound = sound; - } - - public int getVolume() { - return volume; - } - - public void setVolume(int volume) { - this.volume = volume; - } - - public int getPitch() { - return pitch; - } - - public void setPitch(int pitch) { - this.pitch = pitch; - } - - -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/types/animations/AnimationDataHolder.java b/src/main/java/me/ztowne13/customcrates/crates/types/animations/AnimationDataHolder.java deleted file mode 100644 index 09b375d..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/types/animations/AnimationDataHolder.java +++ /dev/null @@ -1,123 +0,0 @@ -package me.ztowne13.customcrates.crates.types.animations; - -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.DebugUtils; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -import java.util.ArrayList; -import java.util.List; - -public abstract class AnimationDataHolder { - private final Player player; - private final Location location; - private final CrateAnimation crateAnimation; - private final List clickedKeys; - private boolean fastTrack = false; - private boolean fastTrackWaitTick = false; - private long totalTickTime; - private int totalTicks = 0; - private int individualTicks = 0; - private int waitingTicks = 0; - private State currentState = State.PLAYING; - - public AnimationDataHolder(Player player, Location location, CrateAnimation crateAnimation) { - this.player = player; - this.location = location; - this.crateAnimation = crateAnimation; - - clickedKeys = new ArrayList<>(); - } - - public void setFastTrack(boolean fastTrack, boolean force) { - if (force) { - this.fastTrack = fastTrack; - } else { - fastTrackWaitTick = true; - } - - } - - public void updateTickTime(long startTime) { - long curTime = System.nanoTime(); - long add = curTime - startTime; - - totalTickTime += add; - - if (DebugUtils.OUTPUT_AVERAGE_ANIMATION_TICK) - ChatUtils.log("Average animation tick in nanoseconds (totalTime = " + totalTickTime + ", ticks = " + totalTicks + "): " + - ((double) totalTickTime / ((double) totalTicks))); - } - - public int getTotalTicks() { - return totalTicks; - } - - public void setTotalTicks(int totalTicks) { - this.totalTicks = totalTicks; - } - - public int getIndividualTicks() { - return individualTicks; - } - - public void setIndividualTicks(int individualTicks) { - this.individualTicks = individualTicks; - } - - public State getCurrentState() { - return currentState; - } - - public void setCurrentState(State currentState) { - this.currentState = currentState; - } - - public Player getPlayer() { - return player; - } - - public Location getLocation() { - return location; - } - - public CrateAnimation getCrateAnimation() { - return crateAnimation; - } - - public int getWaitingTicks() { - return waitingTicks; - } - - public void setWaitingTicks(int waitingTicks) { - this.waitingTicks = waitingTicks; - } - - public List getClickedKeys() { - return clickedKeys; - } - - public boolean isFastTrack() { - return fastTrack; - } - - public boolean isFastTrackWaitTick() { - return fastTrackWaitTick; - } - - public enum State { - PLAYING, - - WAITING, - - CLOSING, - - ENDING, - - SHUFFLING, - - UNCOVERING, - - COMPLETED - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/types/animations/CrateAnimation.java b/src/main/java/me/ztowne13/customcrates/crates/types/animations/CrateAnimation.java deleted file mode 100644 index 7c36bd9..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/types/animations/CrateAnimation.java +++ /dev/null @@ -1,248 +0,0 @@ -package me.ztowne13.customcrates.crates.types.animations; - -import me.ztowne13.customcrates.Messages; -import me.ztowne13.customcrates.SettingsValue; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.api.CrateOpenEvent; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.CrateSettings; -import me.ztowne13.customcrates.crates.PlacedCrate; -import me.ztowne13.customcrates.crates.options.ObtainType; -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import me.ztowne13.customcrates.interfaces.files.FileHandler; -import me.ztowne13.customcrates.interfaces.logging.StatusLogger; -import me.ztowne13.customcrates.players.PlayerManager; -import me.ztowne13.customcrates.players.data.events.HistoryEvent; -import me.ztowne13.customcrates.utils.Utils; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.entity.Player; - -import java.util.List; -import java.util.Random; - -public abstract class CrateAnimation { - public static final long BASE_SPEED = 1; - protected final SpecializedCrates instance; - protected final Crate crate; - protected final FileHandler fileHandler; - protected final CrateAnimationType animationType; - private final Random random = new Random(); - protected String prefix; - - public CrateAnimation(Crate crate, CrateAnimationType animationType) { - this.animationType = animationType; - this.prefix = animationType.getPrefixDotted(); - this.crate = crate; - this.instance = crate.getInstance(); - this.fileHandler = instance.getCrateConfigFile(); - } - - /** - * This is the function that is called every tick to update and redraw the animation. - * - * @param dataHolder The data holder that stores the player's animation runtime information. - * @param update Whether or not this is an update tick - */ - public abstract void tickAnimation(AnimationDataHolder dataHolder, boolean update); - - /** - * This function is what is called when the state of the function is set to COMPLETED - * - * @param dataHolder The data holder that stores the player's animation runtime information. - */ - public abstract void endAnimation(AnimationDataHolder dataHolder); - - /** - * This function is responsible for loading and animation-based config values. - * - * @param statusLogger The status logger to log any errors or successes to. - */ - public abstract void loadDataValues(StatusLogger statusLogger); - - /** - * This function is responsible for calculating any tick updates. It is intended for - * the animations that slow down, speed up, etc - information is changing every tick. - * - * @param dataHolder The data holder that stores the player's animation runtime information. - * @return This value indicates whether or not a main or quintessential update needs to happen, - * opposed to just the default BASE_SPEED tick updates. - */ - public abstract boolean updateTicks(AnimationDataHolder dataHolder); - - /** - * This function checks if there needs to be a state changed, and executes that state change if so. - * - * @param dataHolder The data holder that stores the player's animation runtime information. - * @param update The result of the updateTicks() function, indicating whether a main update needs to - * happen - */ - public abstract void checkStateChange(AnimationDataHolder dataHolder, boolean update); - - /** - * This function is meant to handle any clicks in the inventory during the animation - * - * @param slot The slot that was clicked in the inventory - */ - public void handleClick(AnimationDataHolder dataHolder, int slot) { - } - - /** - * This function is meant to handle any keyboard key presses during the animation - * - * @param type The type of key that was pressed. - */ - public void handleKeyPress(AnimationDataHolder dataHolder, KeyType type) { - dataHolder.getClickedKeys().add(type); - } - - public boolean startAnimation(Player p, Location l, boolean requireKeyInHand, boolean force) { - if (force || canExecuteFor(p, requireKeyInHand)) { - AnimationDataHolder dataHolder = getAnimationType().newDataHolderInstance(p, l, this); - timer(dataHolder); - playRequiredOpenActions(p, !requireKeyInHand, force); - PlayerManager.get(instance, p).setCurrentAnimation(dataHolder); - return true; - } - - playFailToOpen(p, true, true); - return false; - } - - public void runAnimation(final AnimationDataHolder dataHolder) { - long startTime = System.nanoTime(); - - dataHolder.setIndividualTicks(dataHolder.getIndividualTicks() + (int) BASE_SPEED); - dataHolder.setTotalTicks(dataHolder.getTotalTicks() + (int) BASE_SPEED); - - boolean update = updateTicks(dataHolder); - - checkStateChange(dataHolder, update); - tickAnimation(dataHolder, update); - - dataHolder.getClickedKeys().clear(); - - dataHolder.updateTickTime(startTime); - } - - public void finishAnimation(Player p, List rewards, final PlacedCrate placedCrate) { - PlayerManager pm = PlayerManager.get(instance, p); - pm.setInRewardMenu(false); - pm.setCurrentAnimation(null); - - new HistoryEvent(Utils.currentTimeParsed(), getCrate(), rewards, true) - .addTo(PlayerManager.get(instance, p).getPlayerDataManager()); - - for (Reward r : rewards) { - r.giveRewardToPlayer(p); - } - - - CrateOpenEvent crateOpenEvent = new CrateOpenEvent(p, rewards, crate, 1); - Bukkit.getPluginManager().callEvent(crateOpenEvent); - - pm.closeCrate(); - p.closeInventory(); - - // Handle the DYNAMIC crates - if (getCrate().getSettings().getCrateType().isSpecialDynamicHandling() && - !getCrate().getSettings().getObtainType().isStatic()) { - if (getCrate().getSettings().getCrateType().getCategory().equals(CrateAnimationType.Category.CHEST)) { - Bukkit.getScheduler().runTaskLater(instance, () -> { - placedCrate.delete(); - placedCrate.getLocation().getBlock().setType(Material.AIR); - }, 20); - } else { - placedCrate.delete(); - placedCrate.getLocation().getBlock().setType(Material.AIR); - } - } - } - - public void timer(final AnimationDataHolder dataHolder) { - if (!dataHolder.getCurrentState().equals(AnimationDataHolder.State.COMPLETED) || - (!dataHolder.getCrateAnimation().getCrate().getSettings().isAutoClose() && !dataHolder.isFastTrack())) { - runAnimation(dataHolder); - - if (dataHolder.isFastTrack()) { - timer(dataHolder); - return; - } - - Bukkit.getScheduler().scheduleSyncDelayedTask(instance, () -> timer(dataHolder), BASE_SPEED); - } else { - endAnimation(dataHolder); - } - } - - public boolean canExecuteFor(Player p, boolean requireKeyInHand) { - PlayerManager playerManager = PlayerManager.get(instance, p); - CrateSettings crateSettings = getCrate().getSettings(); - - boolean hasPropperOpeningTools = - crateSettings.getKeyItemHandler().playerPassesKeyTest(p, requireKeyInHand) || !crateSettings.isRequireKey(); - boolean passesInventoryCheck = !playerManager.isInCrate() || playerManager.getOpenCrate().isMultiCrate(); - - return hasPropperOpeningTools && passesInventoryCheck; - } - - public void playFailToOpen(Player p, boolean playMessage, boolean failOpen) { - if (p != null) { - if (SettingsValue.PUSHBACK.getValue(instance).equals(Boolean.TRUE) && !getCrate().isMultiCrate()) { - p.setVelocity(p.getLocation().getDirection().multiply(-1)); - } - if (playMessage) { - if (failOpen) - Messages.FAIL_OPEN.msgSpecified(instance, p, new String[]{"%crate%", "%key%"}, - new String[]{crate.getDisplayName(), - crate.getSettings().getKeyItemHandler().getItem().getDisplayName(false)}); - else - Messages.ALREADY_OPENING_CRATE.msgSpecified(instance, p); - } - } - } - - public void playRequiredOpenActions(Player p, boolean fromInv, boolean force) { - PlayerManager pm = PlayerManager.get(instance, p); - CrateSettings crateSettings = getCrate().getSettings(); - - if (pm.getOpenCrate() != null && pm.getOpenCrate().isMultiCrate() && - !crateSettings.getObtainType().equals(ObtainType.STATIC)) { - PlacedCrate pc = PlacedCrate.get(instance, pm.getLastOpenCrate()); - pc.delete(); - } - - pm.openCrate(this.getCrate()); - - if (crateSettings.isRequireKey() && !force) { - crateSettings.getKeyItemHandler().takeKeyFromPlayer(p, fromInv); - } - - crateSettings.getAction().playAll(p, true); - } - - public double getRandomTickTime(double basedOff) { - return basedOff + random.nextInt(3) - random.nextInt(3); - } - - public StatusLogger getStatusLogger() { - return crate.getSettings().getStatusLogger(); - } - - public Crate getCrate() { - return crate; - } - - public FileHandler getFileHandler() { - return fileHandler; - } - - public CrateAnimationType getAnimationType() { - return animationType; - } - - public enum KeyType { - ESC - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/types/animations/CrateAnimationType.java b/src/main/java/me/ztowne13/customcrates/crates/types/animations/CrateAnimationType.java deleted file mode 100644 index 039f8d3..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/types/animations/CrateAnimationType.java +++ /dev/null @@ -1,147 +0,0 @@ -package me.ztowne13.customcrates.crates.types.animations; - -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.types.animations.block.OpenChestAnimation; -import me.ztowne13.customcrates.crates.types.animations.inventory.*; -import me.ztowne13.customcrates.crates.types.animations.minimal.GiveKeyAnimation; -import me.ztowne13.customcrates.crates.types.animations.minimal.GiveKeyAnimationDataHolder; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -public enum CrateAnimationType { - INV_ROULETTE("Roulette", Category.INVENTORY, true), - - INV_MENU("Menu", Category.INVENTORY, true), - - INV_CSGO("CSGO", Category.INVENTORY, true), - - INV_ENCLOSE("Enclose", Category.INVENTORY, true), - - INV_DISCOVER("Discover", Category.INVENTORY, false), - - BLOCK_CRATEOPEN("OpenChest", Category.CHEST, true), - - //BLOCK_CRATEOPEN_ROLLING("CrateType.Block.OpenChestRolling", Category.CHEST), - - GIVE_KEY("", Category.NONE, true); - - private final String prefix; - private final Category category; - private final boolean canFastTrackOnReload; - - CrateAnimationType(String prefix, Category category, boolean canFastTrackOnReload) { - this.prefix = prefix; - this.category = category; - this.canFastTrackOnReload = canFastTrackOnReload; - } - - public void setupFor(Crate crates) { - CrateAnimation ch; - - switch (this) { - case INV_ROULETTE: - ch = new RouletteAnimation(crates); - break; - case INV_CSGO: - ch = new CSGOAnimation(crates); - break; - case INV_MENU: - ch = new MenuAnimation(crates); - break; - case INV_ENCLOSE: - ch = new EncloseAnimation(crates); - break; - case INV_DISCOVER: - ch = new DiscoverAnimation(crates); - break; - case BLOCK_CRATEOPEN: - ch = new OpenChestAnimation(crates); - break; - /*case BLOCK_CRATEOPEN_ROLLING: - ch = new OpenChestRollingAnimation(null, crates); - break;*/ - case GIVE_KEY: - default: - ch = new GiveKeyAnimation(crates); - } - - crates.getSettings().setCrateAnimation(ch); - } - - public AnimationDataHolder newDataHolderInstance(Player player, Location location, CrateAnimation crateAnimation) { - switch (this) { - case INV_ROULETTE: - return new RouletteAnimationDataHolder(player, location, (RouletteAnimation) crateAnimation); - case INV_CSGO: - return new CSGOAnimationDataHolder(player, location, (CSGOAnimation) crateAnimation); - case INV_DISCOVER: - return new DiscoverAnimationDataHolder(player, location, (DiscoverAnimation) crateAnimation); - case INV_ENCLOSE: - return new EncloseAnimationDataHolder(player, location, (EncloseAnimation) crateAnimation); - case INV_MENU: - return new MenuAnimationDataHolder(player, location, (MenuAnimation) crateAnimation); - case BLOCK_CRATEOPEN: - case GIVE_KEY: - return new GiveKeyAnimationDataHolder(player, location, (GiveKeyAnimation) crateAnimation); - default: - return null; - } - } - - public int getUses() { - int uses = 0; - for (Crate crate : Crate.getLoadedCrates().values()) { - if (!crate.isMultiCrate() && crate.getSettings().getCrateType().equals(this)) { - uses++; - } - } - - return uses; - } - - public String getPrefix() { - return "CrateType." + getCategory().getPrefix() + prefix; - } - - public String getPrefixDotted() { - return getPrefix() + "."; - } - - public Category getCategory() { - return category; - } - - public boolean isSpecialDynamicHandling() { - return category.isSpecialDynamicHandling(); - } - - public boolean isCanFastTrackOnReload() { - return canFastTrackOnReload; - } - - public enum Category { - INVENTORY(false, "Inventory."), - - BLOCK(true, "Block."), - - CHEST(true, "Block."), - - NONE(false, ""); - - boolean specialDynamicHandling; - String prefix; - - Category(boolean specialDynamicHandling, String prefix) { - this.specialDynamicHandling = specialDynamicHandling; - this.prefix = prefix; - } - - public boolean isSpecialDynamicHandling() { - return specialDynamicHandling; - } - - public String getPrefix() { - return prefix; - } - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/types/animations/block/NMSChestState.java b/src/main/java/me/ztowne13/customcrates/crates/types/animations/block/NMSChestState.java deleted file mode 100644 index 89a8978..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/types/animations/block/NMSChestState.java +++ /dev/null @@ -1,36 +0,0 @@ -package me.ztowne13.customcrates.crates.types.animations.block; - -import me.ztowne13.customcrates.utils.ReflectionUtilities; -import org.bukkit.Location; -import org.bukkit.block.Block; - -public class NMSChestState { - - public void playChestAction(Block chest, boolean open) { - try { - Location location = chest.getLocation(); - - Class craftWorldClass = ReflectionUtilities.getOBCClass("CraftWorld"); - Object craftWorld = craftWorldClass.cast(location.getWorld()); - Object world = ReflectionUtilities.getHandle(craftWorld); - - Class blockPositionClass = ReflectionUtilities.getNMSClass("BlockPosition"); - Object blockPosition = blockPositionClass.getConstructor(Double.TYPE, Double.TYPE, Double.TYPE) - .newInstance(location.getX(), location.getY(), location.getZ()); - - Object iBlockData = - ReflectionUtilities.getMethod(world.getClass(), "getType", blockPosition.getClass()) - .invoke(world, blockPosition); - Object block = - ReflectionUtilities.getMethod(iBlockData.getClass(), "getBlock").invoke(iBlockData); - - - ReflectionUtilities.getMethod(world.getClass(), "playBlockAction", - blockPosition.getClass(), ReflectionUtilities.getNMSClass("Block"), Integer.TYPE, - Integer.TYPE).invoke(world, blockPosition, block, 1, open ? 1 : 0); - } catch (Exception exc) { - exc.printStackTrace(); - } - } - -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/types/animations/block/OpenChestAnimation.java b/src/main/java/me/ztowne13/customcrates/crates/types/animations/block/OpenChestAnimation.java deleted file mode 100644 index f9e3ec3..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/types/animations/block/OpenChestAnimation.java +++ /dev/null @@ -1,174 +0,0 @@ -package me.ztowne13.customcrates.crates.types.animations.block; - -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.CrateState; -import me.ztowne13.customcrates.crates.PlacedCrate; -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import me.ztowne13.customcrates.crates.types.animations.AnimationDataHolder; -import me.ztowne13.customcrates.crates.types.animations.CrateAnimation; -import me.ztowne13.customcrates.crates.types.animations.CrateAnimationType; -import me.ztowne13.customcrates.interfaces.logging.StatusLogger; -import me.ztowne13.customcrates.interfaces.logging.StatusLoggerEvent; -import me.ztowne13.customcrates.players.PlayerManager; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.entity.Item; -import org.bukkit.entity.Player; -import org.bukkit.util.Vector; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public class OpenChestAnimation extends CrateAnimation { - private static final List items = new ArrayList<>(); - private final HashMap rewardMap = new HashMap<>(); - private final HashMap placedCrateMap = new HashMap<>(); - private int openDuration; - private boolean earlyRewardHologram; - private boolean attachTo = true; - private boolean earlyEffects = false; - private long rewardHoloDelay; - private Location loc; - - public OpenChestAnimation(Crate crate) { - super(crate, CrateAnimationType.BLOCK_CRATEOPEN); - } - - public static void removeAllItems() { - for (Item item : items) - item.remove(); - } - - @Override - public void tickAnimation(AnimationDataHolder dataHolder, boolean update) { - // EMPTY - } - - @Override - public void endAnimation(AnimationDataHolder dataHolder) { - // EMPTY - } - - @Override - public boolean updateTicks(AnimationDataHolder dataHolder) { - return false; - } - - @Override - public void checkStateChange(AnimationDataHolder dataHolder, boolean update) { - // EMPTY - } - - @Override - public boolean startAnimation(Player player, Location location, boolean requireKeyInHand, boolean force) { - this.loc = location; - - if (force || canExecuteFor(player, requireKeyInHand)) { - if (getCrate().getSettings().getCrateType().isSpecialDynamicHandling() && !getCrate().getSettings().getObtainType().isStatic()) { - PlacedCrate placedCrate = PlayerManager.get(instance, player).getLastOpenedPlacedCrate(); - placedCrate.setCratesEnabled(false); - - placedCrateMap.put(player, placedCrate); - } - playAnimation(player, location); - playRequiredOpenActions(player, !requireKeyInHand, force); - return true; - } - - playFailToOpen(player, true, !PlayerManager.get(instance, player).isInCrate()); - return false; - } - - public void playAnimation(final Player player, final Location location) { - Reward reward = getCrate().getSettings().getReward().getRandomReward(); - final ArrayList rewards = new ArrayList<>(); - rewards.add(reward.getDisplayName(true)); - rewardMap.put(player, reward); - - Location upOne = location.clone(); - upOne.setY(upOne.getY() + 1); - upOne.setX(upOne.getX() + .5); - upOne.setZ(upOne.getZ() + .5); - - final Item item = location.getWorld().dropItem(upOne, reward.getDisplayBuilder().getStack()); - item.setPickupDelay(100000); - item.setVelocity(new Vector(0, item.getVelocity().getY(), 0)); - items.add(item); - - ArrayList rewardsStr = new ArrayList<>(); - rewardsStr.add(reward); - - if (earlyEffects) { - getCrate().tick(this.loc, CrateState.OPEN, player, rewardsStr); - } - - if (attachTo) { - crate.getSettings().getAction().playRewardHologram(player, rewards, .6, true, item, openDuration); - } else if (isEarlyRewardHologram()) { - Bukkit.getScheduler().scheduleSyncDelayedTask(instance, () -> crate.getSettings().getAction().playRewardHologram(player, rewards, .6), rewardHoloDelay); - } - - new NMSChestState().playChestAction(location.getBlock(), true); - - Bukkit.getScheduler().scheduleSyncDelayedTask(instance, () -> { - new NMSChestState().playChestAction(location.getBlock(), false); - items.remove(item); - item.remove(); - endAnimation(player); - }, openDuration); - } - - @Override - public void loadDataValues(StatusLogger statusLogger) { - openDuration = fileHandler.getFileDataLoader().loadInt(prefix + "chest-open-duration", 80, statusLogger, - StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_OPENCHEST_CHEST_OPEN_DURATION_SUCCESS, - StatusLoggerEvent.ANIMATION_OPENCHEST_CHEST_OPEN_DURATION_INVALID); - - earlyRewardHologram = fileHandler.getFileDataLoader().loadBoolean(prefix + "early-reward-hologram", true, statusLogger, - StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_OPENCHEST_EARLY_REWARD_SUCCESS, - StatusLoggerEvent.ANIMATION_OPENCHEST_EARLY_REWARD_INVALID); - - rewardHoloDelay = fileHandler.getFileDataLoader().loadLong(prefix + "reward-hologram-delay", 0, statusLogger, - StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_OPENCHEST_REWARD_HOLO_DELAY_SUCCESS, - StatusLoggerEvent.ANIMATION_OPENCHEST_REWARD_HOLO_DELAY_INVALID); - - attachTo = fileHandler.getFileDataLoader().loadBoolean(prefix + "reward-holo-attach-to-item", true, statusLogger, - StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_OPENCHEST_ATTACH_TO_SUCCESS, - StatusLoggerEvent.ANIMATION_OPENCHEST_ATTACH_TO_INVALID); - - earlyEffects = fileHandler.getFileDataLoader().loadBoolean(prefix + "early-open-actions", false, statusLogger, - StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_OPENCHEST_EARLY_OPEN_ACTIONS_SUCCESS, - StatusLoggerEvent.ANIMATION_OPENCHEST_EARLY_OPEN_ACTIONS_INVALID); - - if (attachTo) - earlyRewardHologram = true; - } - - public void endAnimation(Player player) { - Reward reward = rewardMap.get(player); - rewardMap.remove(player); - PlacedCrate placedCrate = placedCrateMap.get(player); - placedCrateMap.remove(player); - - ArrayList rewards = new ArrayList<>(); - rewards.add(reward); - - finishAnimation(player, rewards, placedCrate); - if (!earlyEffects) - getCrate().tick(loc, CrateState.OPEN, player, rewards); - } - - public boolean isEarlyRewardHologram() { - return earlyRewardHologram; - } - - public void setEarlyRewardHologram(boolean earlyRewardHologram) { - this.earlyRewardHologram = earlyRewardHologram; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/CSGOAnimation.java b/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/CSGOAnimation.java deleted file mode 100644 index ed99016..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/CSGOAnimation.java +++ /dev/null @@ -1,288 +0,0 @@ -package me.ztowne13.customcrates.crates.types.animations.inventory; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.CrateState; -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import me.ztowne13.customcrates.crates.options.sounds.SoundData; -import me.ztowne13.customcrates.crates.types.animations.AnimationDataHolder; -import me.ztowne13.customcrates.crates.types.animations.CrateAnimation; -import me.ztowne13.customcrates.crates.types.animations.CrateAnimationType; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.interfaces.logging.StatusLogger; -import me.ztowne13.customcrates.interfaces.logging.StatusLoggerEvent; - -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.Random; - -/** - * Created by ztowne13 on 6/30/16. - */ -public class CSGOAnimation extends InventoryCrateAnimation { - private final ArrayList fillerBlocks = new ArrayList<>(); - private final Random random = new Random(); - private double finalTickLength; - private double tickIncrease; - private int glassUpdateTicks = 2; - private int closeSpeed = -1; - private ItemBuilder identifierBlock = null; - - public CSGOAnimation(Crate crate) { - super(crate, CrateAnimationType.INV_CSGO); - } - - @Override - public void tickInventory(InventoryAnimationDataHolder dataHolder, boolean update) { - CSGOAnimationDataHolder cdh = (CSGOAnimationDataHolder) dataHolder; - - switch (cdh.getCurrentState()) { - case PLAYING: - drawFillers(cdh, glassUpdateTicks); - - if (update) { - playSound(cdh); - updateRewards(cdh); - } - - drawRewards(cdh, 0); - break; - case WAITING: - drawRewards(cdh, 0); - break; - case CLOSING: - case ENDING: - if (cdh.isUpdateAnimatedClose()) { - cdh.setUpdateAnimatedClose(false); - drawFillers(cdh, 1); - } - drawRewards(cdh, cdh.getAnimatedCloseTicks()); - break; - default: - break; - } - } - - @Override - public void checkStateChange(AnimationDataHolder dataHolder, boolean update) { - CSGOAnimationDataHolder cdh = (CSGOAnimationDataHolder) dataHolder; - - switch (cdh.getCurrentState()) { - case PLAYING: - if (update && cdh.getCurrentTicks() > getFinalTickLength()) - cdh.setCurrentState(AnimationDataHolder.State.WAITING); - break; - case WAITING: - if (cdh.getWaitingTicks() == 10) { - if (getCloseSpeed() > -1) - cdh.setCurrentState(AnimationDataHolder.State.CLOSING); - else - cdh.setCurrentState(AnimationDataHolder.State.ENDING); - } - break; - case CLOSING: - if (cdh.getAnimatedCloseTicks() == 3) { - cdh.setWaitingTicks(0); - cdh.setCurrentState(AnimationDataHolder.State.ENDING); - } - break; - case ENDING: - if (cdh.getWaitingTicks() == 50) { - cdh.setCurrentState(AnimationDataHolder.State.COMPLETED); - } - break; - default: - break; - } - } - - /** - * Updates all of the tick values that track how fast and slow the plugin is going - * - * @return Returns whether or not the rewards should be updated and sound should be played. - */ - @Override - public boolean updateTicks(AnimationDataHolder dataHolder) { - CSGOAnimationDataHolder cdh = (CSGOAnimationDataHolder) dataHolder; - - switch (cdh.getCurrentState()) { - case PLAYING: - if (cdh.getIndividualTicks() * CrateAnimation.BASE_SPEED >= cdh.getCurrentTicks() - 1.1) { - cdh.setUpdates(cdh.getUpdates() + 1); - cdh.setIndividualTicks(0); - - cdh.setCurrentTicks(.05 * Math.pow((getTickIncrease() / 40) + 1, cdh.getUpdates())); - - return true; - } - break; - case CLOSING: - if (cdh.getTotalTicks() % getCloseSpeed() == 0) { - cdh.setUpdateAnimatedClose(true); - cdh.setAnimatedCloseTicks(cdh.getAnimatedCloseTicks() + 1); - } - break; - case WAITING: - case ENDING: - cdh.setWaitingTicks(cdh.getWaitingTicks() + 1); - break; - default: - break; - } - - return false; - } - - public void updateRewards(CSGOAnimationDataHolder cdh) { - for (int i = 0; i < cdh.getDisplayedRewards().length; i++) { - Reward r = cdh.getDisplayedRewards()[i]; - int numToSet = i - 1; - - if (r != null && numToSet >= 0) { - cdh.getDisplayedRewards()[numToSet] = cdh.getDisplayedRewards()[i]; - } - } - - Reward r = getCrate().getSettings().getReward().getRandomReward(); - cdh.getDisplayedRewards()[cdh.getDisplayedRewards().length - 1] = r; - } - - public void drawRewards(CSGOAnimationDataHolder cdh, int sideIndent) { - InventoryBuilder inv = cdh.getInventoryBuilder(); - - for (int i = sideIndent; i < cdh.getDisplayedRewards().length - sideIndent; i++) { - Reward r = cdh.getDisplayedRewards()[i]; - if (r != null) { - inv.setItem(i + 10, r.getDisplayBuilder()); - } - } - - } - - @Override - public void drawIdentifierBlocks(InventoryAnimationDataHolder inventoryAnimationDataHolder) { - InventoryBuilder inv = inventoryAnimationDataHolder.getInventoryBuilder(); - - inv.setItem(4, getIdentifierBlock()); - inv.setItem(22, getIdentifierBlock()); - } - - @Override - public ItemBuilder getFiller() { - return getFillerBlocks().get(random.nextInt(getFillerBlocks().size())); - } - - @Override - public void endAnimation(AnimationDataHolder dataHolder) { - CSGOAnimationDataHolder cdh = (CSGOAnimationDataHolder) dataHolder; - - ArrayList rewards = new ArrayList<>(); - rewards.add(cdh.getDisplayedRewards()[cdh.getDisplayedRewards().length / 2]); - - finishAnimation(dataHolder.getPlayer(), rewards, null); - getCrate().tick(cdh.getLocation(), CrateState.OPEN, dataHolder.getPlayer(), rewards); - } - - @Override - public void loadDataValues(StatusLogger statusLogger) { - invName = fileHandler.getFileDataLoader() - .loadString(prefix + "inv-name", getStatusLogger(), StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_CSGO_INVNAME_SUCCESS); - - tickSound = fileHandler.getFileDataLoader() - .loadSound(prefix + "tick-sound", getStatusLogger(), StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_CSGO_TICKSOUND_SOUND_SUCCESS, - StatusLoggerEvent.ANIMATION_CSGO_TICKSOUND_SOUND_FAILURE, - StatusLoggerEvent.ANIMATION_CSGO_TICKSOUND_VOLUME_SUCCESS, - StatusLoggerEvent.ANIMATION_CSGO_TICKSOUND_VOLUME_INVALID, - StatusLoggerEvent.ANIMATION_CSGO_TICKSOUND_VOLUMEPITCH_FAILURE, - StatusLoggerEvent.ANIMATION_CSGO_TICKSOUND_PITCH_SUCCESS, - StatusLoggerEvent.ANIMATION_CSGO_TICKSOUND_PITCH_INVALID); - - identifierBlock = fileHandler.getFileDataLoader() - .loadItem(prefix + "identifier-block", new ItemBuilder(XMaterial.AIR), getStatusLogger(), - StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_CSGO_IDBLOCK_INVALID - ); - identifierBlock.setDisplayName("&f"); - - finalTickLength = fileHandler.getFileDataLoader() - .loadDouble(prefix + "final-crate-tick-length", 7, getStatusLogger(), - StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_CSGO_FINALTICKLENGTH_SUCCESS, - StatusLoggerEvent.ANIMATION_CSGO_FINALTICKLENGTH_INVALID); - - glassUpdateTicks = fileHandler.getFileDataLoader().loadInt(prefix + "tile-update-ticks", 2, getStatusLogger(), - StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, StatusLoggerEvent.ANIMATION_CSGO_GLASSUPDATE_SUCCESS, - StatusLoggerEvent.ANIMATION_CSGO_GLASSUPDATE_INVALID); - - closeSpeed = fileHandler.getFileDataLoader() - .loadInt(prefix + "close-speed", -1, getStatusLogger(), StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_CSGO_CLOSESPEED_SUCCESS, - StatusLoggerEvent.ANIMATION_CSGO_CLOSESPEED_INVALID); - - tickIncrease = fileHandler.getFileDataLoader().loadDouble(prefix + "tick-speed-per-run", 0.4, getStatusLogger(), - StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_CSGO_TICKSPEED_SUCCESS, StatusLoggerEvent.ANIMATION_CSGO_TICKSPEED_INVALID); - - try { - for (String unParsed : getFileHandler().get().getStringList("CrateType.Inventory.CSGO.filler-blocks")) { - String[] args = unParsed.split(";"); - try { - Optional optional = XMaterial.matchXMaterial(unParsed); - if (!optional.isPresent()) { - StatusLoggerEvent.ANIMATION_CSGO_FILLERBLOCK_MATERIAL_INVALID - .log(getStatusLogger(), args[0]); - continue; - } - getFillerBlocks().add(new ItemBuilder(optional.get(), 1).setDisplayName("&f")); - - StatusLoggerEvent.ANIMATION_CSGO_FILLERBLOCK_MATERIAL_SUCCESS - .log(getStatusLogger(), unParsed); - } catch (Exception exc) { - StatusLoggerEvent.ANIMATION_CSGO_FILLERBLOCK_ITEM_INVALID.log(getStatusLogger(), unParsed); - } - } - } catch (Exception exc) { - StatusLoggerEvent.ANIMATION_CSGO_FILLERBLOCK_NONEXISTENT.log(getStatusLogger()); - } - } - - @Override - public void setTickSound(SoundData tickSound) { - this.tickSound = tickSound; - } - - @Override - public String getInvName() { - return invName; - } - - @Override - public void setInvName(String invName) { - this.invName = invName; - } - - public double getFinalTickLength() { - return finalTickLength; - } - - public double getTickIncrease() { - return tickIncrease; - } - - public int getCloseSpeed() { - return closeSpeed; - } - - public ItemBuilder getIdentifierBlock() { - return identifierBlock; - } - - public List getFillerBlocks() { - return fillerBlocks; - } - -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/CSGOAnimationDataHolder.java b/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/CSGOAnimationDataHolder.java deleted file mode 100644 index 2d6f955..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/CSGOAnimationDataHolder.java +++ /dev/null @@ -1,56 +0,0 @@ -package me.ztowne13.customcrates.crates.types.animations.inventory; - -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -/** - * Created by ztowne13 on 3/6/16. - */ -public class CSGOAnimationDataHolder extends InventoryAnimationDataHolder { - private final Reward[] displayedRewards = new Reward[7]; - private double currentTicks = 1.1; - private double updates = 0; - private int animatedCloseTicks = 0; - private boolean updateAnimatedClose = false; - - public CSGOAnimationDataHolder(Player player, Location location, CSGOAnimation crateAnimation) { - super(player, location, crateAnimation, 27); - } - - public double getCurrentTicks() { - return currentTicks; - } - - public void setCurrentTicks(double currentTicks) { - this.currentTicks = currentTicks; - } - - public double getUpdates() { - return updates; - } - - public void setUpdates(double updates) { - this.updates = updates; - } - - public int getAnimatedCloseTicks() { - return animatedCloseTicks; - } - - public void setAnimatedCloseTicks(int animatedCloseTicks) { - this.animatedCloseTicks = animatedCloseTicks; - } - - public Reward[] getDisplayedRewards() { - return displayedRewards; - } - - public boolean isUpdateAnimatedClose() { - return updateAnimatedClose; - } - - public void setUpdateAnimatedClose(boolean updateAnimatedClose) { - this.updateAnimatedClose = updateAnimatedClose; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/DiscoverAnimation.java b/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/DiscoverAnimation.java deleted file mode 100644 index 01df3c5..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/DiscoverAnimation.java +++ /dev/null @@ -1,393 +0,0 @@ -package me.ztowne13.customcrates.crates.types.animations.inventory; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.CrateState; -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import me.ztowne13.customcrates.crates.options.sounds.SoundData; -import me.ztowne13.customcrates.crates.types.animations.AnimationDataHolder; -import me.ztowne13.customcrates.crates.types.animations.CrateAnimationType; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.interfaces.logging.StatusLogger; -import me.ztowne13.customcrates.interfaces.logging.StatusLoggerEvent; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; - -import java.util.ArrayList; -import java.util.Random; - -/** - * Created by ztowne13 on 7/7/16. - *

- * inv-name: '&8&l> &6&l%crate%' - * tick-sound: BLOCK_STONE_HIT, 5, 5 - * click-sound: ENTITY_HORSE_GALLOP, 5, 5 - * uncover-sound: ENTITY_PLAYER_LEVELUP, 5, 5 - * minimum-rewards: 1 - * maximum-rewards: 4 - * count: true - * random-display-duration: 50 - * uncover-block: CHEST;0 - */ -public class DiscoverAnimation extends InventoryCrateAnimation { - private final Random random = new Random(); - private SoundData clickSound; - private SoundData uncoverSound; - private int minRewards; - private int maxRewards; - private int shuffleDisplayDuration; - private int invRows; - private String coverBlockName = "&aReward #%numbetsorr%"; - private String coverBlockLore = "&7You have &f%remaining-clicks% rewards to chose from."; - private String rewardBlockName = "&aReward"; - private String rewardBlockUnlockName = "&aClick me to unlock your reward."; - private String rewardBlockWaitingName = "&aUncover all rewards to unlock"; - private ItemBuilder uncoverBlock; - private ItemBuilder rewardBlock; - private boolean count; - - public DiscoverAnimation(Crate crate) { - super(crate, CrateAnimationType.INV_DISCOVER); - } - - @Override - public void tickInventory(InventoryAnimationDataHolder dataHolder, boolean update) { - DiscoverAnimationDataHolder dadh = (DiscoverAnimationDataHolder) dataHolder; - - switch (dadh.getCurrentState()) { - case PLAYING: - drawFillers(dadh, 1); - updateUncoverTiles(dadh); - drawUncoverTiles(dadh); - break; - case WAITING: - drawFillers(dadh, 1); - drawUncoverTiles(dadh); - break; - case SHUFFLING: - drawFillers(dadh, 1); - updateShufflingTiles(dadh); - drawShufflingTiles(dadh); - break; - case UNCOVERING: - drawFillers(dadh, 1); - updateWinningTiles(dadh); - drawWinningTiles(dadh); - break; - case ENDING: - drawFillers(dadh, 1); - drawWinningTiles(dadh); - break; - default: - break; - } - } - - @Override - public void drawIdentifierBlocks(InventoryAnimationDataHolder inventoryAnimationDataHolder) { - // EMPTY - } - - @Override - public ItemBuilder getFiller() { - return new ItemBuilder(XMaterial.AIR); - } - - @Override - public boolean updateTicks(AnimationDataHolder dataHolder) { - DiscoverAnimationDataHolder dadh = (DiscoverAnimationDataHolder) dataHolder; - - switch (dadh.getCurrentState()) { - case WAITING: - case ENDING: - dadh.setWaitingTicks(dataHolder.getWaitingTicks() + 1); - break; - case SHUFFLING: - dadh.setShuffleTicks(dadh.getShuffleTicks() + (int) BASE_SPEED); - break; - default: - break; - } - - return false; - } - - @Override - public void checkStateChange(AnimationDataHolder dataHolder, boolean update) { - DiscoverAnimationDataHolder dadh = (DiscoverAnimationDataHolder) dataHolder; - - switch (dadh.getCurrentState()) { - case PLAYING: - if (dadh.getRemainingClicks() <= 0) { - dadh.setCurrentState(AnimationDataHolder.State.WAITING); - } - break; - case WAITING: - if (dadh.getWaitingTicks() == 20) { - dadh.setWaitingTicks(0); - dadh.setCurrentState(AnimationDataHolder.State.SHUFFLING); - } - break; - case SHUFFLING: - if (dadh.getShuffleTicks() > getShuffleDisplayDuration()) { - dadh.setCurrentState(AnimationDataHolder.State.UNCOVERING); - } - break; - case UNCOVERING: - if (dadh.getAlreadyDisplayedRewards().keySet().size() == dadh.getAlreadyChosenSlots().size()) { - dadh.setCurrentState(AnimationDataHolder.State.ENDING); - } - break; - case ENDING: - if (dadh.getWaitingTicks() == 50) { - dadh.setCurrentState(AnimationDataHolder.State.COMPLETED); - } - break; - default: - break; - } - } - - public void drawUncoverTiles(DiscoverAnimationDataHolder dadh) { - InventoryBuilder inventoryBuilder = dadh.getInventoryBuilder(); - - ItemBuilder uncoverBlockIb = uncoverBlock.setLore("") - .addLore(coverBlockLore.replace("%remaining-clicks%", dadh.getRemainingClicks() + "")); - ItemBuilder alreadyUncoveredIb = rewardBlock; - alreadyUncoveredIb.setDisplayName(rewardBlockWaitingName); - - for (int i = 0; i < inventoryBuilder.getSize(); i++) { - if (dadh.getAlreadyChosenSlots().contains(i)) { - inventoryBuilder.setItem(i, alreadyUncoveredIb); - } else { - uncoverBlockIb.setDisplayName(coverBlockName.replace("%number%", (i + 1) + "")); - if (count) { - uncoverBlockIb.getStack().setAmount(i + 1); - } - inventoryBuilder.setItem(i, uncoverBlockIb); - } - } - } - - public void updateUncoverTiles(DiscoverAnimationDataHolder dadh) { - for (int slot : dadh.getClickedSlots()) { - if (!dadh.getAlreadyChosenSlots().contains(slot) && dadh.getRemainingClicks() != 0) { - dadh.getAlreadyChosenSlots().add(slot); - dadh.setRemainingClicks(dadh.getRemainingClicks() - 1); - - if (clickSound != null) - clickSound.playTo(dadh.getPlayer(), dadh.getLocation()); - } - } - - dadh.getClickedSlots().clear(); - } - - public void drawShufflingTiles(DiscoverAnimationDataHolder dadh) { - ItemBuilder reward = rewardBlock; - reward.setDisplayName(rewardBlockName); - - for (int i = 0; i < dadh.getShufflingTiles().size(); i++) { - dadh.getInventoryBuilder().setItem(dadh.getShufflingTiles().get(i), reward); - } - } - - public void updateShufflingTiles(DiscoverAnimationDataHolder dadh) { - dadh.getShufflingTiles().clear(); - - for (int i = 0; i < dadh.getInventoryBuilder().getSize(); i++) { - if (random.nextInt(7) == 1) { - dadh.getShufflingTiles().add(i); - } - } - } - - public void drawWinningTiles(DiscoverAnimationDataHolder dadh) { - InventoryBuilder inventoryBuilder = dadh.getInventoryBuilder(); - - ItemBuilder reward = rewardBlock; - reward.setDisplayName(rewardBlockUnlockName); - - for (int i : dadh.getAlreadyChosenSlots()) { - if (dadh.getAlreadyDisplayedRewards().containsKey(i)) { - inventoryBuilder.setItem(i, dadh.getAlreadyDisplayedRewards().get(i).getDisplayBuilder()); - } else { - inventoryBuilder.setItem(i, reward); - } - } - } - - public void updateWinningTiles(DiscoverAnimationDataHolder dadh) { - for (int slot : dadh.getClickedSlots()) { - if (dadh.getAlreadyChosenSlots().contains(slot) && !dadh.getAlreadyDisplayedRewards().containsKey(slot)) { - Reward newR = getCrate().getSettings().getReward().getRandomReward(); - - if (uncoverSound != null) - uncoverSound.playTo(dadh.getPlayer(), dadh.getLocation()); - - dadh.getAlreadyDisplayedRewards().put(slot, newR); - } - } - - dadh.getClickedSlots().clear(); - } - - @Override - public void endAnimation(AnimationDataHolder dataHolder) { - DiscoverAnimationDataHolder dadh = (DiscoverAnimationDataHolder) dataHolder; - Player player = dadh.getPlayer(); - - ArrayList rewards = new ArrayList<>(dadh.getAlreadyDisplayedRewards().values()); - - finishAnimation(player, rewards, null); - getCrate().tick(dadh.getLocation(), CrateState.OPEN, player, rewards); - } - - @Override - public void loadDataValues(StatusLogger statusLogger) { - FileConfiguration fc = getFileHandler().get(); - - invName = fc.getString(prefix + "inv-name"); - - invRows = fileHandler.getFileDataLoader() - .loadInt(prefix + "inventory-rows", 3, statusLogger, StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_DISCOVER_INVROWS_SUCCESS, - StatusLoggerEvent.ANIMATION_DISCOVER_INVROWS_INVALID); - - minRewards = fileHandler.getFileDataLoader() - .loadInt(prefix + "minimum-rewards", 1, statusLogger, StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_DISCOVER_MINREWARDS_SUCCESS, - StatusLoggerEvent.ANIMATION_DISCOVER_MINREWARDS_INVALID); - - maxRewards = fileHandler.getFileDataLoader() - .loadInt(prefix + "maximum-rewards", 1, statusLogger, StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_DISCOVER_MAXREWARDS_SUCCESS, - StatusLoggerEvent.ANIMATION_DISCOVER_MAXREWARDS_INVALID); - - shuffleDisplayDuration = fileHandler.getFileDataLoader() - .loadInt(prefix + "random-display-duration", 1, statusLogger, StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_DISCOVER_RANDDISPLAYLOCATION_SUCCESS, - StatusLoggerEvent.ANIMATION_DISCOVER_RANDDISPLAYLOCATION_INVALID); - - uncoverBlock = - fileHandler.getFileDataLoader().loadItem(prefix + "cover-block", new ItemBuilder(XMaterial.CHEST), statusLogger, - StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_DISCOVER_COVERBLOCK_INVALID - ); - - count = fileHandler.getFileDataLoader().loadBoolean(prefix + "count", true, statusLogger, StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_DISCOVER_COUNT_SUCCESS, - StatusLoggerEvent.ANIMATION_DISCOVER_COUNT_INVALID); - - tickSound = - fileHandler.getFileDataLoader().loadSound(prefix + "tick-sound", statusLogger, StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_DISCOVER_TICKSOUND_SOUND_SUCCESS, - StatusLoggerEvent.ANIMATION_DISCOVER_TICKSOUND_SOUND_FAILURE, - StatusLoggerEvent.ANIMATION_DISCOVER_TICKSOUND_VOLUME_SUCCESS, - StatusLoggerEvent.ANIMATION_DISCOVER_TICKSOUND_VOLUME_INVALID, - StatusLoggerEvent.ANIMATION_DISCOVER_TICKSOUND_PITCHVOL_INVALID, - StatusLoggerEvent.ANIMATION_DISCOVER_TICKSOUND_PITCH_SUCCESS, - StatusLoggerEvent.ANIMATION_DISCOVER_TICKSOUND_PITCH_INVALID); - - clickSound = - fileHandler.getFileDataLoader().loadSound(prefix + "click-sound", statusLogger, StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_DISCOVER_CLICKSOUND_SOUND_SUCCESS, - StatusLoggerEvent.ANIMATION_DISCOVER_CLICKSOUND_SOUND_FAILURE, - StatusLoggerEvent.ANIMATION_DISCOVER_CLICKSOUND_VOLUME_SUCCESS, - StatusLoggerEvent.ANIMATION_DISCOVER_CLICKSOUND_VOLUME_INVALID, - StatusLoggerEvent.ANIMATION_DISCOVER_CLICKSOUND_PITCHVOL_INVALID, - StatusLoggerEvent.ANIMATION_DISCOVER_CLICKSOUND_PITCH_SUCCESS, - StatusLoggerEvent.ANIMATION_DISCOVER_CLICKSOUND_PITCH_INVALID); - - uncoverSound = - fileHandler.getFileDataLoader().loadSound(prefix + "uncover-sound", statusLogger, StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_DISCOVER_UNCOVERSOUND_SOUND_SUCCESS, - StatusLoggerEvent.ANIMATION_DISCOVER_UNCOVERSOUND_SOUND_FAILURE, - StatusLoggerEvent.ANIMATION_DISCOVER_UNCOVERSOUND_VOLUME_SUCCESS, - StatusLoggerEvent.ANIMATION_DISCOVER_UNCOVERSOUND_VOLUME_INVALID, - StatusLoggerEvent.ANIMATION_DISCOVER_UNCOVERSOUND_PITCHVOL_INVALID, - StatusLoggerEvent.ANIMATION_DISCOVER_UNCOVERSOUND_PITCH_SUCCESS, - StatusLoggerEvent.ANIMATION_DISCOVER_UNCOVERSOUND_PITCH_INVALID); - - rewardBlock = fileHandler.getFileDataLoader() - .loadItem(prefix + "reward-block", new ItemBuilder(XMaterial.GREEN_STAINED_GLASS_PANE), statusLogger, - StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_DISCOVER_REWARDBLOCK_INVALID - ); - rewardBlock.setDisplayName(""); - - coverBlockName = fileHandler.getFileDataLoader() - .loadString(prefix + "cover-block-name", getStatusLogger(), StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_DISCOVER_COVER_BLOCK_NAME_SUCCESS); - - coverBlockLore = fileHandler.getFileDataLoader() - .loadString(prefix + "cover-block-lore", getStatusLogger(), StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_DISCOVER_COVER_BLOCK_LORE_SUCCESS); - - rewardBlockName = fileHandler.getFileDataLoader() - .loadString(prefix + "reward-block-name", getStatusLogger(), StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_DISCOVER_REWARD_BLOCK_NAME_SUCCESS); - - rewardBlockUnlockName = fileHandler.getFileDataLoader().loadString(prefix + "reward-block-unlock-name", getStatusLogger(), - StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_DISCOVER_REWARD_BLOCK_UNBLOCK_NAME_SUCCESS); - - rewardBlockWaitingName = fileHandler.getFileDataLoader().loadString(prefix + "reward-block-waiting-name", getStatusLogger(), - StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_DISCOVER_REWARD_BLOCK_WAITING_NAME_SUCCESS); - } - - @Override - public String getInvName() { - return invName; - } - - @Override - public void setInvName(String invName) { - this.invName = invName; - } - - public String getPrefix() { - return prefix; - } - - public void setPrefix(String prefix) { - this.prefix = prefix; - } - - @Override - public SoundData getTickSound() { - return tickSound; - } - - @Override - public void setTickSound(SoundData tickSound) { - this.tickSound = tickSound; - } - - - public int getMinRewards() { - return minRewards; - } - - public int getMaxRewards() { - return maxRewards; - } - - public int getShuffleDisplayDuration() { - return shuffleDisplayDuration; - } - - public boolean isCount() { - return count; - } - - public void setCount(boolean count) { - this.count = count; - } - - public int getInvRows() { - return invRows; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/DiscoverAnimationDataHolder.java b/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/DiscoverAnimationDataHolder.java deleted file mode 100644 index 257e332..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/DiscoverAnimationDataHolder.java +++ /dev/null @@ -1,62 +0,0 @@ -package me.ztowne13.customcrates.crates.types.animations.inventory; - -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -import java.util.*; - -/** - * Created by ztowne13 on 7/7/16. - */ -public class DiscoverAnimationDataHolder extends InventoryAnimationDataHolder { - private final ArrayList alreadyChosenSlots = new ArrayList<>(); - private final HashMap alreadyDisplayedRewards = new HashMap<>(); - private final ArrayList shufflingTiles = new ArrayList<>(); - private int remainingClicks; - private int currentSequence = 1; - private int sequence2Ticks; - - public DiscoverAnimationDataHolder(Player player, Location location, DiscoverAnimation crateAnimation) { - super(player, location, crateAnimation, crateAnimation.getInvRows() * 9); - - int difference = crateAnimation.getMaxRewards() - crateAnimation.getMinRewards(); - remainingClicks = (difference == 0 ? 0 : new Random().nextInt(difference + 1)) + crateAnimation.getMinRewards(); - } - - public int getRemainingClicks() { - return remainingClicks; - } - - public void setRemainingClicks(int remainingClicks) { - this.remainingClicks = remainingClicks; - } - - public int getCurrentSequence() { - return currentSequence; - } - - public void setCurrentSequence(int currentSequence) { - this.currentSequence = currentSequence; - } - - public List getAlreadyChosenSlots() { - return alreadyChosenSlots; - } - - public int getShuffleTicks() { - return sequence2Ticks; - } - - public void setShuffleTicks(int sequence2Ticks) { - this.sequence2Ticks = sequence2Ticks; - } - - public Map getAlreadyDisplayedRewards() { - return alreadyDisplayedRewards; - } - - public List getShufflingTiles() { - return shufflingTiles; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/EncloseAnimation.java b/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/EncloseAnimation.java deleted file mode 100644 index 16f4dde..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/EncloseAnimation.java +++ /dev/null @@ -1,211 +0,0 @@ -package me.ztowne13.customcrates.crates.types.animations.inventory; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.CrateState; -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import me.ztowne13.customcrates.crates.options.sounds.SoundData; -import me.ztowne13.customcrates.crates.types.animations.AnimationDataHolder; -import me.ztowne13.customcrates.crates.types.animations.CrateAnimationType; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.interfaces.logging.StatusLogger; -import me.ztowne13.customcrates.interfaces.logging.StatusLoggerEvent; - -/** - * Created by ztowne13 on 7/5/16. - */ -public class EncloseAnimation extends InventoryCrateAnimation { - private int inventoryRows; - private int updateSpeed; - private int rewardAmount; - private ItemBuilder fillerItem; - - public EncloseAnimation(Crate crate) { - super(crate, CrateAnimationType.INV_ENCLOSE); - } - - @Override - public void tickInventory(InventoryAnimationDataHolder dataHolder, boolean update) { - EncloseAnimationDataHolder eadh = (EncloseAnimationDataHolder) dataHolder; - - if (eadh.getCurrentState() == AnimationDataHolder.State.PLAYING) { - if (update) { - playSound(eadh); - updateRewards(eadh); - } - drawFillers(eadh, 1); - drawRewards(eadh); - } - } - - @Override - public void checkStateChange(AnimationDataHolder dataHolder, boolean update) { - EncloseAnimationDataHolder eadh = (EncloseAnimationDataHolder) dataHolder; - switch (eadh.getCurrentState()) { - case PLAYING: - if (eadh.getCurrentTicksIn() < 0) { - eadh.setCurrentState(AnimationDataHolder.State.ENDING); - } - break; - case ENDING: - if (dataHolder.getWaitingTicks() == 50) { - dataHolder.setCurrentState(AnimationDataHolder.State.COMPLETED); - } - break; - default: - break; - } - } - - @Override - public void drawIdentifierBlocks(InventoryAnimationDataHolder inventoryAnimationDataHolder) { - // EMPTY - } - - @Override - public ItemBuilder getFiller() { - return fillerItem; - } - - @Override - public boolean updateTicks(AnimationDataHolder dataHolder) { - EncloseAnimationDataHolder eadh = (EncloseAnimationDataHolder) dataHolder; - - switch (eadh.getCurrentState()) { - case PLAYING: - if ((eadh.getIndividualTicks() + updateSpeed - 1) % updateSpeed == 0) { - eadh.setCurrentTicksIn(eadh.getCurrentTicksIn() - 1); - eadh.setIndividualTicks(1); - return true; - } - break; - case ENDING: - dataHolder.setWaitingTicks(dataHolder.getWaitingTicks() + 1); - break; - default: - break; - } - - return false; - } - - public void updateRewards(EncloseAnimationDataHolder eadh) { - eadh.getLastDisplayRewards().clear(); - - int size = eadh.getInventoryBuilder().getSize(); - int midPoint = (size / 2) + 1; - - for (int i = 0; i < size; i++) { - if (i >= midPoint - eadh.getCurrentTicksIn() - 1 - rewardAmount && - i < midPoint + eadh.getCurrentTicksIn() + rewardAmount) { - Reward r = getCrate().getSettings().getReward().getRandomReward(); - eadh.getLastDisplayRewards().add(r); - } - } - - } - - public void drawRewards(EncloseAnimationDataHolder eadh) { - int size = eadh.getInventoryBuilder().getSize(); - int midPoint = (size / 2) + 1; - - int currentDisplayedReward = 0; - - for (int i = 0; i < size; i++) { - if (i >= midPoint - eadh.getCurrentTicksIn() - 1 - rewardAmount && - i < midPoint + eadh.getCurrentTicksIn() + rewardAmount) { - Reward r = eadh.getLastDisplayRewards().get(currentDisplayedReward); - eadh.getInventoryBuilder().setItem(i, r.getDisplayBuilder()); - currentDisplayedReward++; - } - } - } - - @Override - public void endAnimation(AnimationDataHolder dataHolder) { - EncloseAnimationDataHolder edh = (EncloseAnimationDataHolder) dataHolder; - - finishAnimation(edh.getPlayer(), edh.getLastDisplayRewards(), null); - getCrate().tick(edh.getLocation(), CrateState.OPEN, edh.getPlayer(), edh.getLastDisplayRewards()); - } - - @Override - public void loadDataValues(StatusLogger statusLogger) { - invName = fileHandler.getFileDataLoader() - .loadString(prefix + "inv-name", getStatusLogger(), StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_ENCLOSEMENT_INVNAME_SUCCESS); - - inventoryRows = fileHandler.getFileDataLoader() - .loadInt(prefix + "inventory-rows", 2, getStatusLogger(), StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_ENCLOSEMENT_INVROWS_SUCCESS, - StatusLoggerEvent.ANIMATION_ENCLOSEMENT_INVROWS_INVALID); - - if (getInventoryRows() > 2) { - setInventoryRows(2); - } - - fillerItem = fileHandler.getFileDataLoader() - .loadItem(prefix + "fill-block", new ItemBuilder(XMaterial.PURPLE_STAINED_GLASS_PANE), - getStatusLogger(), StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_ENCLOSEMENT_FILLBLOCK_INVALID - ); - fillerItem.setDisplayName("&f"); - - tickSound = fileHandler.getFileDataLoader() - .loadSound(prefix + "tick-sound", getStatusLogger(), StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_ENCLOSEMENT_TICKSOUND_SOUND_SUCCESS, - StatusLoggerEvent.ANIMATION_ENCLOSEMENT_TICKSOUND_SOUND_FAILURE, - StatusLoggerEvent.ANIMATION_ENCLOSEMENT_TICKSOUND_VOLUME_SUCCESS, - StatusLoggerEvent.ANIMATION_ENCLOSEMENT_TICKSOUND_VOLUME_INVALID, - StatusLoggerEvent.ANIMATION_ENCLOSEMENT_TICKSOUND_VOLUMEPITCH_FAILURE, - StatusLoggerEvent.ANIMATION_ENCLOSEMENT_TICKSOUND_PITCH_SUCCESS, - StatusLoggerEvent.ANIMATION_ENCLOSEMENT_TICKSOUND_PITCH_INVALID); - - updateSpeed = fileHandler.getFileDataLoader() - .loadInt(prefix + "update-speed", 2, getStatusLogger(), StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_ENCLOSEMENT_UPDATESPEED_SUCCESS, - StatusLoggerEvent.ANIMATION_ENCLOSEMENT_UPDATESPEED_INVALID); - - rewardAmount = fileHandler.getFileDataLoader().loadInt(prefix + "reward-amount", 1, getStatusLogger(), - StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, StatusLoggerEvent.ANIMATION_ENCLOSEMENT_REWARDAMOUNT_SUCCESS, - StatusLoggerEvent.ANIMATION_ENCLOSEMENT_REWARDAMOUNT_INVALID); - - if (rewardAmount % 2 == 0) { - rewardAmount++; - } - rewardAmount--; - rewardAmount = rewardAmount == 0 ? 0 : rewardAmount / 2; - } - - @Override - public String getInvName() { - return invName; - } - - @Override - public void setInvName(String invName) { - this.invName = invName; - } - - public int getInventoryRows() { - return inventoryRows; - } - - public void setInventoryRows(int inventoryRows) { - this.inventoryRows = inventoryRows; - } - - public int getRewardAmount() { - return rewardAmount; - } - - @Override - public SoundData getTickSound() { - return tickSound; - } - - @Override - public void setTickSound(SoundData tickSound) { - this.tickSound = tickSound; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/EncloseAnimationDataHolder.java b/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/EncloseAnimationDataHolder.java deleted file mode 100644 index f5d4c20..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/EncloseAnimationDataHolder.java +++ /dev/null @@ -1,39 +0,0 @@ -package me.ztowne13.customcrates.crates.types.animations.inventory; - -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -import java.util.ArrayList; -import java.util.List; - -/** - * Created by ztowne13 on 7/5/16. - */ -public class EncloseAnimationDataHolder extends InventoryAnimationDataHolder { - private int currentTicksIn; - - private List lastDisplayRewards = new ArrayList<>(); - - public EncloseAnimationDataHolder(Player player, Location location, EncloseAnimation crateAnimation) { - super(player, location, crateAnimation, ((crateAnimation.getInventoryRows()) * 9 * 2) + 9); - - currentTicksIn = (((((crateAnimation.getInventoryRows() * 2) + 1) * 9) - 1) / 2) - crateAnimation.getRewardAmount(); - } - - public int getCurrentTicksIn() { - return currentTicksIn; - } - - public void setCurrentTicksIn(int currentTicksIn) { - this.currentTicksIn = currentTicksIn; - } - - public List getLastDisplayRewards() { - return lastDisplayRewards; - } - - public void setLastDisplayRewards(List lastDisplayRewards) { - this.lastDisplayRewards = lastDisplayRewards; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/InventoryAnimationDataHolder.java b/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/InventoryAnimationDataHolder.java deleted file mode 100644 index b83848a..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/InventoryAnimationDataHolder.java +++ /dev/null @@ -1,68 +0,0 @@ -package me.ztowne13.customcrates.crates.types.animations.inventory; - -import me.ztowne13.customcrates.crates.types.animations.AnimationDataHolder; -import me.ztowne13.customcrates.crates.types.animations.CrateAnimation; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.bukkit.scheduler.BukkitRunnable; - -import java.util.ArrayList; -import java.util.List; - -public abstract class InventoryAnimationDataHolder extends AnimationDataHolder { - private final ArrayList clickedSlots; - private BukkitRunnable runnable; - private InventoryBuilder inventoryBuilder; - - public InventoryAnimationDataHolder(Player player, Location location, CrateAnimation crateAnimation, int slots) { - super(player, location, crateAnimation); - - String inventoryName = getProperInventoryName(crateAnimation); - setInventoryBuilder(new InventoryBuilder(player, slots, inventoryName)); - - clickedSlots = new ArrayList<>(); - } - - @Override - public InventoryCrateAnimation getCrateAnimation() { - return (InventoryCrateAnimation) super.getCrateAnimation(); - } - - public String getProperInventoryName(CrateAnimation crateAnimation) { - String inventoryName; - if (getCrateAnimation().getCrate().getSettings().getCrateInventoryName() == null) { - inventoryName = getCrateAnimation().getInvName(); - } else { - inventoryName = getCrateAnimation().getCrate().getSettings().getCrateInventoryName(); - } - - inventoryName = inventoryName.replace("%crate%", crateAnimation.getCrate().getDisplayName()); - - if (inventoryName.length() > 31) { - inventoryName = inventoryName.substring(0, 31); - } - - return inventoryName; - } - - public List getClickedSlots() { - return clickedSlots; - } - - public BukkitRunnable getRunnable() { - return runnable; - } - - public void setRunnable(BukkitRunnable runnable) { - this.runnable = runnable; - } - - public InventoryBuilder getInventoryBuilder() { - return inventoryBuilder; - } - - public void setInventoryBuilder(InventoryBuilder inventoryBuilder) { - this.inventoryBuilder = inventoryBuilder; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/InventoryCrateAnimation.java b/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/InventoryCrateAnimation.java deleted file mode 100644 index a2e45e3..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/InventoryCrateAnimation.java +++ /dev/null @@ -1,156 +0,0 @@ -package me.ztowne13.customcrates.crates.types.animations.inventory; - -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.options.sounds.SoundData; -import me.ztowne13.customcrates.crates.types.animations.AnimationDataHolder; -import me.ztowne13.customcrates.crates.types.animations.CrateAnimation; -import me.ztowne13.customcrates.crates.types.animations.CrateAnimationType; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import org.bukkit.Sound; -import org.bukkit.event.inventory.InventoryType; -import org.bukkit.inventory.Inventory; - -public abstract class InventoryCrateAnimation extends CrateAnimation { - private static final int REDRAW_TICKS = 1; - private static final boolean FORCE_CLOSE = false; - - protected SoundData tickSound = null; - protected String invName = ""; - - public InventoryCrateAnimation(Crate crate, CrateAnimationType crateAnimationType) { - super(crate, crateAnimationType); - } - - - /** - * This is the function responsible for drawing all neccessary things at each state - * to the inventory that aren't drawn by default. - * - * @param dataHolder The data holder that stores the player's animation runtime information. - * @param update A boolean to be able to identify whether to update certain features. - */ - public abstract void tickInventory(InventoryAnimationDataHolder dataHolder, boolean update); - - /** - * This function is responsible for drawing any static blocks that remain in the menu for - * the whole animation. - * - * @param inventoryAnimationDataHolder The data holder that stores the player's animation runtime information. - */ - public abstract void drawIdentifierBlocks(InventoryAnimationDataHolder inventoryAnimationDataHolder); - - /** - * This information returns the filler block(s) that are displayed in drawFillers() - * - * @return An instance of an ItemBuilder of the filler item. - */ - public abstract ItemBuilder getFiller(); - - - @Override - public void handleClick(AnimationDataHolder dataHolder, int slot) { - InventoryAnimationDataHolder inventoryAnimationDataHolder = (InventoryAnimationDataHolder) dataHolder; - if (!inventoryAnimationDataHolder.getClickedSlots().contains(slot)) { - inventoryAnimationDataHolder.getClickedSlots().add(slot); - } - } - - @Override - public void handleKeyPress(AnimationDataHolder dataHolder, KeyType type) { - super.handleKeyPress(dataHolder, type); - - if (type.equals(KeyType.ESC) && crate.getSettings().isCanFastTrack()) { - dataHolder.setFastTrack(true, false); - } - } - - @Override - public void tickAnimation(AnimationDataHolder dataHolder, boolean update) { - InventoryAnimationDataHolder inventoryDataHolder = (InventoryAnimationDataHolder) dataHolder; - - tickInventory(inventoryDataHolder, update); - - drawIdentifierBlocks(inventoryDataHolder); - drawInventory(inventoryDataHolder); - - tickFastTrack(inventoryDataHolder); - } - - public void drawInventory(InventoryAnimationDataHolder dataHolder) { - if (dataHolder.getTotalTicks() % REDRAW_TICKS != 0 || dataHolder.isFastTrack()) - return; - - if (FORCE_CLOSE) { - dataHolder.getPlayer().closeInventory(); - } - - InventoryBuilder builder = dataHolder.getInventoryBuilder(); - - // Open inventory if it has been closed - if (!dataHolder.getPlayer().getOpenInventory().getTopInventory().getType().equals(InventoryType.CHEST) || - dataHolder.getPlayer().getOpenInventory().getTopInventory().getSize() != builder.getInv().getSize()) { - dataHolder.getPlayer().openInventory(dataHolder.getInventoryBuilder().getInv()); - } - - // Redraw items into inventory if it is still open - Inventory topInventory = dataHolder.getPlayer().getOpenInventory().getTopInventory(); - for (int i = 0; i < builder.getInv().getSize(); i++) { - if (builder.getInv().getItem(i) == null || topInventory.getItem(i) == null || - !topInventory.getItem(i).equals(builder.getInv().getItem(i))) { - dataHolder.getPlayer().getOpenInventory().getTopInventory().setItem(i, builder.getInv().getItem(i)); - } - } - - dataHolder.getPlayer().updateInventory(); - } - - public void drawFillers(InventoryAnimationDataHolder dataHolder, int glassUpdateTicks) { - if (dataHolder.getTotalTicks() % glassUpdateTicks != 0 || dataHolder.isFastTrack()) - return; - - InventoryBuilder inv = dataHolder.getInventoryBuilder(); - - for (int i = 0; i < inv.getInv().getSize(); i++) { - inv.setItem(i, getFiller()); - } - } - - public void playSound(InventoryAnimationDataHolder dataHolder) { - if (getTickSound() != null && !dataHolder.isFastTrack()) { - Sound sound = getTickSound().getSound().parseSound(); - if (sound != null) { - dataHolder.getPlayer().playSound(dataHolder.getLocation(), sound, getTickSound().getVolume(), - getTickSound().getPitch()); - } - } - } - - public void tickFastTrack(InventoryAnimationDataHolder dataHolder) { - if (dataHolder.isFastTrack()) { - for (int i = 0; i < dataHolder.getInventoryBuilder().getSize(); i++) { - handleClick(dataHolder, i); - } - } - - if (dataHolder.isFastTrackWaitTick()) { - dataHolder.setFastTrack(true, true); - } - } - - public SoundData getTickSound() { - return tickSound; - } - - public void setTickSound(SoundData tickSound) { - this.tickSound = tickSound; - } - - public String getInvName() { - return invName; - } - - public void setInvName(String invName) { - this.invName = invName; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/MenuAnimation.java b/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/MenuAnimation.java deleted file mode 100644 index 24eeead..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/MenuAnimation.java +++ /dev/null @@ -1,156 +0,0 @@ -package me.ztowne13.customcrates.crates.types.animations.inventory; - -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.CrateState; -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import me.ztowne13.customcrates.crates.types.animations.AnimationDataHolder; -import me.ztowne13.customcrates.crates.types.animations.CrateAnimationType; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.interfaces.logging.StatusLogger; -import me.ztowne13.customcrates.interfaces.logging.StatusLoggerEvent; -import me.ztowne13.customcrates.utils.Utils; -import org.bukkit.entity.Player; - -import java.util.Random; - -public class MenuAnimation extends InventoryCrateAnimation { - private final Random random = new Random(); - private int minRewards; - private int maxRewards; - private int inventoryRows = 0; - - public MenuAnimation(Crate crate) { - super(crate, CrateAnimationType.INV_MENU); - } - - @Override - public void tickInventory(InventoryAnimationDataHolder dataHolder, boolean update) { - MenuAnimationDataHolder madh = (MenuAnimationDataHolder) dataHolder; - if (dataHolder.getCurrentState() == AnimationDataHolder.State.WAITING) { - updateAndDrawRewards(madh); - } - } - - @Override - public void drawIdentifierBlocks(InventoryAnimationDataHolder inventoryAnimationDataHolder) { - // IGNORED - } - - @Override - public ItemBuilder getFiller() { - return null; - } - - @Override - public boolean updateTicks(AnimationDataHolder dataHolder) { - if (dataHolder.getCurrentState() == AnimationDataHolder.State.ENDING) { - dataHolder.setWaitingTicks(dataHolder.getWaitingTicks() + 1); - } - return false; - } - - @Override - public void checkStateChange(AnimationDataHolder dataHolder, boolean update) { - switch (dataHolder.getCurrentState()) { - case PLAYING: - dataHolder.setCurrentState(AnimationDataHolder.State.WAITING); - break; - case WAITING: - dataHolder.setCurrentState(AnimationDataHolder.State.ENDING); - break; - case ENDING: - if (dataHolder.getWaitingTicks() == 100) { - dataHolder.setCurrentState(AnimationDataHolder.State.COMPLETED); - } - break; - default: - break; - } - } - - public void updateAndDrawRewards(MenuAnimationDataHolder mdh) { - int randomNumber = 0; - if (getMaxRewards() > getMinRewards()) { - randomNumber = this.random.nextInt(getMaxRewards() - getMinRewards()); - } - - int amountOfRewards = randomNumber + getMinRewards(); - - for (int i = 0; i < amountOfRewards; i++) { - int slot = Utils.getRandomNumberExcluding((getInventoryRows() * 9) - 1, mdh.getUsedNumbers()); - mdh.getUsedNumbers().add(slot); - - Reward reward = getCrate().getSettings().getReward().getRandomReward(); - mdh.getDisplayedRewards().add(reward); - - mdh.getInventoryBuilder().setItem(slot, reward.getDisplayBuilder()); - } - } - - @Override - public void endAnimation(AnimationDataHolder dataHolder) { - MenuAnimationDataHolder mdh = (MenuAnimationDataHolder) dataHolder; - Player player = mdh.getPlayer(); - - finishAnimation(player, mdh.getDisplayedRewards(), null); - getCrate().tick(mdh.getLocation(), CrateState.OPEN, player, mdh.getDisplayedRewards()); - } - - @Override - public void loadDataValues(StatusLogger statusLogger) { - invName = fileHandler.getFileDataLoader() - .loadString(prefix + "inv-name", getStatusLogger(), StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_MENU_INVNAME_SUCCESS); - - minRewards = fileHandler.getFileDataLoader() - .loadInt(prefix + "minimum-rewards", 1, getStatusLogger(), StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_MENU_MINIMUM_REWARDS_SUCCESS, - StatusLoggerEvent.ANIMATION_MENU_MINIMUM_REWARDS_INVALID); - - maxRewards = fileHandler.getFileDataLoader() - .loadInt(prefix + "maximum-rewards", 4, getStatusLogger(), StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_MENU_MAXIMUM_REWARDS_SUCCESS, - StatusLoggerEvent.ANIMATION_MENU_MAXIMUM_REWARDS_INVALID); - - inventoryRows = fileHandler.getFileDataLoader() - .loadInt(prefix + "inventory-rows", 3, getStatusLogger(), StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_MENU_INVENTORY_ROWS_SUCCESS, - StatusLoggerEvent.ANIMATION_MENU_INVENTORY_ROWS_INVALID); - } - - @Override - public String getInvName() { - return invName; - } - - @Override - public void setInvName(String invName) { - this.invName = invName; - } - - public int getMinRewards() { - return minRewards; - } - - public void setMinRewards(int minRewards) { - this.minRewards = minRewards; - } - - public int getMaxRewards() { - return maxRewards; - } - - public void setMaxRewards(int maxRewards) { - this.maxRewards = maxRewards; - } - - public int getInventoryRows() { - return inventoryRows; - } - - public void setInventoryRows(int inventoryRows) { - this.inventoryRows = inventoryRows; - } - - -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/MenuAnimationDataHolder.java b/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/MenuAnimationDataHolder.java deleted file mode 100644 index 9d9d975..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/MenuAnimationDataHolder.java +++ /dev/null @@ -1,33 +0,0 @@ -package me.ztowne13.customcrates.crates.types.animations.inventory; - - -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -import java.util.ArrayList; -import java.util.List; - -/** - * Created by ztowne13 on 3/6/16. - */ -public class MenuAnimationDataHolder extends InventoryAnimationDataHolder { - private final List displayedRewards; - private final List usedNumbers; - - public MenuAnimationDataHolder(Player player, Location location, MenuAnimation crateAnimation) { - super(player, location, crateAnimation, crateAnimation.getInventoryRows() * 9); - - displayedRewards = new ArrayList<>(); - usedNumbers = new ArrayList<>(); - } - - public List getDisplayedRewards() { - return displayedRewards; - } - - public List getUsedNumbers() { - return usedNumbers; - } - -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/RouletteAnimation.java b/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/RouletteAnimation.java deleted file mode 100644 index 233fd07..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/RouletteAnimation.java +++ /dev/null @@ -1,200 +0,0 @@ -package me.ztowne13.customcrates.crates.types.animations.inventory; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.CrateState; -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import me.ztowne13.customcrates.crates.types.animations.AnimationDataHolder; -import me.ztowne13.customcrates.crates.types.animations.CrateAnimationType; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.interfaces.logging.StatusLogger; -import me.ztowne13.customcrates.interfaces.logging.StatusLoggerEvent; -import org.bukkit.entity.Player; - -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.Random; - -/** - * Created by ztowne13 on 6/30/16. - */ -public class RouletteAnimation extends InventoryCrateAnimation { - private final Random random = new Random(); - private double finalTickLength; - private double tickIncrease; - private int glassUpdateTicks = 2; - private List items; - - public RouletteAnimation(Crate crate) { - super(crate, CrateAnimationType.INV_ROULETTE); - } - - @Override - public void tickInventory(InventoryAnimationDataHolder dataHolder, boolean update) { - RouletteAnimationDataHolder rdh = (RouletteAnimationDataHolder) dataHolder; - - if (rdh.getCurrentState() == AnimationDataHolder.State.PLAYING) { - drawFillers(rdh, glassUpdateTicks); - - if (update) { - playSound(rdh); - updateReward(rdh); - } - - drawRewards(rdh); - } - } - - @Override - public boolean updateTicks(AnimationDataHolder dataHolder) { - RouletteAnimationDataHolder rdh = (RouletteAnimationDataHolder) dataHolder; - - switch (rdh.getCurrentState()) { - case PLAYING: - if (rdh.getIndividualTicks() * BASE_SPEED >= rdh.getCurrentTicks() - 1.1) { - rdh.setUpdates(rdh.getUpdates() + 1); - rdh.setIndividualTicks(0); - - rdh.setCurrentTicks(.05 * Math.pow((getTickIncrease() / 40) + 1, rdh.getUpdates())); - return true; - } - break; - case ENDING: - rdh.setWaitingTicks(rdh.getWaitingTicks() + 1); - break; - default: - break; - } - - return false; - } - - @Override - public void checkStateChange(AnimationDataHolder dataHolder, boolean update) { - RouletteAnimationDataHolder rdh = (RouletteAnimationDataHolder) dataHolder; - AnimationDataHolder.State state = rdh.getCurrentState(); - - if (state == AnimationDataHolder.State.PLAYING && rdh.getCurrentTicks() > getFinalTickLength()) { - rdh.setCurrentState(AnimationDataHolder.State.ENDING); - } - - if (state == AnimationDataHolder.State.ENDING && rdh.getWaitingTicks() == 50) { - rdh.setCurrentState(AnimationDataHolder.State.COMPLETED); - } - } - - public void updateReward(RouletteAnimationDataHolder rdh) { - Reward r = getCrate().getSettings().getReward().getRandomReward(); - rdh.setLastShownReward(r); - } - - public void drawRewards(RouletteAnimationDataHolder rdh) { - InventoryBuilder inv = rdh.getInventoryBuilder(); - - inv.setItem(13, rdh.getLastShownReward().getDisplayBuilder()); - } - - @Override - public void drawIdentifierBlocks(InventoryAnimationDataHolder inventoryAnimationDataHolder) { - // EMPTY - } - - @Override - public ItemBuilder getFiller() { - return getItems().get(random.nextInt(getItems().size())); - } - - @Override - public void endAnimation(AnimationDataHolder dataHolder) { - RouletteAnimationDataHolder rdh = (RouletteAnimationDataHolder) dataHolder; - Player player = rdh.getPlayer(); - - ArrayList rewards = new ArrayList<>(); - rewards.add(rdh.getLastShownReward()); - - finishAnimation(player, rewards, null); - getCrate().tick(rdh.getLocation(), CrateState.OPEN, player, rewards); - } - - @Override - public void loadDataValues(StatusLogger statusLogger) { - invName = fileHandler.getFileDataLoader() - .loadString(prefix + "inv-name", getStatusLogger(), StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_ROULETTE_INVNAME_SUCCESS); - - tickSound = fileHandler.getFileDataLoader() - .loadSound(prefix + "tick-sound", getStatusLogger(), StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_ROULETTE_TICKSOUND_SOUND_SUCCESS, - StatusLoggerEvent.ANIMATION_ROULETTE_TICKSOUND_SOUND_FAILURE, - StatusLoggerEvent.ANIMATION_ROULETTE_TICKSOUND_VOLUME_SUCCESS, - StatusLoggerEvent.ANIMATION_ROULETTE_TICKSOUND_VOLUME_INVALID, - StatusLoggerEvent.ANIMATION_ROULETTE_TICKSOUND_VOLUMEPITCH_FAILURE, - StatusLoggerEvent.ANIMATION_ROULETTE_TICKSOUND_PITCH_SUCCESS, - StatusLoggerEvent.ANIMATION_ROULETTE_TICKSOUND_PITCH_INVALID); - - finalTickLength = fileHandler.getFileDataLoader().loadDouble(prefix + "final-crate-tick-length", 7, getStatusLogger(), - StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, StatusLoggerEvent.ANIMATION_ROULETTE_FINALTICKLENGTH_SUCCESS, - StatusLoggerEvent.ANIMATION_ROULETTE_FINALTICKLENGTH_INVALID); - - glassUpdateTicks = fileHandler.getFileDataLoader() - .loadInt(prefix + "tile-update-ticks", 2, getStatusLogger(), StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_ROULETTE_GLASSUPDATE_SUCCESS, - StatusLoggerEvent.ANIMATION_ROULETTE_GLASSUPDATE_INVALID); - - tickIncrease = fileHandler.getFileDataLoader() - .loadDouble(prefix + "tick-speed-per-run", 0.4, getStatusLogger(), - StatusLoggerEvent.ANIMATION_VALUE_NONEXISTENT, - StatusLoggerEvent.ANIMATION_ROULETTE_TICKSPEED_SUCCESS, - StatusLoggerEvent.ANIMATION_ROULETTE_TICKSPEED_INVALID); - - - setItems(new ArrayList<>()); - - try { - for (String s : fileHandler.get().getStringList("CrateType.Inventory.Roulette.random-blocks")) { - try { - Optional optional = XMaterial.matchXMaterial(s); - if (!optional.isPresent()) { - StatusLoggerEvent.ANIMATION_ROULETTE_RANDOMBLOCK_MATERIAL_NONEXISTENT - .log(getStatusLogger(), s); - continue; - } - - getItems().add(new ItemBuilder(optional.get(), 1).setDisplayName("&f")); - StatusLoggerEvent.ANIMATION_ROULETTE_RANDOMBLOCK_MATERIAL_SUCCESS - .log(getStatusLogger(), s); - } catch (Exception exc) { - StatusLoggerEvent.ANIMATION_ROULETTE_RANDOMBLOCK_ITEM_INVALID.log(getStatusLogger(), s); - } - } - } catch (Exception exc) { - StatusLoggerEvent.ANIMATION_ROULETTE_RANDOMBLOCK_NONEXISTENT.log(getStatusLogger()); - } - } - - public List getItems() { - return items; - } - - public void setItems(List items) { - this.items = items; - } - - public double getFinalTickLength() { - return finalTickLength; - } - - public void setFinalTickLength(double finalTickLength) { - this.finalTickLength = finalTickLength; - } - - public double getTickIncrease() { - return tickIncrease; - } - - public void setTickIncrease(double tickIncrease) { - this.tickIncrease = tickIncrease; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/RouletteAnimationDataHolder.java b/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/RouletteAnimationDataHolder.java deleted file mode 100644 index 6b238ac..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/types/animations/inventory/RouletteAnimationDataHolder.java +++ /dev/null @@ -1,50 +0,0 @@ -package me.ztowne13.customcrates.crates.types.animations.inventory; - -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -/** - * Created by ztowne13 on 3/6/16. - */ -public class RouletteAnimationDataHolder extends InventoryAnimationDataHolder { - private final double displayAmount; - private double currentTicks = 1.1; - private double updates = 0; - - private Reward lastShownReward; - - public RouletteAnimationDataHolder(Player player, Location location, RouletteAnimation crateAnimation) { - super(player, location, crateAnimation, 27); - - displayAmount = crateAnimation.getRandomTickTime(crateAnimation.getFinalTickLength()); - } - - public double getDisplayAmount() { - return displayAmount; - } - - public double getCurrentTicks() { - return currentTicks; - } - - public void setCurrentTicks(double currentTicks) { - this.currentTicks = currentTicks; - } - - public Reward getLastShownReward() { - return lastShownReward; - } - - public void setLastShownReward(Reward lastShownReward) { - this.lastShownReward = lastShownReward; - } - - public double getUpdates() { - return updates; - } - - public void setUpdates(double updates) { - this.updates = updates; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/types/animations/minimal/GiveKeyAnimation.java b/src/main/java/me/ztowne13/customcrates/crates/types/animations/minimal/GiveKeyAnimation.java deleted file mode 100644 index 08b8311..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/types/animations/minimal/GiveKeyAnimation.java +++ /dev/null @@ -1,54 +0,0 @@ -package me.ztowne13.customcrates.crates.types.animations.minimal; - -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.CrateState; -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import me.ztowne13.customcrates.crates.types.animations.AnimationDataHolder; -import me.ztowne13.customcrates.crates.types.animations.CrateAnimation; -import me.ztowne13.customcrates.crates.types.animations.CrateAnimationType; -import me.ztowne13.customcrates.interfaces.logging.StatusLogger; -import org.bukkit.entity.Player; - -import java.util.ArrayList; - -public class GiveKeyAnimation extends CrateAnimation { - - public GiveKeyAnimation(Crate crate) { - super(crate, CrateAnimationType.GIVE_KEY); - } - - @Override - public void tickAnimation(AnimationDataHolder dataHolder, boolean update) { - // EMPTY - } - - @Override - public void endAnimation(AnimationDataHolder dataHolder) { - Player player = dataHolder.getPlayer(); - - Reward r = getCrate().getSettings().getReward().getRandomReward(); - ArrayList rewards = new ArrayList<>(); - rewards.add(r); - - finishAnimation(player, rewards, null); - getCrate().tick(dataHolder.getLocation(), CrateState.OPEN, player, rewards); - } - - @Override - public boolean updateTicks(AnimationDataHolder dataHolder) { - return false; - } - - @Override - public void checkStateChange(AnimationDataHolder dataHolder, boolean update) { - if (dataHolder.getCurrentState() == AnimationDataHolder.State.PLAYING) { - dataHolder.setCurrentState(AnimationDataHolder.State.COMPLETED); - } - } - - @Override - public void loadDataValues(StatusLogger statusLogger) { - // EMPTY - } - -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/types/animations/minimal/GiveKeyAnimationDataHolder.java b/src/main/java/me/ztowne13/customcrates/crates/types/animations/minimal/GiveKeyAnimationDataHolder.java deleted file mode 100644 index 2ca12fc..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/types/animations/minimal/GiveKeyAnimationDataHolder.java +++ /dev/null @@ -1,12 +0,0 @@ -package me.ztowne13.customcrates.crates.types.animations.minimal; - -import me.ztowne13.customcrates.crates.types.animations.AnimationDataHolder; -import org.bukkit.Location; -import org.bukkit.entity.Player; - -public class GiveKeyAnimationDataHolder extends AnimationDataHolder { - - public GiveKeyAnimationDataHolder(Player player, Location location, GiveKeyAnimation crateAnimation) { - super(player, location, crateAnimation); - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/types/display/CrateDisplayType.java b/src/main/java/me/ztowne13/customcrates/crates/types/display/CrateDisplayType.java deleted file mode 100644 index e306404..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/types/display/CrateDisplayType.java +++ /dev/null @@ -1,12 +0,0 @@ -package me.ztowne13.customcrates.crates.types.display; - -/** - * Created by ztowne13 on 2/24/16. - */ -public enum CrateDisplayType { - BLOCK, - - MOB, - - NPC -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/types/display/DynamicCratePlaceholder.java b/src/main/java/me/ztowne13/customcrates/crates/types/display/DynamicCratePlaceholder.java deleted file mode 100644 index ec1d476..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/types/display/DynamicCratePlaceholder.java +++ /dev/null @@ -1,27 +0,0 @@ -package me.ztowne13.customcrates.crates.types.display; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.PlacedCrate; - -/** - * Created by ztowne13 on 2/24/16. - */ -public abstract class DynamicCratePlaceholder { - protected final SpecializedCrates instance; - - public DynamicCratePlaceholder(SpecializedCrates instance) { - this.instance = instance; - } - - public abstract void place(PlacedCrate placedCrate); - - public abstract void remove(PlacedCrate placedCrate); - - public abstract String getType(); - - public abstract void setType(Object obj); - - public abstract void fixHologram(PlacedCrate placedCrate); - - public abstract String toString(); -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/types/display/EntityType.java b/src/main/java/me/ztowne13/customcrates/crates/types/display/EntityType.java deleted file mode 100644 index 5dfdc6e..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/types/display/EntityType.java +++ /dev/null @@ -1,184 +0,0 @@ -package me.ztowne13.customcrates.crates.types.display; - -import me.ztowne13.customcrates.utils.VersionUtils.Version; - -import java.util.ArrayList; -import java.util.List; - -/** - * Created by ztowne13 on 2/27/16. - */ -public enum EntityType { - // v1.8 - PLAYER(2, Version.v1_8), - SPIDER(1, Version.v1_8), - GIANT(2, Version.v1_8), - GHAST(3, Version.v1_8), - BLAZE(2, Version.v1_8), - ENDER_DRAGON(5, Version.v1_8), - GUARDIAN(2, Version.v1_8), - SQUID(1, Version.v1_8), - BAT(.5, Version.v1_8), - CAVE_SPIDER(.5, Version.v1_8), - CHICKEN(1, Version.v1_8), - COW(1, Version.v1_8), - CREEPER(2, Version.v1_8), - ENDERMAN(2.9, Version.v1_8), - ENDERMITE(.5, Version.v1_8), - HORSE(1.2, Version.v1_8), - IRON_GOLEM(2.7, Version.v1_8), - MAGMA_CUBE(1.7, Version.v1_8), - MUSHROOM_COW(1.4, Version.v1_8), - OCELOT(.5, Version.v1_8), - PIG(.8, Version.v1_8), - PIG_ZOMBIE(2, Version.v1_8), - RABBIT(.5, Version.v1_8), - SHEEP(1.2, Version.v1_8), - SILVERFISH(.5, Version.v1_8), - SKELETON(2, Version.v1_8), - SLIME(1.7, Version.v1_8), - SNOWMAN(2, Version.v1_8), - VILLAGER(2, Version.v1_8), - WITCH(2, Version.v1_8), - WITHER(3.5, Version.v1_8), - WOLF(.8, Version.v1_8), - ZOMBIE(2, Version.v1_8), - - // v1.9 - SHULKER(2, Version.v1_9), - - // v1.10 - POLAR_BEAR(2, Version.v1_10), - - // v1.11 - ELDER_GUARDIAN(2, Version.v1_11), - WITHER_SKELETON(2, Version.v1_11), - STRAY(2, Version.v1_11), - HUSK(2, Version.v1_11), - ZOMBIE_VILLAGER(2, Version.v1_11), - SKELETON_HORSE(2, Version.v1_11), - ZOMBIE_HORSE(2, Version.v1_11), - DONKEY(2, Version.v1_11), - MULE(2, Version.v1_11), - EVOKER(2, Version.v1_11), - VEX(2, Version.v1_11), - VINDICATOR(2, Version.v1_11), - LLAMA(2, Version.v1_11), - - // v1.12 - ILLUSIONER(2, Version.v1_12), - PARROT(2, Version.v1_12), - - // v1.13 - TURTLE(2, Version.v1_13), - PHANTOM(2, Version.v1_13), - TRIDENT(2, Version.v1_13), - COD(2, Version.v1_13), - SALMON(2, Version.v1_13), - PUFFERFISH(2, Version.v1_13), - TROPICAL_FISH(2, Version.v1_13), - DROWNED(2, Version.v1_13), - DOLPHIN(2, Version.v1_13), - - // v1.14 - CAT(2, Version.v1_14), - PANDA(2, Version.v1_14), - PILLAGER(2, Version.v1_14), - RAVAGER(2, Version.v1_14), - TRADER_LLAMA(2, Version.v1_14), - WANDERING_TRADER(2, Version.v1_14), - FOX(2, Version.v1_14), - - // v1.15 - BEE(2, Version.v1_15), - - // v1.16 - ZOMBIFIED_PIGLIN(2, Version.v1_16), - HOGLIN(2, Version.v1_16), - PIGLIN(2, Version.v1_16), - STRIDER(2, Version.v1_16), - ZOGLIN(2, Version.v1_16); - - - // Not allowed -// EVOKER_FANGS(2, VersionUtils.Version.v1_11), -// LLAMA_SPIT(2, VersionUtils.Version.v1_11), -// DROPPED_ITEM(2, VersionUtils.Version.v1_9), -// EXPERIENCE_ORB(2, VersionUtils.Version.v1_9), -// LEASH_HITCH(2, VersionUtils.Version.v1_9), -// PAINTING(2, VersionUtils.Version.v1_9), -// ARROW(2, VersionUtils.Version.v1_9), -// SNOWBALL(2, VersionUtils.Version.v1_9), -// FIREBALL(2, VersionUtils.Version.v1_9), -// SMALL_FIREBALL(2, VersionUtils.Version.v1_9), -// ENDER_PEARL(2, VersionUtils.Version.v1_9), -// ENDER_SIGNAL(2, VersionUtils.Version.v1_9), -// THROWN_EXP_BOTTLE(2, VersionUtils.Version.v1_9), -// ITEM_FRAME(2, VersionUtils.Version.v1_9), -// WITHER_SKULL(2, VersionUtils.Version.v1_9), -// PRIMED_TNT(2, VersionUtils.Version.v1_9), -// FALLING_BLOCK(2, VersionUtils.Version.v1_9), -// FIREWORK(2, VersionUtils.Version.v1_9), -// ARMOR_STAND(2, VersionUtils.Version.v1_9), -// MINECART_COMMAND(2, VersionUtils.Version.v1_9), -// BOAT(2, VersionUtils.Version.v1_9), -// MINECART(2, VersionUtils.Version.v1_9), -// MINECART_CHEST(2, VersionUtils.Version.v1_9), -// MINECART_FURNACE(2, VersionUtils.Version.v1_9), -// MINECART_TNT(2, VersionUtils.Version.v1_9), -// MINECART_HOPPER(2, VersionUtils.Version.v1_9), -// MINECART_MOB_SPAWNER(2, VersionUtils.Version.v1_9), -// ENDER_CRYSTAL(2, VersionUtils.Version.v1_9), -// SPLASH_POTION(2, VersionUtils.Version.v1_9), -// EGG(2, VersionUtils.Version.v1_9), -// FISHING_HOOK(2, VersionUtils.Version.v1_9), -// LIGHTNING(2, VersionUtils.Version.v1_9), -// WEATHER(2, VersionUtils.Version.v1_9), -// COMPLEX_PART(2, VersionUtils.Version.v1_9), -// UNKNOWN(2, VersionUtils.Version.v1_9), -// TIPPED_ARROW(2, VersionUtils.Version.v1_9), -// SPECTRAL_ARROW(2, VersionUtils.Version.v1_9), -// SHULKER_BULLET(2, VersionUtils.Version.v1_9), -// DRAGON_FIREBALL(2, VersionUtils.Version.v1_9), -// LINGERING_POTION(2, VersionUtils.Version.v1_9), -// AREA_EFFECT_CLOUD(2, VersionUtils.Version.v1_9); - - private final double height; - private final Version minimumVersion; - - EntityType(double height, Version minimumVersion) { - this.height = height; - this.minimumVersion = minimumVersion; - } - - public static EntityType getEnum(String name) { - try { - EntityType ent = valueOf(name.toUpperCase()); - if (!ent.minimumVersion.isServerVersionOrLater()) { - throw new IllegalArgumentException(name + " is not available in this version"); - } - return ent; - } catch (Exception exc) { - throw new IllegalArgumentException(name + " is a nonexistent entity type"); - } - } - - public static List enumValues() { - ArrayList entityTypeList = new ArrayList<>(); - for (EntityType type : values()) { - if (type.minimumVersion.isServerVersionOrLater()) { - entityTypeList.add(type); - } - } - - return entityTypeList; - } - - public org.bukkit.entity.EntityType getBukkitEntityType() { - return org.bukkit.entity.EntityType.valueOf(name()); - } - - public double getHeight() { - return height; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/types/display/MaterialPlaceholder.java b/src/main/java/me/ztowne13/customcrates/crates/types/display/MaterialPlaceholder.java deleted file mode 100644 index 0d7cc87..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/types/display/MaterialPlaceholder.java +++ /dev/null @@ -1,55 +0,0 @@ -package me.ztowne13.customcrates.crates.types.display; - -import me.ztowne13.customcrates.SettingsValue; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.PlacedCrate; -import me.ztowne13.customcrates.interfaces.logging.StatusLoggerEvent; -import org.bukkit.Material; - -/** - * Created by ztowne13 on 2/24/16. - */ -public class MaterialPlaceholder extends DynamicCratePlaceholder { - public MaterialPlaceholder(SpecializedCrates cc) { - super(cc); - } - - public void place(PlacedCrate placedCrate) { - Material m = placedCrate.getCrate().getSettings().getCrateItemHandler().getItem(1).getType(); - if (placedCrate.getCrate().isEnabled() - && !placedCrate.getCrate().getSettings().getCrateItemHandler().crateMatchesBlock(placedCrate.getLocation().getBlock().getType())) { - try { - if (SettingsValue.KEEP_CRATE_BLOCK_CONSISTENT.getValue(instance).equals(Boolean.TRUE) || - placedCrate.getLocation().getBlock().getType().equals(Material.AIR)) { - placedCrate.getLocation().getBlock().setType(m); - } - } catch (Exception exc) { - StatusLoggerEvent.SETTINGS_CRATE_FAILURE_DISABLE.log(placedCrate.getCrate().getSettings().getStatusLogger(), - m.toString() + " is not a block and therefore cannot be used as a crate type!"); - placedCrate.getCrate().setDisabledByError(false); - placedCrate.setCratesEnabled(false); - } - } - } - - public void remove(PlacedCrate placedCrate) { - placedCrate.getLocation().getBlock().setType(Material.AIR); - } - - public String getType() { - return ""; - } - - public void setType(Object obj) { - // EMPTY - } - - public void fixHologram(PlacedCrate placedCrate) { - // EMPTY - } - - public String toString() { - return "Block"; - } - -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/types/display/npcs/Citizens2NPCPlaceHolder.java b/src/main/java/me/ztowne13/customcrates/crates/types/display/npcs/Citizens2NPCPlaceHolder.java deleted file mode 100644 index 367dfc6..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/types/display/npcs/Citizens2NPCPlaceHolder.java +++ /dev/null @@ -1,112 +0,0 @@ -package me.ztowne13.customcrates.crates.types.display.npcs; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.PlacedCrate; -import me.ztowne13.customcrates.crates.types.display.DynamicCratePlaceholder; -import me.ztowne13.customcrates.crates.types.display.EntityType; -import me.ztowne13.customcrates.utils.LocationUtils; -import me.ztowne13.customcrates.utils.NPCUtils; -import net.citizensnpcs.api.CitizensAPI; -import net.citizensnpcs.api.npc.NPC; -import net.citizensnpcs.api.npc.NPCRegistry; -import net.citizensnpcs.npc.skin.SkinnableEntity; -import org.bukkit.Bukkit; -import org.bukkit.Location; - -import java.util.HashMap; -import java.util.Map; - -/** - * Created by ztowne13 on 2/25/16. - */ -public class Citizens2NPCPlaceHolder extends DynamicCratePlaceholder { - private static Map npcMap = new HashMap<>(); - - private String name; - - public Citizens2NPCPlaceHolder(SpecializedCrates instance) { - super(instance); - } - - public static Map getNpcMap() { - return npcMap; - } - - public static void setNpcMap(Map npcMap) { - Citizens2NPCPlaceHolder.npcMap = npcMap; - } - - public void place(final PlacedCrate placedCrate) { - Bukkit.getScheduler().scheduleSyncDelayedTask(instance, () -> { - LocationUtils.removeDubBlocks(placedCrate.getLocation()); - - NPCRegistry npcRegistry = CitizensAPI.getNPCRegistry(); - NPC npc; - - if (NPCUtils.npcExists(placedCrate)) { - npc = NPCUtils.getNpcForCrate(placedCrate); - if (npc.getEntity().getType().equals(org.bukkit.entity.EntityType.PLAYER)) { - getNpcMap().put(placedCrate, npc); - return; - } else { - npc.destroy(); - } - } - - npc = npcRegistry.createNPC(org.bukkit.entity.EntityType.PLAYER, "Specialized Crate - Crate"); - //npc.addTrait(new IdentifierTrait()); - - npc.data().setPersistent(NPC.PLAYER_SKIN_UUID_METADATA, name); - //npc.data().setPersistent(NPC.PLAYER_SKIN_USE_LATEST, false); - - npc.spawn(LocationUtils.getLocationCentered(placedCrate.getLocation())); - - NPCUtils.applyDefaultInfo(npc); - - //applySkin(npc, getName()); - - getNpcMap().put(placedCrate, npc); - }, 20); - - } - - public void remove(PlacedCrate placedCrate) { - getNpcMap().get(placedCrate).destroy(); - } - - public String getType() { - return getName(); - } - - public void setType(Object obj) { - setName(obj.toString()); - } - - public void fixHologram(PlacedCrate placedCrate) { - Location l = placedCrate.getLocation().clone(); - l.setY(l.getY() + EntityType.PLAYER.getHeight() - .8); - placedCrate.getHologram().getDynamicHologram().teleport(l); - } - - public void applySkin(NPC npc, String name) { - if (npc.isSpawned()) { - - SkinnableEntity skinnable = (SkinnableEntity) npc.getEntity(); - if (skinnable != null) { - skinnable.setSkinName(name); - } - } - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String toString() { - return "NPC"; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/types/display/npcs/IdentifierTrait.java b/src/main/java/me/ztowne13/customcrates/crates/types/display/npcs/IdentifierTrait.java deleted file mode 100644 index 9ecdd4e..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/types/display/npcs/IdentifierTrait.java +++ /dev/null @@ -1,19 +0,0 @@ -package me.ztowne13.customcrates.crates.types.display.npcs; - -import net.citizensnpcs.api.persistence.Persist; -import net.citizensnpcs.api.trait.Trait; - -public class IdentifierTrait extends Trait { - @Persist(value = "isCrate") - boolean isCrate; - - public IdentifierTrait() { - super("IdentifierTrait"); - isCrate = true; - } - // the default value of @Persist saves the value under the field name (in this case, 'myVariable'). - - public boolean isCrate() { - return isCrate; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/crates/types/display/npcs/MobPlaceholder.java b/src/main/java/me/ztowne13/customcrates/crates/types/display/npcs/MobPlaceholder.java deleted file mode 100644 index 08d7ab3..0000000 --- a/src/main/java/me/ztowne13/customcrates/crates/types/display/npcs/MobPlaceholder.java +++ /dev/null @@ -1,103 +0,0 @@ -package me.ztowne13.customcrates.crates.types.display.npcs; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.PlacedCrate; -import me.ztowne13.customcrates.crates.types.display.DynamicCratePlaceholder; -import me.ztowne13.customcrates.crates.types.display.EntityType; -import me.ztowne13.customcrates.utils.LocationUtils; -import me.ztowne13.customcrates.utils.NPCUtils; -import net.citizensnpcs.api.CitizensAPI; -import net.citizensnpcs.api.npc.NPC; -import net.citizensnpcs.api.npc.NPCRegistry; -import org.bukkit.Bukkit; -import org.bukkit.Location; - -import java.util.HashMap; -import java.util.Map; - -/** - * Created by ztowne13 on 2/24/16. - */ -public class MobPlaceholder extends DynamicCratePlaceholder { - private static Map npcMap = new HashMap<>(); - - private EntityType entityType; - - public MobPlaceholder(SpecializedCrates instance) { - super(instance); - } - - public static Map getNpcMap() { - return npcMap; - } - - public static void setNpcMap(Map npcMap) { - MobPlaceholder.npcMap = npcMap; - } - - public void place(final PlacedCrate placedCrate) { - Bukkit.getScheduler().runTaskLater(instance, () -> { - LocationUtils.removeDubBlocks(placedCrate.getLocation()); - - NPCRegistry npcRegistry = CitizensAPI.getNPCRegistry(); - NPC npc; - - if (NPCUtils.npcExists(placedCrate)) { - npc = NPCUtils.getNpcForCrate(placedCrate); - - if (npc.getEntity().getType().equals(getEntityType().getBukkitEntityType())) { - getNpcMap().put(placedCrate, npc); - return; - } else { - npc.destroy(); - } - } - - npc = npcRegistry.createNPC(entityType.getBukkitEntityType(), "Specialized Crate - Crate"); - - //npc.addTrait(new IdentifierTrait()); - - NPCUtils.applyDefaultInfo(npc); - - npc.spawn(LocationUtils.getLocationCentered(placedCrate.getLocation()).add(0, -1, 0)); - - getNpcMap().put(placedCrate, npc); - }, 20); - - } - - public void remove(PlacedCrate placedCrate) { - getNpcMap().get(placedCrate).destroy(); - } - - public boolean existsAt(Location location) { - return true; - } - - public String getType() { - return entityType == null ? "null" : entityType.name(); - } - - public void setType(Object obj) { - setEntityType(EntityType.getEnum(obj.toString())); - } - - public void fixHologram(PlacedCrate placedCrate) { - Location l = placedCrate.getLocation().clone(); - l.setY(l.getY() + getEntityType().getHeight() - .5); - placedCrate.getHologram().getDynamicHologram().teleport(l); - - } - - public EntityType getEntityType() { - return entityType; - } - - public void setEntityType(EntityType entityType) { - this.entityType = entityType; - } - - public String toString() { - return "Mob"; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/InventoryBuilder.java b/src/main/java/me/ztowne13/customcrates/interfaces/InventoryBuilder.java deleted file mode 100644 index 6857cfc..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/InventoryBuilder.java +++ /dev/null @@ -1,77 +0,0 @@ -package me.ztowne13.customcrates.interfaces; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.VersionUtils; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; - -import static java.lang.Math.max; -import static java.lang.Math.min; - -public class InventoryBuilder { - protected final int minimumSlots; - private final String invName; - private Inventory inv; - private Player player; - - public InventoryBuilder(Player player, int slots, String invName) { - this(player, slots, invName, 0); - } - - public InventoryBuilder(Player player, int slots, String invName, int minimumSlots) { - this.invName = invName; - this.minimumSlots = minimumSlots; - this.player = player; - - String title = ChatColor.translateAlternateColorCodes('&', invName); - if (VersionUtils.Version.v1_12.isServerVersionOrEarlier() && title.length() > 31) { - title = title.substring(0, 32); - } - setInv(Bukkit.createInventory(player, min(54, max(minimumSlots, slots)), title)); - } - - public void clear() { - for (int i = 0; i < inv.getSize(); i++) - setItem(i, new ItemBuilder(XMaterial.AIR, 1)); - } - - public int getSize() { - return getInv().getSize(); - } - - public String getName() { - return invName; - } - - public void setItem(int slot, ItemStack stack) { - getInv().setItem(slot, stack); - } - - public void setItem(int slot, ItemBuilder builder) { - getInv().setItem(slot, builder.getStack()); - } - - public void open() { - getPlayer().openInventory(getInv()); - } - - public Inventory getInv() { - return inv; - } - - public void setInv(Inventory inv) { - this.inv = inv; - } - - public Player getPlayer() { - return player; - } - - public void setPlayer(Player player) { - this.player = player; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/InventoryUtils.java b/src/main/java/me/ztowne13/customcrates/interfaces/InventoryUtils.java deleted file mode 100644 index b672cc7..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/InventoryUtils.java +++ /dev/null @@ -1,28 +0,0 @@ -package me.ztowne13.customcrates.interfaces; - -/** - * Created by ztowne13 on 3/11/16. - */ -public class InventoryUtils { - private InventoryUtils() { - // EMPTY - } - - public static int getRowsFor(int alreadyUserPerSlot, int needSlotSpaces) { - return getRowsFor(alreadyUserPerSlot, needSlotSpaces, 1); - } - - public static int getRowsFor(int alreadyUsedPerSlot, int needSlotSpaces, int page) { - int itemsPerRow = 9 - alreadyUsedPerSlot; - - int fullInv = itemsPerRow * 6; - int toSkip = (fullInv * (page - 1)); - needSlotSpaces -= toSkip; - - int extraRow = (needSlotSpaces % itemsPerRow == 0 ? 0 : 1); - int fullRows = needSlotSpaces / itemsPerRow; - int rows = fullRows + extraRow; - - return 9 * rows; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/EconomyHandler.java b/src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/EconomyHandler.java deleted file mode 100644 index e2169bf..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/EconomyHandler.java +++ /dev/null @@ -1,50 +0,0 @@ -package me.ztowne13.customcrates.interfaces.externalhooks; - -import me.ztowne13.customcrates.Messages; -import me.ztowne13.customcrates.SpecializedCrates; -import net.milkbowl.vault.economy.Economy; -import org.bukkit.entity.Player; -import org.bukkit.plugin.RegisteredServiceProvider; - -public class EconomyHandler { - private final SpecializedCrates instance; - private final boolean enabled; - private Economy economy; - - public EconomyHandler(SpecializedCrates instance) { - this.instance = instance; - this.enabled = instance.getServer().getPluginManager().isPluginEnabled("Vault") && setupEconomy(); - } - - private boolean setupEconomy() { - RegisteredServiceProvider economyProvider = - instance.getServer().getServicesManager().getRegistration(Economy.class); - if (economyProvider != null) { - economy = economyProvider.getProvider(); - } - - return economy != null; - } - - public boolean handleCheck(Player p, int cost, boolean withMessage) { - if (enabled && cost > 0) { - double bal = economy.getBalance(p); - - if (bal < cost) { - if (withMessage) - Messages.ECONOMY_NOT_ENOUGH_MONEY - .msgSpecified(instance, p, new String[]{"%amount%", "%short%"}, new String[]{cost + "", (cost - bal) + ""}); - return false; - } - - economy.withdrawPlayer(p, cost); - } - - return true; - } - - public void failSoReturn(Player p, int cost) { - if (enabled && cost > 0) - economy.depositPlayer(p, cost); - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/PlaceHolderAPIHandler.java b/src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/PlaceHolderAPIHandler.java deleted file mode 100644 index 437c892..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/PlaceHolderAPIHandler.java +++ /dev/null @@ -1,188 +0,0 @@ -package me.ztowne13.customcrates.interfaces.externalhooks; - -import me.clip.placeholderapi.PlaceholderAPI; -import me.clip.placeholderapi.expansion.PlaceholderExpansion; -import me.ztowne13.customcrates.Messages; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.PlacedCrate; -import me.ztowne13.customcrates.players.PlayerDataManager; -import me.ztowne13.customcrates.players.PlayerManager; -import me.ztowne13.customcrates.players.data.VirtualCrateData; -import me.ztowne13.customcrates.utils.Utils; -import org.bukkit.entity.Player; -import org.jetbrains.annotations.NotNull; - -public class PlaceHolderAPIHandler extends PlaceholderExpansion { - private final SpecializedCrates instance; - - public PlaceHolderAPIHandler(SpecializedCrates instance) { - this.instance = instance; - } - - public static String setPlaceHolders(Player player, String message) { - return PlaceholderAPI.setPlaceholders(player, message); - } - - @Override - public boolean persist() { - return true; - } - - @Override - public boolean canRegister() { - return true; - } - - @Override - public @NotNull String getIdentifier() { - return "specializedcrates"; - } - - @Override - public @NotNull String getAuthor() { - return instance.getDescription().getAuthors().toString(); - } - - @Override - public @NotNull String getVersion() { - return instance.getDescription().getVersion(); - } - - @Override - public String onPlaceholderRequest(Player player, @NotNull String identifier) { - // %specializedcrates_virtual_keys_[cratename]% - // %specializedcrates_total_virtual_keys% - // %specializedcrates_virtual_crates_[cratename]% - // %specializedcrates_cooldown_[cratename]% - // %specializedcrates_placedcrates% - // %specializedcrates_last_crate_opened% - // %specializedcrates_last_crate_opened_rewards% - // %specializedcrates_last_player_[cratename]% - // %specializedcrates_last_reward_[cratename]% - - if (!instance.isAllowTick()) - return ""; - - if (player == null) - return ""; - - String[] args = identifier.split("_"); - - PlayerManager playerManager = PlayerManager.get(instance, player); - PlayerDataManager playerDataManager = playerManager.getPlayerDataManager(); - - if (args.length == 1) { - if (args[0].equalsIgnoreCase("placedcrates")) - return PlacedCrate.getPlacedCrates().keySet().size() + ""; - } else if (args.length == 2) { - // specializedcrates_cooldown - if (args[0].equalsIgnoreCase("cooldown")) { - try { - // specializedcrates_cooldown_[cratename] - if (!Crate.exists(args[1])) - return "[" + args[1] + " is an invalid crate]"; - - Crate crate = Crate.getCrate(instance, args[1]); - - if (playerDataManager.getCrateCooldownEventByCrates(crate) == null) - return "-"; - - long seconds = playerDataManager.getCrateCooldownEventByCrates(crate).isCooldownOver(); - - String[] values = Utils.convertSecondToHHMMString(seconds); - String formatted = ""; - - if (!values[0].equalsIgnoreCase("0")) - formatted = - formatted + values[0] + " " + Messages.PLACEHOLDER_DAYS.getProperMsg(crate.getInstance()) + ", "; - if (!values[1].equalsIgnoreCase("00")) - formatted = - formatted + values[1] + " " + Messages.PLACEHOLDER_HOURS.getProperMsg(crate.getInstance()) + ", "; - if (!values[2].equalsIgnoreCase("00")) - formatted = formatted + values[2] + " " + Messages.PLACEHOLDER_MINUTES.getProperMsg(crate.getInstance()) + - ", "; - if (!values[3].equalsIgnoreCase("00")) - formatted = formatted + values[3] + " " + Messages.PLACEHOLDER_SECONDS.getProperMsg(crate.getInstance()); -// else -// formatted = formatted.substring(0, formatted.length() - 2); - - return formatted.equals("") ? "0" : formatted; - } catch (Exception exc) { - exc.printStackTrace(); - } - } - } else if (args.length == 3) { - // specializedcrates_virtual - if (args[0].equalsIgnoreCase("virtual")) { - // specialized_virtual_..._[cratename] - if (!Crate.exists(args[2])) - return "[" + args[2] + " is an invalid crate]"; - - Crate crate = Crate.getCrate(instance, args[2]); - - // specializedcrates_virtual_keys_[cratename] - if (args[1].equalsIgnoreCase("keys")) { - String value = "0"; - try { - value = "" + playerDataManager.getVirtualCrateData().get(crate).getKeys(); - } catch (Exception exc) { - // IGNORED - } - - return value; - } - // specializedcrates_virtual_crates_[cratename] - else if (args[1].equalsIgnoreCase("crates")) { - String value = "0"; - - try { - value = playerDataManager.getVirtualCrateData().get(crate).getCrates() + ""; - } catch (Exception exc) { - // IGNORED - } - - return value; - } - } else if (args[0].equalsIgnoreCase("last")) { - if (args[1].equalsIgnoreCase("crate") && args[2].equalsIgnoreCase("opened")) { - if (!playerDataManager.getHistoryEvents().isEmpty()) - return playerDataManager.getHistoryEvents().get(playerDataManager.getHistoryEvents().size() - 1) - .getCrate().getName(); - else - return "None"; - } - - if (!Crate.exists(args[2])) - return "[" + args[2] + " is an invalid crate]"; - - Crate crate = Crate.getCrate(instance, args[2]); - - if (args[1].equalsIgnoreCase("player")) - return crate.getLastOpenedName(); - else if (args[1].equalsIgnoreCase("reward")) - return crate.getLastOpenedReward(); - } else if (args[0].equalsIgnoreCase("total") && args[1].equalsIgnoreCase("virtual") && - args[2].equalsIgnoreCase("keys")) { - int total = 0; - for (VirtualCrateData virtualCrateData : playerDataManager.getVirtualCrateData().values()) { - total += virtualCrateData.getKeys(); - } - - return total + ""; - } - } else if (args.length == 4 && - args[0].equalsIgnoreCase("last") && args[1].equalsIgnoreCase("crate") && - args[2].equalsIgnoreCase("opened") && args[3].equalsIgnoreCase("rewards")) { - if (!playerDataManager.getHistoryEvents().isEmpty()) { - String rewards = - playerDataManager.getHistoryEvents().get(playerDataManager.getHistoryEvents().size() - 1) - .getRewards().toString(); - return rewards.substring(1, rewards.length() - 1); - } else { - return "None"; - } - } - return null; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/Hologram.java b/src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/Hologram.java deleted file mode 100644 index 6761a18..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/Hologram.java +++ /dev/null @@ -1,29 +0,0 @@ -package me.ztowne13.customcrates.interfaces.externalhooks.holograms; - -import me.ztowne13.customcrates.SpecializedCrates; -import org.bukkit.Location; - -public abstract class Hologram { - protected final SpecializedCrates instance; - - protected Location location; - - public Hologram(SpecializedCrates instance, Location location) { - this.instance = instance; - this.location = location; - } - - public abstract void addLine(String line); - - public abstract void setLine(int i, String line); - - public abstract void delete(); - - public Location getLocation() { - return location; - } - - public void setLocation(Location location) { - this.location = location; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/HologramManager.java b/src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/HologramManager.java deleted file mode 100644 index c580af3..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/HologramManager.java +++ /dev/null @@ -1,35 +0,0 @@ -package me.ztowne13.customcrates.interfaces.externalhooks.holograms; - -import me.ztowne13.customcrates.SpecializedCrates; -import org.bukkit.Location; - -import java.util.ArrayList; -import java.util.List; - -public abstract class HologramManager { - protected final SpecializedCrates instance; - - protected List holograms; - - public HologramManager(SpecializedCrates instance) { - this.instance = instance; - holograms = new ArrayList<>(); - } - - public Hologram createHologram(Location location) { - Hologram hologram = newHologram(location); - holograms.add(hologram); - return hologram; - } - - public abstract Hologram newHologram(Location location); - - public void deleteHologram(Hologram hologram) { - hologram.delete(); - holograms.remove(hologram); - } - - public List getHolograms() { - return holograms; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/cmi/ZripsHologram.java b/src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/cmi/ZripsHologram.java deleted file mode 100644 index 442a5c0..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/cmi/ZripsHologram.java +++ /dev/null @@ -1,57 +0,0 @@ -package me.ztowne13.customcrates.interfaces.externalhooks.holograms.cmi; - -import com.Zrips.CMI.CMI; -import com.Zrips.CMI.Containers.CMILocation; -import com.Zrips.CMI.Modules.Holograms.CMIHologram; -import com.Zrips.CMI.Modules.Holograms.HologramManager; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.interfaces.externalhooks.holograms.Hologram; -import org.bukkit.Location; - -public class ZripsHologram extends Hologram { - private final HologramManager hologramManager; - private final CMIHologram cmiHologram; - - public ZripsHologram(SpecializedCrates instance, Location location) { - super(instance, location); - hologramManager = CMI.getInstance().getHologramManager(); - this.cmiHologram = - new CMIHologram( - "Crate(" + location.getWorld().getName() + "," - + location.getBlockX() + "," - + location.getBlockY() + "," - + location.getBlockZ() + ")", new CMILocation(location)); - - CMI.getInstance().getHologramManager().addHologram(this.cmiHologram); - this.cmiHologram.update(); - } - - @Override - public void addLine(String line) { - cmiHologram.getLines().add(line); - cmiHologram.refresh(); - } - - @Override - public void setLine(int i, String line) { - if (i >= cmiHologram.getLines().size()) { - addLine(line); - } else { - cmiHologram.getLines().set(i, line); - cmiHologram.refresh(); - } - } - - @Override - public void delete() { - hologramManager.removeHolo(cmiHologram); - cmiHologram.disable(); - } - - @Override - public void setLocation(Location location) { - super.setLocation(location); - cmiHologram.setLoc(location); - cmiHologram.refresh(); - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/cmi/ZripsHologramManager.java b/src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/cmi/ZripsHologramManager.java deleted file mode 100644 index a5c7fbc..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/cmi/ZripsHologramManager.java +++ /dev/null @@ -1,17 +0,0 @@ -package me.ztowne13.customcrates.interfaces.externalhooks.holograms.cmi; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.interfaces.externalhooks.holograms.Hologram; -import me.ztowne13.customcrates.interfaces.externalhooks.holograms.HologramManager; -import org.bukkit.Location; - -public class ZripsHologramManager extends HologramManager { - public ZripsHologramManager(SpecializedCrates instance) { - super(instance); - } - - @Override - public Hologram newHologram(Location location) { - return new ZripsHologram(instance, location); - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/holograms/SainttXHologram.java b/src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/holograms/SainttXHologram.java deleted file mode 100644 index ea9f7fe..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/holograms/SainttXHologram.java +++ /dev/null @@ -1,65 +0,0 @@ -package me.ztowne13.customcrates.interfaces.externalhooks.holograms.holograms; - -import com.sainttx.holograms.HologramPlugin; -import com.sainttx.holograms.api.HologramManager; -import com.sainttx.holograms.api.line.TextLine; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.interfaces.externalhooks.holograms.Hologram; -import me.ztowne13.customcrates.utils.LocationUtils; -import org.bukkit.Location; -import org.bukkit.plugin.java.JavaPlugin; - -import java.util.UUID; - -public class SainttXHologram extends Hologram { - private final HologramManager hm; - private final com.sainttx.holograms.api.Hologram hologram; - private double defaultYOffSet = -.2; - - public SainttXHologram(SpecializedCrates instance, Location location) { - super(instance, location); - this.hm = JavaPlugin.getPlugin(HologramPlugin.class).getHologramManager(); - UUID uuid = UUID.randomUUID(); - this.hologram = new com.sainttx.holograms.api.Hologram(uuid.toString(), location); - hm.addActiveHologram(hologram); - this.hologram.spawn(); - setLocation(location); - } - - @Override - public void addLine(String line) { - hologram.addLine(new TextLine(hologram, line)); - if (hologram.getLine(0).getRaw().equalsIgnoreCase("THIS LINE SHOULD BE GETTING REMOVED")) { - hologram.removeLine(hologram.getLine(0)); - } - } - - @Override - public void setLine(int i, String line) { - hologram.removeLine(hologram.getLine(i)); - hologram.addLine(new TextLine(hologram, line), i); - } - - @Override - public void delete() { - if (hologram != null && hm != null) { - hm.removeActiveHologram(hologram); - hm.deleteHologram(hologram); - } - } - - @Override - public void setLocation(Location location) { - location.setY(location.getY() + getDefaultYOffSet()); - super.setLocation(LocationUtils.getLocationCentered(location)); - hologram.teleport(this.location); - } - - public double getDefaultYOffSet() { - return defaultYOffSet; - } - - public void setDefaultYOffSet(double defaultYOffSet) { - this.defaultYOffSet = defaultYOffSet; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/holograms/SainttXHologramManager.java b/src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/holograms/SainttXHologramManager.java deleted file mode 100644 index 8b3dd36..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/holograms/SainttXHologramManager.java +++ /dev/null @@ -1,17 +0,0 @@ -package me.ztowne13.customcrates.interfaces.externalhooks.holograms.holograms; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.interfaces.externalhooks.holograms.Hologram; -import me.ztowne13.customcrates.interfaces.externalhooks.holograms.HologramManager; -import org.bukkit.Location; - -public class SainttXHologramManager extends HologramManager { - public SainttXHologramManager(SpecializedCrates instance) { - super(instance); - } - - @Override - public Hologram newHologram(Location location) { - return new SainttXHologram(instance, location); - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/holographicdisplays/HDHologram.java b/src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/holographicdisplays/HDHologram.java deleted file mode 100644 index 877911c..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/holographicdisplays/HDHologram.java +++ /dev/null @@ -1,50 +0,0 @@ -package me.ztowne13.customcrates.interfaces.externalhooks.holograms.holographicdisplays; - -import com.gmail.filoghost.holographicdisplays.api.HologramsAPI; -import com.gmail.filoghost.holographicdisplays.api.line.TextLine; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.interfaces.externalhooks.holograms.Hologram; -import org.bukkit.Location; - -import java.util.HashMap; - -public class HDHologram extends Hologram { - private final com.gmail.filoghost.holographicdisplays.api.Hologram hologram; - private final HashMap lines = new HashMap<>(); - - public HDHologram(SpecializedCrates instance, Location location) { - super(instance, location); - this.hologram = HologramsAPI.createHologram(instance, location); - - setLocation(location); - hologram.setAllowPlaceholders(true); - } - - @Override - public void addLine(String line) { - TextLine tl = hologram.appendTextLine(line); - lines.put(hologram.size() - 1, tl); - } - - @Override - public void setLine(int i, String line) { - if (lines.containsKey(i)) { - lines.get(i).setText(line); - } else { - addLine(line); - } - } - - @Override - public void delete() { - if (hologram != null) { - hologram.delete(); - } - } - - @Override - public void setLocation(Location location) { - super.setLocation(location); - hologram.teleport(location); - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/holographicdisplays/HDHologramManager.java b/src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/holographicdisplays/HDHologramManager.java deleted file mode 100644 index c593054..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/holographicdisplays/HDHologramManager.java +++ /dev/null @@ -1,17 +0,0 @@ -package me.ztowne13.customcrates.interfaces.externalhooks.holograms.holographicdisplays; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.interfaces.externalhooks.holograms.Hologram; -import me.ztowne13.customcrates.interfaces.externalhooks.holograms.HologramManager; -import org.bukkit.Location; - -public class HDHologramManager extends HologramManager { - public HDHologramManager(SpecializedCrates instance) { - super(instance); - } - - @Override - public Hologram newHologram(Location location) { - return new HDHologram(instance, location); - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/nohologram/NoHologramManager.java b/src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/nohologram/NoHologramManager.java deleted file mode 100644 index b4bcdaf..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/externalhooks/holograms/nohologram/NoHologramManager.java +++ /dev/null @@ -1,35 +0,0 @@ -package me.ztowne13.customcrates.interfaces.externalhooks.holograms.nohologram; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.interfaces.externalhooks.holograms.Hologram; -import me.ztowne13.customcrates.interfaces.externalhooks.holograms.HologramManager; -import org.bukkit.Location; - -public class NoHologramManager extends HologramManager { - private final Hologram noHologram; - - public NoHologramManager(SpecializedCrates instance) { - super(instance); - this.noHologram = new Hologram(instance, null) { - @Override - public void addLine(String line) { - // EMPTY - } - - @Override - public void setLine(int i, String line) { - // EMPTY - } - - @Override - public void delete() { - // EMPTY - } - }; - } - - @Override - public Hologram newHologram(Location location) { - return noHologram; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/files/FileDataLoader.java b/src/main/java/me/ztowne13/customcrates/interfaces/files/FileDataLoader.java deleted file mode 100644 index 8e18b74..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/files/FileDataLoader.java +++ /dev/null @@ -1,181 +0,0 @@ -package me.ztowne13.customcrates.interfaces.files; - -import com.cryptomorin.xseries.XMaterial; -import com.cryptomorin.xseries.XSound; -import me.ztowne13.customcrates.crates.options.sounds.SoundData; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.interfaces.logging.StatusLogger; -import me.ztowne13.customcrates.interfaces.logging.StatusLoggerEvent; -import me.ztowne13.customcrates.utils.Utils; - -import java.util.Optional; - -/** - * Created by ztowne13 on 7/7/16. - */ -public class FileDataLoader { - private final FileHandler fileHandler; - - public FileDataLoader(FileHandler fileHandler) { - this.fileHandler = fileHandler; - } - - public String loadString(String path, StatusLogger statusLogger, StatusLoggerEvent pathDoesntExist, StatusLoggerEvent success) { - if (!fileHandler.get().contains(path)) { - pathDoesntExist.log(statusLogger, path); - return ""; - } - - success.log(statusLogger); - return fileHandler.get().getString(path); - } - - public ItemBuilder loadItem(String path, ItemBuilder defValue, StatusLogger statusLogger, StatusLoggerEvent pathDoesntExist, - StatusLoggerEvent invalid) { - if (!fileHandler.get().contains(path)) { - pathDoesntExist.log(statusLogger, path); - return defValue; - } - - String value = fileHandler.get().getString(path); - - Optional optional = XMaterial.matchXMaterial(value.replace(";", ":")); - if (optional.isPresent()) { - return new ItemBuilder(optional.get(), 1); - } else { - invalid.log(statusLogger, value); - } - return defValue; - } - - public SoundData loadSound(String path, StatusLogger statusLogger, StatusLoggerEvent pathDoesntExist, - StatusLoggerEvent soundSuccess, - StatusLoggerEvent soundFailure, - StatusLoggerEvent volumeSuccess, - StatusLoggerEvent volumeInvalid, - StatusLoggerEvent noVolPitch, - StatusLoggerEvent pitchSuccess, - StatusLoggerEvent pitchInvalid) { - if (!fileHandler.get().contains(path)) { - pathDoesntExist.log(statusLogger, path); - return new SoundData(XSound.values()[0], 0); - } - - String value = fileHandler.get().getString(path); - - String[] args = value.replaceAll("\\s+", "").split(","); - - Optional optional = XSound.matchXSound(args[0]); - if (optional.isPresent()) { - SoundData sd = new SoundData(optional.get()); - soundSuccess.log(statusLogger); - - if (args.length >= 2) { - if (Utils.isInt(args[1])) { - sd.setVolume(Integer.parseInt(args[1])); - volumeSuccess.log(statusLogger); - } else { - sd.setVolume(5); - volumeInvalid.log(statusLogger, args[1]); - } - - if (args.length >= 3) { - if (Utils.isInt(args[2])) { - sd.setPitch(Integer.parseInt(args[2])); - pitchSuccess.log(statusLogger); - } else { - sd.setPitch(5); - pitchInvalid.log(statusLogger, args[2]); - } - } else { - sd.setPitch(5); - } - } else { - noVolPitch.log(statusLogger); - sd.setVolume(5); - sd.setPitch(5); - } - - return sd; - } else { - soundFailure.log(statusLogger); - } - - return new SoundData(XSound.values()[0], 0); - } - - public int loadInt(String path, int defValue, StatusLogger statusLogger, StatusLoggerEvent pathDoesntExist, - StatusLoggerEvent success, StatusLoggerEvent invalid) { - if (!fileHandler.get().contains(path)) { - pathDoesntExist.log(statusLogger, path); - return defValue; - } - - String value = fileHandler.get().getString(path); - - if (Utils.isInt(value)) { - success.log(statusLogger); - return Integer.parseInt(value); - } else { - invalid.log(statusLogger); - return defValue; - } - } - - public double loadDouble(String path, double defValue, StatusLogger statusLogger, StatusLoggerEvent pathDoesntExist, - StatusLoggerEvent success, - StatusLoggerEvent invalid) { - if (!fileHandler.get().contains(path)) { - pathDoesntExist.log(statusLogger, path); - return defValue; - } - - String value = fileHandler.get().getString(path); - - if (Utils.isDouble(value)) { - success.log(statusLogger); - return Double.parseDouble(value); - } else { - invalid.log(statusLogger); - return defValue; - } - } - - public long loadLong(String path, long defValue, StatusLogger statusLogger, StatusLoggerEvent pathDoesntExist, - StatusLoggerEvent success, - StatusLoggerEvent invalid) { - if (!fileHandler.get().contains(path)) { - pathDoesntExist.log(statusLogger, path); - return defValue; - } - - String value = fileHandler.get().getString(path); - - if (Utils.isLong(value)) { - success.log(statusLogger); - return Long.parseLong(value); - } else { - invalid.log(statusLogger); - return defValue; - } - } - - public boolean loadBoolean(String path, boolean defValue, StatusLogger statusLogger, StatusLoggerEvent pathDoesntExist, - StatusLoggerEvent success, - StatusLoggerEvent invalid) { - if (!fileHandler.get().contains(path)) { - pathDoesntExist.log(statusLogger, path); - return defValue; - } - - String value = fileHandler.get().getString(path); - - if (Utils.isBoolean(value)) { - success.log(statusLogger); - return Boolean.parseBoolean(value); - } else { - invalid.log(statusLogger); - return defValue; - } - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/files/FileHandler.java b/src/main/java/me/ztowne13/customcrates/interfaces/files/FileHandler.java deleted file mode 100644 index dfba744..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/files/FileHandler.java +++ /dev/null @@ -1,360 +0,0 @@ -package me.ztowne13.customcrates.interfaces.files; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.DebugUtils; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; - -import java.io.*; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.Map; -import java.util.logging.Level; - -public class FileHandler { - - private static Map map = new HashMap<>(); - private final SpecializedCrates instance; - private final FileDataLoader fileDataLoader; - private String name; - private String directory = ""; - private String loaded; - private boolean canBeEdited; - private boolean saveWithCustomSave; - private boolean properLoad = false; - private boolean newFile; - private FileConfiguration data = null; - private File dataFile = null; - - public FileHandler(SpecializedCrates instance, String name, String directory, boolean canBeEdited, boolean saveWithCustomSave, - boolean newFile) { - this.name = name; - this.instance = instance; - this.directory = directory; - this.canBeEdited = canBeEdited; - this.saveWithCustomSave = saveWithCustomSave; - this.newFile = newFile; - - this.fileDataLoader = new FileDataLoader(this); - - map.put(name, this); - } - - public FileHandler(SpecializedCrates instance, String name, boolean canBeEdited, boolean saveWithCustomSave) { - this.name = name; - this.canBeEdited = canBeEdited; - this.instance = instance; - this.saveWithCustomSave = saveWithCustomSave; - - this.fileDataLoader = new FileDataLoader(this); - - map.put(name, this); - } - - public static void clearLoaded() { - map.clear(); - map = new HashMap<>(); - } - - public static Map getMap() { - return map; - } - - public static void setMap(Map map) { - FileHandler.map = map; - } - - public void loadFile() { - instance.getDebugUtils().log("loadFile() - CALL", getClass(), false); - - if (getDataFile() == null) { - setDataFile(new File(new File(instance.getDataFolder().getPath() + getDirectory()), getName())); - - if (getName().equalsIgnoreCase("Messages.yml") && !folderExists("Crates")) { - new File(instance.getDataFolder().getPath() + getDirectory()).mkdir(); - - try { - instance.firstLoadFiles(); - } catch (Exception exc) { - exc.printStackTrace(); - } - } - } - } - - public void reload() { - instance.getDebugUtils().log("reload() - CALL", getClass(), false); - - loadFile(); - - try { - data = YamlConfiguration.loadConfiguration(getDataFile()); - - if (canBeEdited) { - data.saveToString(); - if (name.equalsIgnoreCase("Rewards.YML") || !data.saveToString().equalsIgnoreCase("")) { - File defConfigFile = new File(instance.getDataFolder(), getName()); - if (defConfigFile.exists()) { - YamlConfiguration defConfig = YamlConfiguration.loadConfiguration(defConfigFile); - getData().setDefaults(defConfig); - } - - - if (isCanBeEdited()) { - loadByByte(); - } - - properLoad = true; - } else { - if (!newFile) - throw new NullPointerException("Failed to load the file " + getName()); - } - } else { - properLoad = true; - } - } catch (Exception exc) { - exc.printStackTrace(); - ChatUtils.log(new String[]{"Failed to load the " + name + - " file due to a critical error. Please fix the file and restart your server.", - "Oftentimes, if this is your first time loading the server, a simple reload or restart fixes the issue!"}); - properLoad = false; - } - } - - private void loadByByte() { - instance.getDebugUtils().log("loadByByte() - CALL", getClass(), false); - - if (saveWithCustomSave) { - try { - FileInputStream fileInputSteamBefore = new FileInputStream(getDataFile()); - InputStreamReader fileInputSteam = new InputStreamReader(fileInputSteamBefore, StandardCharsets.UTF_8); - - setLoaded(""); - - int content; - while ((content = fileInputSteam.read()) != -1) { - setLoaded(getLoaded() + ((char) content)); - } - - getData().loadFromString(getLoaded()); - } catch (Exception exc) { - // IGNORED - } - } - } - - public boolean folderExists(String path) { - try { - for (File file : instance.getDataFolder().listFiles()) { - if (file.isDirectory() && file.getName().equalsIgnoreCase(path.replace("/", ""))) { - return true; - } - } - } catch (Exception exc) { - // IGNORED - } - return false; - } - - public void save() { - instance.getDebugUtils().log("save() - CALL", getClass(), false); - long curTime = System.currentTimeMillis(); - - if (getData() == null || getDataFile() == null) { - return; - } - - try { - if (properLoad || newFile) { - if (!isSaveWithCustomSave() || newFile) { - get().save(getDataFile()); - } else { - saveByByte(); - } - } else { - ChatUtils.log(name + " file not saving to prevent it from further damage."); - } - } catch (Exception ex) { - ex.printStackTrace(); - instance.getLogger().log(Level.SEVERE, ex, () -> "Could not save config to " + getDataFile()); - } - instance.getDebugUtils().log("save() - Time to complete: " + (System.currentTimeMillis() - curTime), getClass()); - if (DebugUtils.OUTPUT_FILE_SAVE_TIME) { - ChatUtils.log("Time to save " + name + ": " + (System.currentTimeMillis() - curTime)); - } - } - - private void saveByByte() { - instance.getDebugUtils().log("saveByByte() - CALL", getClass(), false); - ArrayList bukkitLoad = new ArrayList<>(); - for (String s : getData().saveToString().split("\n")) { - if (!isCommentLine(s)) { - bukkitLoad.add(s); - } - } - - ArrayList byteLoad = new ArrayList<>(Arrays.asList(getLoaded().split("\n"))); - - StringBuilder modifiedString = new StringBuilder(); - - HashMap lastLevel = new HashMap<>(); - - for (String s : bukkitLoad) { - StringBuilder commentSec = new StringBuilder(); - String without = ChatUtils.stripFromWhitespace(s); - - if (!isCommentLine(s)) { - String[] split1 = without.split(":"); - - int id = 0; - int currentLevel = 0; - for (String bks : byteLoad) { - if (ChatUtils.stripFromWhitespace(bks).split(":")[0].equals(split1[0])) { - if (!lastLevel.containsKey(split1[0]) || lastLevel.get(split1[0]) < currentLevel) { - lastLevel.put(split1[0], currentLevel); - break; - } - currentLevel++; - } - id++; - } - - for (int end = id - 1; end > -1; end--) { - String line = byteLoad.get(end); - if (isCommentLine(line)) { - commentSec.insert(0, line + "\n"); - } else if (!line.equalsIgnoreCase(s)) { - break; - } - } - } - modifiedString.append(commentSec).append(s).append("\n"); - } - - try { - FileOutputStream fop = new FileOutputStream(getDataFile()); - - byte[] contentInBytes = modifiedString.toString().getBytes(); - - fop.write(contentInBytes); - fop.flush(); - fop.close(); - - } catch (IOException e) { - e.printStackTrace(); - } - } - - public void copy(FileHandler dest) throws IOException { - InputStream is; - OutputStream os; - - is = new FileInputStream(getDataFile()); - os = new FileOutputStream(dest.getDataFile()); - byte[] buffer = new byte[1024]; - int length; - while ((length = is.read(buffer)) > 0) { - os.write(buffer, 0, length); - } - - is.close(); - os.close(); - } - - public FileConfiguration get() { - instance.getDebugUtils().log("get() - CALL", getClass(), false); - if (getData() == null) { - reload(); - } - return getData(); - } - - public void saveDefaults() { - loadFile(); - - if (!dataFile.exists()) { - instance.saveResource(directory + name, false); - } - - if (dataFile == null) { - reload(); - } - } - - public boolean isCommentLine(String s) { - return s.trim().length() == 0 || s.equalsIgnoreCase("\n") || ChatUtils.stripFromWhitespace(s).startsWith("#"); - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public String getDirectory() { - return directory; - } - - public void setDirectory(String directory) { - this.directory = directory; - } - - public String getLoaded() { - return loaded; - } - - public void setLoaded(String loaded) { - this.loaded = loaded; - } - - public FileConfiguration getData() { - instance.getDebugUtils().log("getData() - CALL", getClass(), false); - - return data; - } - - public void setData(FileConfiguration data) { - this.data = data; - } - - public File getDataFile() { - return dataFile; - } - - public void setDataFile(File dataFile) { - this.dataFile = dataFile; - } - - public boolean isCanBeEdited() { - return canBeEdited; - } - - public void setCanBeEdited(boolean canBeEdited) { - this.canBeEdited = canBeEdited; - } - - public boolean isProperLoad() { - return properLoad; - } - - public void setProperLoad(boolean properLoad) { - this.properLoad = properLoad; - } - - public boolean isSaveWithCustomSave() { - return saveWithCustomSave; - } - - public void setSaveWithCustomSave(boolean saveWithCustomSave) { - this.saveWithCustomSave = saveWithCustomSave; - } - - public FileDataLoader getFileDataLoader() { - return fileDataLoader; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/files/FileSettings.java b/src/main/java/me/ztowne13/customcrates/interfaces/files/FileSettings.java deleted file mode 100644 index 72e93af..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/files/FileSettings.java +++ /dev/null @@ -1,13 +0,0 @@ -package me.ztowne13.customcrates.interfaces.files; - -/** - * Created by ztowne13 on 6/8/16. - */ -public class FileSettings { - public static final String SPLITTER_1 = ","; - public static final String SPLITTER_2 = ";"; - - private FileSettings() { - // EMPTY - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/IGCDefaultItems.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/IGCDefaultItems.java deleted file mode 100644 index 97507ba..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/IGCDefaultItems.java +++ /dev/null @@ -1,36 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; - -/** - * Created by ztowne13 on 3/11/16. - */ -public enum IGCDefaultItems { - EXIT_BUTTON( - new ItemBuilder(XMaterial.GRAY_DYE, 1).setDisplayName("&cExit").setLore("&4&oNOTE: THIS DOES NOT SAVE CHANGES") - .addLore("").addLore("&7Exit or return to the previous menu.")), - - SAVE_BUTTON(new ItemBuilder(XMaterial.LIME_DYE, 1).setDisplayName("&aSave and reload").addLore("") - .addLore("&7Save your current changes and reload the plugin.")), - - SAVE_ONLY_BUTTON(new ItemBuilder(XMaterial.LIME_DYE, 1).setDisplayName("&aSave").setLore("&7Note: click reload to") - .addLore("&7see the changes.")), - - RELOAD_BUTTON(new ItemBuilder(XMaterial.PINK_DYE, 1).setDisplayName("&aReload").setLore("&7This reloads the plugin") - .addLore("&4&lMAKE SURE YOU SAVE FIRST!")); - - ItemBuilder ib; - - IGCDefaultItems(ItemBuilder ib) { - this.ib = ib; - } - - public ItemBuilder getIb() { - return ib; - } - - public void setIb(ItemBuilder ib) { - this.ib = ib; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/IGCListEditor.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/IGCListEditor.java deleted file mode 100644 index 792c288..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/IGCListEditor.java +++ /dev/null @@ -1,181 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.InventoryUtils; -import me.ztowne13.customcrates.interfaces.igc.inputmenus.InputMenu; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.ReflectionUtilities; -import org.bukkit.Material; -import org.bukkit.entity.Player; - -import java.lang.reflect.Method; -import java.util.List; - -public class IGCListEditor extends IGCMenu { - int page; - String header; - String identifier; - XMaterial displayItem; - List values; - boolean deleteMode = false; - Class clazz = null; - String methodName, errorMsg; - - public IGCListEditor(SpecializedCrates cc, Player p, IGCMenu lastMenu, String header, String identifier, - List values, XMaterial displayItem, int page) { - super(cc, p, lastMenu, "&7&l> &6&l" + header + " PG" + page); - this.header = header; - this.values = values; - this.identifier = identifier; - this.page = page; - this.displayItem = displayItem; - } - - public IGCListEditor(SpecializedCrates cc, Player p, IGCMenu lastMenu, String header, String identifier, - List values, XMaterial displayItem, int page, Class clazz, String methodName, String errorMsg) { - this(cc, p, lastMenu, header, identifier, values, displayItem, page); - this.clazz = clazz; - this.methodName = methodName; - this.errorMsg = errorMsg; - } - - @Override - public void openMenu() { - - int slots; - - if (values.size() - ((page - 1) * 28) > 28) - slots = 28; - else - slots = values.size() - ((page - 1) * 28); - - slots = InventoryUtils.getRowsFor(2, slots) + 9; - - if (header.length() > 18) { - header = header.substring(0, 18); - } - setInventoryName("&7&l> &6&l" + header + " PG" + page); - InventoryBuilder ib = createDefault(slots, 18); - - ib.setItem(0, IGCDefaultItems.EXIT_BUTTON.getIb()); - ib.setItem(8, new ItemBuilder(XMaterial.PAPER) - .setDisplayName("&aAdd a new " + ChatUtils.removeColor(identifier).toLowerCase()) - .setLore("&7Reminder: you must save for").addLore("&7any changes to take effect.")); - - updateDeleteMode(); - - int i = 10; - int toSkip = ((page - 1) * 28); - int skipped = 0; - int displayedItems = 0; - int itemNum = (page - 1) * 28; - - for (Object val : values) { - if (toSkip > skipped || displayedItems >= 28) { - skipped++; - continue; - } - - if (i % 9 == 8) { - i += 2; - } - - itemNum++; - ItemBuilder item = new ItemBuilder(displayItem).setDisplayName("&a" + identifier + " " + itemNum); - - item.addLore("&f" + val.toString()); - item.addLore("") - .addLore("&7&oClick to edit this " + ChatUtils.removeColor(identifier).toLowerCase() + "."); - - - ib.setItem(i, item); - i++; - displayedItems++; - } - - if (page != 1) { - ib.setItem(2, new ItemBuilder(XMaterial.ARROW).setDisplayName("&aGo back a page")); - } - - if (((values.size() / 28) + (values.size() % 28 == 0 ? 0 : 1) != page) && values.isEmpty()) { - ib.setItem(6, new ItemBuilder(XMaterial.ARROW).setDisplayName("&aGo forward a page")); - } - - ib.open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - if (slot == 0) { - up(); - } else if (slot == 2 && getIb().getInv().getItem(slot).getType() == Material.ARROW) { - page--; - open(); - } else if (slot == 6 && getIb().getInv().getItem(slot).getType() == Material.ARROW) { - page++; - open(); - } else if (slot == 8) { - new InputMenu(getCc(), getP(), "new " + ChatUtils.removeColor(identifier), "null", clazz != null ? clazz : String.class, this); - } else if (slot == 17) { - deleteMode = !deleteMode; - updateDeleteMode(); - } else if (getIb().getInv().getItem(slot) != null && getIb().getInv().getItem(slot).getType().equals(displayItem.parseMaterial())) { - ItemBuilder clickedItem = new ItemBuilder(getIb().getInv().getItem(slot)); - if (deleteMode) { - String[] split = ChatUtils.removeColor(clickedItem.getName(true)).split(" "); - int id = Integer.parseInt(split[split.length - 1]); - values.remove(id - 1); - open(); - } else { - new InputMenu(getCc(), getP(), ChatUtils.removeColor(clickedItem.getName(true)), - clickedItem.getItemMeta().getLore().get(0), String.class, this); - } - } - } - - @Override - public boolean handleInput(String value, String input) { - Object handledInput = input; - if (clazz != null) { - try { - Method method = ReflectionUtilities.getMethod(clazz, methodName, String.class); - handledInput = method.invoke(clazz, input.toUpperCase()); - - } catch (Exception exc) { - ChatUtils.msgError(getP(), errorMsg); - return false; - } - } - - if (value.equalsIgnoreCase("new " + ChatUtils.removeColor(identifier))) { - values.add(handledInput); - ChatUtils.msgSuccess(getP(), "Added the " + identifier + " '" + input + "'"); - } else { - String[] split = value.split(" "); - int id = Integer.parseInt(split[split.length - 1]); - - values.set(id - 1, handledInput); - - ChatUtils.msgSuccess(getP(), "Updated the " + identifier + " to '" + input + "'"); - } - return true; - } - - public void updateDeleteMode() { - if (!deleteMode) { - getIb().setItem(17, new ItemBuilder(XMaterial.RED_CARPET).setDisplayName("&aEnable 'remove' mode") - .setLore("&7By enabling 'remove' mode") - .addLore("&7you can just click on " + ChatUtils.removeColor(identifier) + "s") - .addLore("&7to remove them").addLore("").addLore("&fDelete every item to use the") - .addLore("&fdefault lore in the config.yml")); - } else { - getIb().setItem(17, new ItemBuilder(XMaterial.RED_CARPET).setDisplayName("&cDisable 'remove' mode") - .setLore("&7This will stop you from").addLore("&7removing " + ChatUtils.removeColor(identifier) + "s") - .addLore("").addLore("&fDelete every item to use the").addLore("&fdefault lore in the config.yml")); - } - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/IGCListSelector.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/IGCListSelector.java deleted file mode 100644 index 247e2a2..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/IGCListSelector.java +++ /dev/null @@ -1,144 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.InventoryUtils; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import org.bukkit.Material; -import org.bukkit.entity.Player; - -import java.util.List; - -public class IGCListSelector extends IGCMenu { - int page; - String header; - XMaterial displayItem; - List values; - List builders = null; - List descriptors = null; - boolean reopen = true; - - public IGCListSelector(SpecializedCrates cc, Player p, IGCMenu lastMenu, String header, - List values, XMaterial displayItem, int page, List descriptors, boolean reopen) { - super(cc, p, lastMenu, "&7&l> &6&l" + header + " PG" + page); - this.header = header; - this.values = values; - this.page = page; - this.displayItem = displayItem; - this.descriptors = descriptors; - this.reopen = reopen; - } - - public IGCListSelector(SpecializedCrates cc, Player p, IGCMenu lastMenu, String header, - List values, XMaterial displayItem, int page, List descriptors) { - this(cc, p, lastMenu, header, values, displayItem, page, descriptors, true); - } - - public IGCListSelector(SpecializedCrates cc, Player p, IGCMenu lastMenu, String header, - List values, XMaterial displayItem, int page, List descriptors, - List builders) { - this(cc, p, lastMenu, header, values, displayItem, page, descriptors); - this.builders = builders; - } - - @Override - public void openMenu() { - int slots; - - if (values.size() - ((page - 1) * 28) > 28) - slots = 28; - else - slots = values.size() - ((page - 1) * 28); - - slots = InventoryUtils.getRowsFor(2, slots) + 9; - - setInventoryName("&7&l> &6&l" + header + " PG" + page); - InventoryBuilder ib = createDefault(slots, 18); - - ib.setItem(0, IGCDefaultItems.EXIT_BUTTON.getIb()); - - int i = 10; - int toSkip = ((page - 1) * 28); - int skipped = 0; - int displayedItems = 0; - int itemNum = (page - 1) * 28; - - int added = 0; - for (Object val : values) { - if (toSkip > skipped || displayedItems >= 28) { - skipped++; - continue; - } - - if (i % 9 == 8) { - i += 2; - } - - itemNum++; - ItemBuilder item; - - if (builders == null) { - item = new ItemBuilder(displayItem, 1).setDisplayName("&a" + val); - - if (descriptors != null) - item.addAutomaticLore("&f", 30, descriptors.get(added)); - - item.addLore("") - .addLore("&7&oClick to select this."); - - added++; - } else { - item = builders.get(added); - item.setDisplayName("&a" + val); - - if (descriptors != null) - item.addAutomaticLore("&f", 30, descriptors.get(added)); - - added++; - } - - ib.setItem(i, item); - i++; - displayedItems++; - } - - if (page != 1) { - ib.setItem(2, new ItemBuilder(XMaterial.ARROW).setDisplayName("&aGo back a page")); - } - - if (((values.size() / 28) + (values.size() % 28 == 0 ? 0 : 1) != page) && values.size() != 0) { - ib.setItem(6, new ItemBuilder(XMaterial.ARROW).setDisplayName("&aGo forward a page")); - } - - ib.open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - if (slot == 0) { - up(); - } else if (slot == 2 && getIb().getInv().getItem(slot).getType() == Material.ARROW) { - page--; - open(); - } else if (slot == 6 && getIb().getInv().getItem(slot).getType() == Material.ARROW) { - page++; - open(); - } else if (getIb().getInv().getItem(slot) != null) { - int row = slot / 9; - int slotInRow = slot % 9; - int num = ((page - 1) * 28) + ((row - 1) * 7) + (slotInRow - 1); - - lastMenu.handleInput(header, values.get(num).toString()); - - if (reopen) - up(); - } - } - - @Override - public boolean handleInput(String value, String input) { - return true; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/IGCMenu.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/IGCMenu.java deleted file mode 100644 index aa5f660..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/IGCMenu.java +++ /dev/null @@ -1,179 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.igc.buttons.IGCButton; -import me.ztowne13.customcrates.interfaces.igc.buttons.IGCButtonType; -import me.ztowne13.customcrates.interfaces.igc.inputmenus.InputMenu; -import me.ztowne13.customcrates.players.PlayerManager; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.entity.Player; - -/** - * Created by ztowne13 on 3/11/16. - */ -public abstract class IGCMenu { - static int GLOBAL_MIN = 9; - - SpecializedCrates cc; - Player p; - - String inventoryName, cVal = "&7Current Value: &f"; - InventoryBuilder ib; - - IGCMenu lastMenu; - InputMenu inputMenu; - - IGCButton[] buttons; - int[] buttonSpots; - - public IGCMenu(SpecializedCrates cc, Player p, IGCMenu lastMenu, String inventoryName) { - this(cc, p, lastMenu, inventoryName, new IGCButtonType[]{}, new int[]{}); - } - - - public IGCMenu(SpecializedCrates cc, Player p, IGCMenu lastMenu, String inventoryName, IGCButtonType[] buttonTypes, int[] buttonSpots) { - this.cc = cc; - this.p = p; - this.inventoryName = inventoryName.length() >= 32 ? inventoryName.substring(0, 31) : inventoryName; - this.lastMenu = lastMenu; - this.buttonSpots = buttonSpots; - this.buttons = new IGCButton[buttonTypes.length]; - for (int i = 0; i < buttonTypes.length; i++) { - this.buttons[i] = buttonTypes[i].createInstance(); - } - } - - public abstract void openMenu(); - - public abstract void handleClick(int slot); - - public abstract boolean handleInput(String value, String input); - - public void open() { - openMenu(); - - for (int i = 0; i < buttonSpots.length; i++) { - int buttonSpot = buttonSpots[i]; - IGCButton button = buttons[i]; - getIb().setItem(buttonSpot, button.getButtonItem()); - } - } - - public void manageClick(int slot) { - for (int i = 0; i < buttonSpots.length; i++) { - int buttonSpot = buttonSpots[i]; - IGCButton button = buttons[i]; - if (buttonSpot == slot) { - if (button.handleClick(this)) { - open(); - } - return; - } - } - - handleClick(slot); - } - - public void putInMenu() { - PlayerManager pm = PlayerManager.get(cc, p); - pm.setOpenMenu(this); - } - - public InventoryBuilder createDefault(int slots) { - if (slots < GLOBAL_MIN) { - slots = GLOBAL_MIN; - } - ib = new InventoryBuilder(p, slots > 54 ? 54 : slots, inventoryName); - return ib; - } - - public InventoryBuilder createDefault(int slots, int minSlots) { - if (slots < GLOBAL_MIN) { - slots = GLOBAL_MIN; - } - if (slots > 54) - slots = 54; - ib = new InventoryBuilder(p, slots, inventoryName, minSlots); - return ib; - } - - public void up() { - lastMenu.open(); - } - - public void reload() { - long start = System.currentTimeMillis(); - getP().closeInventory(); - ChatUtils.msg(getP(), "&6&lINFO! &eReloading..."); - getCc().reload(); - ChatUtils.msgSuccess(getP(), "Reloaded the Specialized Crate plugin &7(" + (System.currentTimeMillis() - start) + "ms)&a."); - } - - - // Getters and Setters - - public SpecializedCrates getCc() { - return cc; - } - - public void setCc(SpecializedCrates cc) { - this.cc = cc; - } - - public Player getP() { - return p; - } - - public void setP(Player p) { - this.p = p; - } - - public String getInventoryName() { - return inventoryName; - } - - public void setInventoryName(String inventoryName) { - this.inventoryName = inventoryName; - } - - public InventoryBuilder getIb() { - return ib; - } - - public void setIb(InventoryBuilder ib) { - this.ib = ib; - } - - public InputMenu getInputMenu() { - return inputMenu; - } - - public void setInputMenu(InputMenu inputMenu) { - this.inputMenu = inputMenu; - } - - public boolean isInInputMenu() { - return !(inputMenu == null); - } - - public IGCMenu getLastMenu() { - return lastMenu; - } - - public void setLastMenu(IGCMenu lastMenu) { - this.lastMenu = lastMenu; - } - - public String getcVal() { - return cVal; - } - - public void setcVal(String cVal) { - this.cVal = cVal; - } - - public IGCButton[] getButtons() { - return buttons; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/IGCMenuMain.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/IGCMenuMain.java deleted file mode 100644 index a8a0c5d..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/IGCMenuMain.java +++ /dev/null @@ -1,115 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.Messages; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.PlacedCrate; -import me.ztowne13.customcrates.crates.options.CReward; -import me.ztowne13.customcrates.crates.types.animations.CrateAnimationType; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.igc.fileconfigs.*; -import me.ztowne13.customcrates.interfaces.igc.fileconfigs.rewards.IGCMenuRewards; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.players.data.SQLDataHandler; -import org.bukkit.entity.Player; - -/** - * Created by ztowne13 on 3/11/16. - */ -public class IGCMenuMain extends IGCMenu { - public IGCMenuMain(SpecializedCrates cc, Player p, IGCMenu lastMenu) { - super(cc, p, lastMenu, "&7&l> &6&lHome"); - } - - @Override - public void openMenu() { - InventoryBuilder ib = createDefault(36); - ib.setItem(0, new ItemBuilder(IGCDefaultItems.SAVE_ONLY_BUTTON.getIb()).setDisplayName("&aSave every file/crate")); - ib.setItem(9, IGCDefaultItems.RELOAD_BUTTON.getIb()); - ib.setItem(27, IGCDefaultItems.EXIT_BUTTON.getIb()); - - ItemBuilder paper = new ItemBuilder(XMaterial.PAPER); - - paper.setDisplayName("&aConfig.YML"); - paper.setLore("").addLore("&6&lEdit various plugin features").addLore("") - .addLore("&7Amount of values: &f" + getCc().getSettings().getConfigValues().keySet().size()); - ib.setItem(11, paper); - - paper.setDisplayName("&aCrateConfig.YML"); - paper.setLore("").addLore("&6&lEdit crate animations").addLore("") - .addLore("&7Amount of animations: &f" + CrateAnimationType.values().length); - ib.setItem(12, paper); - - paper.setDisplayName("&aRewards.YML"); - paper.setLore("").addLore("&6&lCreate / edit rewards").addLore("") - .addLore("&7Amount of rewards: &f" + CReward.getAllRewards().keySet().size()); - ib.setItem(13, paper); - - paper.setDisplayName("&aMessages.YML"); - paper.setLore("").addLore("&6&lChange chat messages").addLore("") - .addLore("&7Amount of messages: &f" + (Messages.values().length - 5)); - ib.setItem(14, paper); - - ib.setItem(16, - new ItemBuilder(XMaterial.CHEST).setDisplayName("&aCrates").setLore("").addLore("&6&lCreate / edit crates") - .addLore("") - .addLore("&7Amount: &f" + Crate.getLoadedCrates().keySet().size()) - .addLore("&7Amount Placed: &f" + PlacedCrate.getPlacedCrates().keySet().size())); - - ItemBuilder sqlYml = new ItemBuilder(XMaterial.PAPER); - sqlYml.setDisplayName("&aSQL.YML"); - sqlYml.addLore("").addLore("&6&lEdit the MySQL database info").addLore("").addLore("&7Amount of values: &f5"); - ib.setItem(20, sqlYml); - - boolean dbStatus = (SQLDataHandler.getSql() == null || !SQLDataHandler.getSql().getConnection().isOpen()); - ItemBuilder sqlStatus = new ItemBuilder(dbStatus ? XMaterial.RED_DYE : XMaterial.GREEN_DYE); - sqlStatus.setDisplayName("&eMySQL Database Status"); - sqlStatus.addLore("").addLore(dbStatus ? "&c&lNot Connected" : "&a&lConnected!"); - sqlStatus.addLore("") - .addAutomaticLore("&f", 30, "If you are not using MYSQL as the data handler, you can ignore this!"); - - ib.setItem(35, sqlStatus); - - ib.open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - switch (slot) { - case 0: - getCc().saveEverything(); - break; - case 9: - reload(); - break; - case 27: - getP().closeInventory(); - break; - case 11: - new IGCMenuConfig(getCc(), getP(), this).open(); - break; - case 12: - new IGCMenuCrateConfig(getCc(), getP(), this).open(); - break; - case 13: - new IGCMenuRewards(getCc(), getP(), this, 1).open(); - break; - case 14: - new IGCMenuMessages(getCc(), getP(), this).open(); - break; - case 16: - new IGCMenuCrates(getCc(), getP(), this).open(); - break; - case 20: - new IGCMenuSQL(getCc(), getP(), this).open(); - break; - } - } - - @Override - public boolean handleInput(String value, String input) { - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/buttons/IGCButton.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/buttons/IGCButton.java deleted file mode 100644 index 60a5029..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/buttons/IGCButton.java +++ /dev/null @@ -1,17 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.buttons; - -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; - -public interface IGCButton { - ItemBuilder getButtonItem(); - - /** - * Handle the click of a button - * - * @return If true, reopen the menu, and false if not to reopen - */ - boolean handleClick(IGCMenu menu); - - Object getValue(); -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/buttons/IGCButtonBack.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/buttons/IGCButtonBack.java deleted file mode 100644 index 977e631..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/buttons/IGCButtonBack.java +++ /dev/null @@ -1,32 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.buttons; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; - -public class IGCButtonBack implements IGCButton { - @Override - public ItemBuilder getButtonItem() { - ItemBuilder button = new ItemBuilder(XMaterial.GRAY_DYE, 1); - button.setDisplayName("&cExit"); - button.addLore("&4&oNOTE: THIS DOES NOT SAVE CHANGES"); - button.addLore(""); - button.addLore("&7Exit or return to the previous menu."); - return button; - } - - @Override - public boolean handleClick(IGCMenu menu) { - if (menu.getLastMenu() == null) { - menu.getP().closeInventory(); - return false; - } - menu.up(); - return false; - } - - @Override - public Object getValue() { - return null; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/buttons/IGCButtonRewardFilter.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/buttons/IGCButtonRewardFilter.java deleted file mode 100644 index da9af79..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/buttons/IGCButtonRewardFilter.java +++ /dev/null @@ -1,33 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.buttons; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.crates.options.CReward; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; - -public class IGCButtonRewardFilter implements IGCButton { - CReward.RewardSortType sortType = CReward.RewardSortType.CREATED_ORDER; - - @Override - public ItemBuilder getButtonItem() { - ItemBuilder button = new ItemBuilder(XMaterial.HOPPER); - button.setDisplayName("&6Sorting the Rewards by"); - button.addLore("&e" + sortType.getNiceName()); - button.addLore(""); - for (String line : sortType.getNiceDescription()) { - button.addLore(line); - } - return button; - } - - @Override - public boolean handleClick(IGCMenu menu) { - sortType = sortType.getNext(); - return true; - } - - @Override - public CReward.RewardSortType getValue() { - return sortType; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/buttons/IGCButtonType.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/buttons/IGCButtonType.java deleted file mode 100644 index 95da04d..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/buttons/IGCButtonType.java +++ /dev/null @@ -1,23 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.buttons; - -public enum IGCButtonType { - SAVE, - BACK, - RELOAD, - SAVE_AND_RELOAD, - REWARD_FILTER; - - public IGCButton createInstance() { - switch (this) { - case SAVE: - case RELOAD: - case SAVE_AND_RELOAD: - break; - case REWARD_FILTER: - return new IGCButtonRewardFilter(); - case BACK: - return new IGCButtonBack(); - } - return null; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateActions.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateActions.java deleted file mode 100644 index 1a59054..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateActions.java +++ /dev/null @@ -1,172 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.crates; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.InventoryUtils; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCListSelector; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.inputmenus.InputMenu; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.inventory.meta.ItemMeta; - -import java.util.Arrays; -import java.util.List; - -/** - * Created by ztowne13 on 4/3/16. - */ -public class IGCCrateActions extends IGCTierMenu { - List actionTypes; - List descriptors; - List builders; - boolean deleteMode = false; - String actionType; - - public IGCCrateActions(SpecializedCrates cc, Player p, IGCMenu lastMenu, Crate crates, String tier) { - super(cc, p, lastMenu, "&7&l> &6&lActions", crates, tier); - actionTypes = Arrays.asList( - "MESSAGE", - "BROADCAST", - "TITLE", - "SUBTITLE", - "ACTIONBAR", - "COMMAND", - "PRE_MESSAGE", - "PRE_BROADCAST", - "PRE_TITLE", - "PRE_SUBTITLE", - "PRE_ACTIONBAR", - "PRE_COMMAND" - ); - - descriptors = Arrays.asList( - "Send a message to the player after the crate animation has been completed.", - "Sends a broadcast to the server after the crate animation has been completed.", - "Displays a title to the player after the crate animation has been completed.", - "Displays a subtitle to the player after the crate animation has been completed.", - "Displays an action bar to the player after the crate animation has been completed.", - "Runs a command in console after the crate animation has been completed. To add per-reward commands, visit the rewards.yml.", - "Send a message to the player immediately when the player begins opening the crate.", - "Sends a broadcast to the server immediately when the player begins opening the crate.", - "Displays a title to the player immediately when the player begins opening the crate.", - "Displays a subtitle to the player immediately when the player begins opening the crate.", - "Displays an action bar to the player immediately when the player begins opening the crate.", - "Runs a command in console immediately when the player begins opening the crate. To add per-reward commands, visit the rewards.yml." - ); - - builders = Arrays.asList( - new ItemBuilder(XMaterial.PAPER), - new ItemBuilder(XMaterial.BEACON), - new ItemBuilder(XMaterial.WRITTEN_BOOK), - new ItemBuilder(XMaterial.BOOK), - new ItemBuilder(XMaterial.IRON_INGOT), - new ItemBuilder(XMaterial.COMMAND_BLOCK), - new ItemBuilder(XMaterial.PAPER), - new ItemBuilder(XMaterial.BEACON), - new ItemBuilder(XMaterial.WRITTEN_BOOK), - new ItemBuilder(XMaterial.BOOK), - new ItemBuilder(XMaterial.IRON_INGOT), - new ItemBuilder(XMaterial.COMMAND_BLOCK) - ); - } - - @Override - public void openMenu() { - - int count = 0; - if (cs.getAction().getActions().containsKey(tier)) { - for (String actionType : cs.getAction().getActions().get(tier).keySet()) { - count += cs.getAction().getActions().get(tier).get(actionType).size(); - } - } - - InventoryBuilder ib = createDefault(InventoryUtils.getRowsFor(4, count) + 9, 18); - - ib.setItem(0, IGCDefaultItems.EXIT_BUTTON.getIb()); - if (!deleteMode) { - getIb().setItem(8, - new ItemBuilder(XMaterial.RED_CARPET).setDisplayName("&aEnable 'delete' mode") - .setLore("&7By enabling 'delete' mode").addLore("&7you can just click on actions") - .addLore("&7to remove ")); - } else { - getIb().setItem(8, - new ItemBuilder(XMaterial.RED_CARPET).setDisplayName("&cDisable 'delete' mode") - .setLore("&7This will stop you from").addLore("&7removing actions")); - } - ib.setItem(17, new ItemBuilder(XMaterial.PAPER).setDisplayName("&aAdd a new action")); - - int i = 2; - if (cs.getAction().getActions().containsKey(tier)) { - for (String actionType : cs.getAction().getActions().get(tier).keySet()) { - for (String actionMSG : cs.getAction().getActions().get(tier).get(actionType)) { - if (i % 9 == 7) { - i += 4; - } - - ib.setItem(i, new ItemBuilder(XMaterial.BOOK).setDisplayName("&a" + actionType).setLore(actionMSG)); - i++; - } - } - } - - ib.open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - if (slot == 0) { - up(); - } else if (slot == 8) { - deleteMode = !deleteMode; - if (!deleteMode) { - getIb().setItem(8, - new ItemBuilder(XMaterial.RED_CARPET).setDisplayName("&aEnable 'delete' mode") - .setLore("&7By enabling 'delete' mode").addLore("&7you can just click on rewards") - .addLore("&7to remove ")); - } else { - getIb().setItem(8, - new ItemBuilder(XMaterial.RED_CARPET).setDisplayName("&cDisable 'delete' mode") - .setLore("&7This will stop you from").addLore("&7removing rewards")); - } - } else if (slot == 17) { -// new InputMenu(getCc(), getP(), "new action - type", "null", "Valid action types: " + actionTypes.toString(), -// String.class, this, true); - new IGCListSelector(getCc(), getP(), this, "Actions", actionTypes, XMaterial.PAPER, 1, descriptors, builders).open(); - } else if (getIb().getInv().getItem(slot) != null && getIb().getInv().getItem(slot).getType().equals(Material.BOOK)) { - if (deleteMode) { - ItemMeta im = getIb().getInv().getItem(slot).getItemMeta(); - cs.getAction().removeEntry(ChatUtils.removeColor(im.getDisplayName()), im.getLore().get(0), tier); - open(); - } - } - } - - @Override - public boolean handleInput(String value, String input) { - if (value.equalsIgnoreCase("Actions")) { - if (actionTypes.contains(input.toUpperCase())) { - actionType = input.toUpperCase(); - new InputMenu(getCc(), getP(), "new action - message", "null", "Placeholders: %name%, %nickname%, %rewards%, %crate%", - String.class, this, false); - - Bukkit.getScheduler().scheduleSyncDelayedTask(getCc(), () -> getP().closeInventory(), 1); - } else { - ChatUtils.msgError(getP(), input + " is not a valid action type: " + actionTypes.toString()); - } - } else if (value.equalsIgnoreCase("new action - message")) { - cs.getAction().addEntry(actionType, input, tier); - ChatUtils.msgSuccess(getP(), - "Added a new action with action type '" + actionType + "' and message '" + input + "'"); - return true; - } - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateAnimation.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateAnimation.java deleted file mode 100644 index 9862613..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateAnimation.java +++ /dev/null @@ -1,91 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.crates; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.types.animations.CrateAnimationType; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCListSelector; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.entity.Player; - -import java.util.Arrays; - -/** - * Created by ztowne13 on 4/2/16. - */ -public class IGCCrateAnimation extends IGCMenuCrate { - - public IGCCrateAnimation(SpecializedCrates cc, Player p, IGCMenu lastMenu, Crate crates) { - super(cc, p, lastMenu, "&7&l> &6&lAnimation Settings", crates); - } - - @Override - public void openMenu() { - - InventoryBuilder ib = createDefault(27); - - ib.setItem(0, IGCDefaultItems.EXIT_BUTTON.getIb()); - - ib.setItem(13, - new ItemBuilder(XMaterial.BIRCH_FENCE_GATE).setDisplayName("&aSet auto-close").setLore("&7Current value: ") - .addLore("&7" + cs.isAutoClose()).addLore("").addAutomaticLore("&f", 30, - "If the crate is in an inventory, should it automatically close when it is done?")); - - ib.setItem(11, new ItemBuilder(XMaterial.ITEM_FRAME).setDisplayName("&aSet the crate animation") - .setLore("&7Current Value: ").addLore("&7" + cs.getCrateType().name()).addLore("") - .addAutomaticLore("&f", 30, "This is the animation that will play when the crate is opened.")); - - ItemBuilder skipAnimation = new ItemBuilder(XMaterial.GUNPOWDER); - skipAnimation.setDisplayName("&aSet allow-skip-animation"); - skipAnimation.addLore("&7Current Value:").addLore("&7" + cs.isCanFastTrack()); - skipAnimation.addLore("").addAutomaticLore("&f", 30, - "Whether or not the player can end the animation at any point while opening the crate."); - - ib.setItem(15, skipAnimation); - - - ib.open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - switch (slot) { - case 0: - up(); - break; - case 13: - cs.setAutoClose(!cs.isAutoClose()); - open(); - break; - case 11: - new IGCListSelector(getCc(), getP(), this, "Animation Type", Arrays.asList(CrateAnimationType.values()), - XMaterial.PAPER, 1, null).open(); - break; - case 15: - cs.setCanFastTrack(!cs.isCanFastTrack()); - open(); - break; - } - } - - @Override - public boolean handleInput(String value, String input) { - if (value.equalsIgnoreCase("Animation Type")) { - try { - CrateAnimationType ct = CrateAnimationType.valueOf(input.toUpperCase()); - cs.setCrateType(ct); - ChatUtils.msgSuccess(getP(), "Set the Animation Type to " + input); - return true; - } catch (Exception exc) { - ChatUtils.msgError(getP(), - input + " is not valid in the list of crate animations: " + Arrays.toString(CrateAnimationType.values())); - } - } - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateFireworks.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateFireworks.java deleted file mode 100644 index c34ecb3..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateFireworks.java +++ /dev/null @@ -1,120 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.crates; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.options.particles.FireworkData; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.InventoryUtils; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.inputmenus.InputMenu; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.entity.Player; - -/** - * Created by ztowne13 on 4/3/16. - */ -public class IGCCrateFireworks extends IGCTierMenu { - boolean deleteMode = false; - - public IGCCrateFireworks(SpecializedCrates cc, Player p, IGCMenu lastMenu, Crate crates, String tier) { - super(cc, p, lastMenu, "&7&l> &6&lFireworks", crates, tier); - } - - @Override - public void openMenu() { - - InventoryBuilder ib = createDefault(InventoryUtils.getRowsFor(4, - (crates.getSettings().getFirework().getFireworks().containsKey(tier) ? cs.getFirework().getFireworks().get(tier).size() : 0)) + - 9, 18); - - ib.setItem(0, IGCDefaultItems.EXIT_BUTTON.getIb()); - ib.setItem(17, new ItemBuilder(XMaterial.PAPER).setDisplayName("&aAdd a new firework") - .setLore("&7Please hold the firework in").addLore("&7your hand. Type 'add' to") - .addLore("&7add a firework and 'done'").addLore("&7to finish editing and return") - .addLore("&7to this menu.")); - - updateDeleteModeItem(); - - if (cs.getFirework().getFireworks().containsKey(tier)) { - int i = 2; - for (FireworkData fd : cs.getFirework().getFireworks().get(tier)) { - if (i % 9 == 7) { - i += 4; - } - - ib.setItem(i, new ItemBuilder(XMaterial.FIREWORK_ROCKET) - .setDisplayName("&6&lFirework ID: &e" + fd.getId()) - .addAutomaticLore("&7", 31, "&aColors: &7" + fd.getColors()) - .addAutomaticLore("&7", 31, "&aFade Colors: &7" + fd.getFadeColors()) - .addLore("&aPower: &7" + fd.getPower()).addLore("&aFlicker: &7" + fd.isFlicker()) - .addLore("&aTrail: &7" + fd.isTrail()).addLore("&aType: &7" + fd.getFeType().name()) - .addLore(fd.getId())); - i++; - } - } - - ib.open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - if (slot == 0) { - up(); - } else if (slot == 8) { - deleteMode = !deleteMode; - updateDeleteModeItem(); - } else if (slot == 17) { - new InputMenu(getCc(), getP(), "add firework", "null", - "Please hold whatever fireworks in your hand you want to add and type 'add'.", - String.class, this, true); - } else if (getIb().getInv().getItem(slot) != null && - XMaterial.FIREWORK_ROCKET.isSimilar(getIb().getInv().getItem(slot))) { - if (deleteMode) { - cs.getFirework().removeFireworks(tier, cs.getFirework().getByItemStack(tier, getIb().getInv().getItem(slot))); - open(); - } - } - } - - @Override - public boolean handleInput(String value, String input) { - if (value.equalsIgnoreCase("add firework")) { - if (input.equalsIgnoreCase("add")) { - if (getP().getItemInHand() != null && - XMaterial.FIREWORK_ROCKET.isSimilar(getP().getItemInHand())) { - FireworkData fd = new FireworkData(getCc(), cs); - boolean result = fd.loadFromFirework(getP().getItemInHand()); - if (!result) { - ChatUtils.msgError(getP(), "You cannot add a firework with no colors."); - return false; - } - - cs.getFirework().addFirework(tier, fd); - ChatUtils.msgSuccess(getP(), - "Added the firework you are holding to the crate. Please type 'add' to add another firework you are holding or 'done' to return to the menu."); - return true; - } else { - ChatUtils.msgError(getP(), "You are not holding a firework!"); - } - } else { - ChatUtils.msgError(getP(), "You can only type 'add' to add a firework and 'done' to return to the menu."); - } - } - return false; - } - - void updateDeleteModeItem() { - ItemBuilder deleteModeItem = new ItemBuilder(XMaterial.RED_CARPET); - if (!deleteMode) { - getIb().setItem(8, deleteModeItem.setDisplayName("&aEnable 'delete' mode").setLore("&7By enabling 'delete' mode") - .addLore("&7you can just click on fireworks").addLore("&7to remove them")); - } else { - getIb().setItem(8, deleteModeItem.setDisplayName("&cDisable 'delete' mode").setLore("&7This will stop you from") - .addLore("&7removing fireworks")); - } - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateHolograms.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateHolograms.java deleted file mode 100644 index 90bca79..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateHolograms.java +++ /dev/null @@ -1,226 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.crates; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.options.CHologram; -import me.ztowne13.customcrates.crates.options.holograms.animations.HoloAnimType; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCListEditor; -import me.ztowne13.customcrates.interfaces.igc.IGCListSelector; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.inputmenus.InputMenu; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.Utils; -import org.bukkit.entity.Player; - -import java.util.Arrays; - -/** - * Created by ztowne13 on 4/2/16. - *

- * 4:32 - */ -public class IGCCrateHolograms extends IGCMenuCrate { - public IGCCrateHolograms(SpecializedCrates cc, Player p, IGCMenu lastMenu, Crate crates) { - super(cc, p, lastMenu, "&7&l> &6&lHolograms", crates); - } - - @Override - public void openMenu() { - - InventoryBuilder ib = createDefault(27); - CHologram cholo = crates.getSettings().getHologram(); - - ib.setItem(0, IGCDefaultItems.EXIT_BUTTON.getIb()); - - // Reward Hologram - String rewardHolo = cholo.getRewardHologram(); - ItemBuilder rewardHologram = new ItemBuilder(XMaterial.LIGHT_BLUE_DYE, 1); - rewardHologram.setDisplayName("&aEdit the reward-hologram"); - rewardHologram.addLore("&7Current value:") - .addLore(ChatUtils.toChatColor(rewardHolo) == "" ? "&7&oNot in use" : rewardHolo).addLore(""); - rewardHologram.addAutomaticLore("&f", 30, - "This is the hologram that appears after someone wins a reward. Type 'none' to remove it. " + - "Use %reward% as a placeholder for the reward name and %player% as a placeholder for the player name."); - ib.setItem(2, rewardHologram); - - //Reward Hologram duration - ItemBuilder rewardHoloDuration = new ItemBuilder(XMaterial.PAPER, 1); - rewardHoloDuration.setDisplayName("&aEdit the reward-hologram duration"); - rewardHoloDuration.addLore("&7Current value:").addLore("&7" + cholo.getRewardHoloDuration()).addLore(""); - rewardHoloDuration.addAutomaticLore("&f", 30, "This is the length, in ticks, the reward hologram will remain up"); - ib.setItem(11, rewardHoloDuration); - - //Reward Hologram yoffset - ItemBuilder rewardHoloYOffset = new ItemBuilder(XMaterial.BLAZE_ROD, 1); - rewardHoloYOffset.setDisplayName("&aEdit the reward-hologram Y-Offset"); - rewardHoloYOffset.addLore("&7Current value:").addLore("&7" + cholo.getRewardHoloYOffset()).addLore(""); - rewardHoloYOffset - .addAutomaticLore("&f", 30, "This is the amount up or down from the crate the REWARD-hologram will appear."); - rewardHoloYOffset.addLore("") - .addAutomaticLore("&e", 30, - "&6&lNOTE: &eTHIS IS FOR THE REWARD HOLOGRAM, NOT THE NORMAL/ANIMATED HOLOGRAM."); - ib.setItem(20, rewardHoloYOffset); - - //Hologram Lines - ItemBuilder hologramLines = new ItemBuilder(XMaterial.BOOK, 1); - hologramLines.setDisplayName("&aEdit the hologram"); - hologramLines.addLore("&7Current value:"); - for (String line : cholo.getLines()) { - hologramLines.addLore(line); - } - hologramLines.addLore("").addAutomaticLore("&f", 30, - "Edit the crate hologram. You DO NOT need to edit this value if using a hologram animation."); - ib.setItem(4, hologramLines); - - // Green block - boolean usingDefault = (cholo.getHoloAnimType() == null || cholo.getHoloAnimType().equals(HoloAnimType.NONE)); - ItemBuilder usingDefaultOrAnimate = new ItemBuilder(usingDefault ? XMaterial.GREEN_WOOL : - XMaterial.RED_WOOL, 1); - usingDefaultOrAnimate.setDisplayName("&aStatus: "); - usingDefaultOrAnimate.addLore(usingDefault ? "&eUsing the normal hologram" : "&eUsing the animated hologram"); - usingDefaultOrAnimate.addLore("").addAutomaticLore("&f", 30, usingDefault ? - "To use animated holograms, change the hologram animation type to something other than NONE." : - "To stop using animated holograms, change the hologram animation type to NONE."); - ib.setItem(9, usingDefaultOrAnimate); - - // Animated Hologram - ItemBuilder animatedHolo = new ItemBuilder(XMaterial.WRITABLE_BOOK, 1); - animatedHolo.setDisplayName("&aEdit the animated hologram frames"); - animatedHolo.addLore("&7Frames: " + cholo.getPrefixes().size()).addLore(""); - animatedHolo.addAutomaticLore("&f", 30, - "Each frame will play, one after the other every (whatever speed you set) ticks.") - .addLore("").addAutomaticLore("&f", 30, - "If there are going to be a lot of frames, editing this in the config file may be quicker."); - ib.setItem(6, animatedHolo); - - // Animated hologram type - ItemBuilder animatedHoloType = new ItemBuilder(XMaterial.BEACON, 1); - animatedHoloType.setDisplayName("&aEdit the hologram animation type"); - animatedHoloType.addLore("&7Current value:").addLore("&7" + cholo.getHoloAnimType().name()).addLore(""); - animatedHoloType.addAutomaticLore("&f", 30, - "Change the hologram animation type (there is currently only 1). Set to NONE to use the default holograms."); - ib.setItem(15, animatedHoloType); - - // Animated hologram speed - ItemBuilder animatedHoloSpeed = new ItemBuilder(XMaterial.SUGAR, 1); - animatedHoloSpeed.setDisplayName("&aEdit the animated hologram speed"); - animatedHoloSpeed.addLore("&7Current value:").addLore("&7" + cholo.getSpeed()).addLore(""); - animatedHoloSpeed.addAutomaticLore("&f", 30, - "This is the delay between frame updates. The lower the value, the faster the frames cycle. A value of 10 is a frame update every second."); - ib.setItem(24, animatedHoloSpeed); - - // Hologram offset - ItemBuilder hologramOffset = new ItemBuilder(XMaterial.BLAZE_ROD, 1); - hologramOffset.setDisplayName("&aEdit the hologram Y-Offset"); - hologramOffset.addLore("&7Current value:").addLore("&7" + cs.getHologramOffset()); - hologramOffset.addLore("").addAutomaticLore("&f", 30, - "This is the amount up or down from the crate that the NORMAL hologram will appear."); - hologramOffset.addLore("").addAutomaticLore("&e", 30, - "This affects the normal AND animated hologram (whichever you're using), but NOT the reward hologram"); - ib.setItem(13, hologramOffset); - - ib.open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - if (slot == 0) { - up(); - } else if (slot == 2) { - new InputMenu(getCc(), getP(), "reward-hologram", crates.getSettings().getHologram().getRewardHologram(), - "Type 'none' to remove the reward hologram. Use %reward% as a placeholder for the reward and " + - "%player% as a placeholder for the player name or %nickname% for the player nickname.", - String.class, - this); - } else if (slot == 11) { - new InputMenu(getCc(), getP(), "reward-hologram-duration", - crates.getSettings().getHologram().getRewardHoloDuration() + "", Integer.class, this); - } else if (slot == 20) { - new InputMenu(getCc(), getP(), "reward-hologram-yoffset", - crates.getSettings().getHologram().getRewardHoloYOffset() + "", Double.class, this); - } else if (slot == 4) { - new IGCListEditor(getCc(), getP(), this, "Hologram Editor", "Line", cs.getHologram().getLines(), - XMaterial.BOOK, - 1).open(); - } else if (slot == 6) { - new IGCListEditor(getCc(), getP(), this, "Animation Editor", "Frame", cs.getHologram().getPrefixes(), - XMaterial.BOOK, - 1).open(); - } else if (slot == 13) { - new InputMenu(getCc(), getP(), "hologram-offset", - crates.getSettings().getHologramOffset() + "", Double.class, this); - } else if (slot == 15) { -// new InputMenu(getCc(), getP(), "hologram.animation.type", crates.getCs().getCholoCopy().getHat().toString(), -// "Animation types: " + Arrays.toString(HoloAnimType.values()), String.class, this, true); - new IGCListSelector(getCc(), getP(), this, "Holo Animation Type", Arrays.asList(HoloAnimType.values()), - XMaterial.PAPER, 1, HoloAnimType.descriptors()).open(); - } else if (slot == 24) { - new InputMenu(getCc(), getP(), "hologram.animation.speed", - crates.getSettings().getHologram().getSpeed() + "", Integer.class, this); - } - } - - @Override - public boolean handleInput(String value, String input) { - if (value.equalsIgnoreCase("reward-hologram")) { - if (input.equalsIgnoreCase("none") || input.equalsIgnoreCase("off") || input.equalsIgnoreCase("null")) { - cs.getHologram().setRewardHologram(""); - return true; - } - cs.getHologram().setRewardHologram(ChatUtils.fromChatColor(input)); - ChatUtils.msgSuccess(getP(), "Set " + value + " to " + input); - return true; - } else if (value.equalsIgnoreCase("reward-hologram-duration")) { - if (Utils.isInt(input)) { - int newDur = Integer.parseInt(input); - cs.getHologram().setRewardHoloDuration(newDur); - ChatUtils.msgSuccess(getP(), "Set " + value + " to " + input); - return true; - } else { - ChatUtils.msgError(getP(), input + " is not a valid whole-number."); - } - } else if (value.equalsIgnoreCase("reward-hologram-yoffset")) { - if (Utils.isDouble(input)) { - double newYOff = Double.parseDouble(input); - cs.getHologram().setRewardHoloYOffset(newYOff); - ChatUtils.msgSuccess(getP(), "Set " + value + " to " + input); - return true; - } else { - ChatUtils.msgError(getP(), input + " is not a valid decimal-number."); - } - } else if (value.equalsIgnoreCase("hologram-offset")) { - if (Utils.isDouble(input)) { - double newYOff = Double.parseDouble(input); - cs.setHologramOffset(newYOff); - ChatUtils.msgSuccess(getP(), "Set " + value + " to " + input); - return true; - } else { - ChatUtils.msgError(getP(), input + " is not a valid decimal-number."); - } - } else if (value.equalsIgnoreCase("Holo Animation Type")) { - try { - HoloAnimType newHoloAnim = HoloAnimType.valueOf(input.toUpperCase()); - cs.getHologram().setHoloAnimType(newHoloAnim); - ChatUtils.msgSuccess(getP(), "Set hologram.animation.type to " + input); - return true; - } catch (Exception exc) { - ChatUtils.msgError(getP(), input + " is not a valid hologram animation type."); - } - } else if (value.equalsIgnoreCase("hologram.animation.speed")) { - if (Utils.isInt(input)) { - int newSpeed = Integer.parseInt(input); - cs.getHologram().setSpeed(newSpeed); - ChatUtils.msgSuccess(getP(), "Set " + value + " to " + input); - return true; - } else { - ChatUtils.msgError(getP(), input + " is not a valid whole-number."); - } - } - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateParticle.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateParticle.java deleted file mode 100644 index 08d6312..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateParticle.java +++ /dev/null @@ -1,296 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.crates; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.options.particles.ParticleData; -import me.ztowne13.customcrates.crates.options.particles.ParticleEffect; -import me.ztowne13.customcrates.crates.options.particles.effects.OffsetTiltedRingsPA; -import me.ztowne13.customcrates.crates.options.particles.effects.PEAnimationType; -import me.ztowne13.customcrates.crates.options.particles.effects.TiltedRingsPA; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCListSelector; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.inputmenus.InputMenu; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.Utils; -import me.ztowne13.customcrates.utils.VersionUtils; -import org.bukkit.entity.Player; - -import java.util.Arrays; - -/** - * Created by ztowne13 on 4/2/16. - */ -public class IGCCrateParticle extends IGCTierMenu { - ParticleData pd; - - String[] colorableParticles = new String[]{ - "SPELL_MOB", - "SPELL_MOB_AMBIENT", - "NOTE", - "REDSTONE" - }; - - public IGCCrateParticle(SpecializedCrates cc, Player p, IGCMenu lastMenu, Crate crates, ParticleData pd, String tier) { - super(cc, p, lastMenu, "&7&l> &6&lParticles", crates, tier); - this.pd = pd; - } - - @Override - public void openMenu() { - InventoryBuilder ib = createDefault(pd.getParticleAnimationEffect() == null ? 36 : 27); - - ib.setItem(0, IGCDefaultItems.EXIT_BUTTON.getIb()); - ib.setItem(8, new ItemBuilder(XMaterial.RED_CARPET).setDisplayName("&cDelete this particle") - .setLore("&7NOTE: This action cannot").addLore("&7be undone!")); - - ib.setItem(10, new ItemBuilder(XMaterial.BEACON).setDisplayName("&aParticle Animation") - .addLore("&7Current value: ") - .addLore("&7" + (pd.getParticleAnimationEffect() == null ? "none" : - PEAnimationType.getFromParticleAnimationEffect(pd.getParticleAnimationEffect()).name())).addLore("") - .addAutomaticLore("&f", 30, - "&fThe animation type of the particle. Set this value to 'none' to have no animation.")); - ib.setItem(11, new ItemBuilder(XMaterial.NETHER_STAR).setDisplayName("&aParticle Type").setLore("&7Current value: ") - .addLore("&7" + pd.getParticleName()).addLore("") - .addAutomaticLore("&f", 30, "The particle type that this particle will display.")); - - ItemBuilder colorEditor = new ItemBuilder(XMaterial.LIME_DYE, 1); - colorEditor.setDisplayName("&aEdit the color of the particle"); - - for (String s : colorableParticles) - if (s.equalsIgnoreCase(pd.getParticleName())) - ib.setItem(20, colorEditor); - - if (pd.getParticleAnimationEffect() == null) { - ib.setItem(12, - new ItemBuilder(XMaterial.BLAZE_ROD).setDisplayName("&aX Range") - .addLore("&7Current value: ") - .addLore("&7" + pd.getRangeX()).addLore("") - .addAutomaticLore("&f", 30, "Range particles will spawn in the X direction.")); - ib.setItem(13, - new ItemBuilder(XMaterial.BLAZE_ROD).setDisplayName("&aY Range") - .addLore("&7Current value: ") - .addLore("&7" + pd.getRangeY()).addLore("") - .addAutomaticLore("&f", 30, "Range particles will spawn in the Y direction.")); - ib.setItem(14, - new ItemBuilder(XMaterial.BLAZE_ROD).setDisplayName("&aZ Range") - .addLore("&7Current value: ") - .addLore("&7" + pd.getRangeZ()).addLore("") - .addAutomaticLore("&f", 30, "Range particles will spawn in the Z direction.")); - ib.setItem(15, new ItemBuilder(XMaterial.SUGAR).setDisplayName("&aParticle speed").setLore("&7Current value: ") - .addLore("&7" + pd.getSpeed()).addLore("").addAutomaticLore("&f", 30, - "The speed the particles will move around at. For some particles, this changes their color.")); - ib.setItem(16, new ItemBuilder(XMaterial.BUCKET).setDisplayName("&aParticle amount").setLore("&7Current value: ") - .addLore("&7" + pd.getAmount()).addLore("") - .addAutomaticLore("&f", 30, "The amount of particles that will be displayed every tick.")); - - ItemBuilder xCenter = new ItemBuilder(XMaterial.BLAZE_POWDER); - xCenter.setDisplayName("&aCenter Offset X"); - xCenter.addLore("&7Current Value:"); - xCenter.addLore("&7" + pd.getCenterX()); - xCenter.addLore(""); - xCenter.addAutomaticLore("&f", 30, - "The x offset for the middle of where all the particles will spawn. This is useful if the particles spawn in a compact area and that area is off-centered."); - - ItemBuilder yCenter = new ItemBuilder(XMaterial.BLAZE_POWDER); - yCenter.setDisplayName("&aCenter Offset Y"); - yCenter.addLore("&7Current Value:"); - yCenter.addLore("&7" + pd.getCenterY()); - yCenter.addLore(""); - yCenter.addAutomaticLore("&f", 30, - "The y offset for the middle of where all the particles will spawn. This is useful if the particles spawn in a compact area and that area is off-centered."); - - ItemBuilder zCenter = new ItemBuilder(XMaterial.BLAZE_POWDER); - zCenter.setDisplayName("&aCenter Offset Z"); - zCenter.addLore("&7Current Value:"); - zCenter.addLore("&7" + pd.getCenterZ()); - zCenter.addLore(""); - zCenter.addAutomaticLore("&f", 30, - "The z offset for the middle of where all the particles will spawn. This is useful if the particles spawn in a compact area and that area is off-centered."); - - - getIb().setItem(21, xCenter); - getIb().setItem(22, yCenter); - getIb().setItem(23, zCenter); - - } else { - ib.setItem(12, - new ItemBuilder(XMaterial.BLAZE_ROD).setDisplayName("&aRadius") - .addAutomaticLore("&f", 30, - "What radius (how 'large') the effect will have. Ideally should be around 1-2.") - .addLore("") - .addLore("&7Current value: ") - .addLore("&7" + pd.getRangeX())); - ib.setItem(13, - new ItemBuilder(XMaterial.BLAZE_ROD).setDisplayName("&aY Offset") - .addAutomaticLore("&f", 30, - "The Y-Offset to center the animation on. Negative numbers make it go down, positive numbers make it go up. Decimals are OK.") - .addLore("") - .addLore("&7Current value: ") - .addLore("&7" + pd.getRangeY())); - - if (pd.getParticleAnimationEffect() instanceof TiltedRingsPA || - pd.getParticleAnimationEffect() instanceof OffsetTiltedRingsPA) { - ib.setItem(14, - new ItemBuilder(XMaterial.BLAZE_ROD).setDisplayName("&aRotation") - .addAutomaticLore("&f", 30, - "The rotation (in degrees) of the animation. This helps if the animation is playing sideways. Setting it to 90 will rotate it a quarter turn.") - .addLore("").addLore("&7Current value: ") - .addLore("&7" + pd.getRangeZ())); - } else { - ib.setItem(14, - new ItemBuilder(XMaterial.BLAZE_ROD).setDisplayName("&aHeight") - .addAutomaticLore("&f", 30, - "How high up and down the animation will go. A value of 1 to 3 will keep it around the crate.") - .addLore("").addLore("&7Current value: ") - .addLore("&7" + pd.getRangeZ())); - } - - ib.setItem(15, new ItemBuilder(XMaterial.SUGAR).setDisplayName("&aAnimation Speed") - .addAutomaticLore("&f", 30, "The speed of the animation. A value of 20 is a fairly reasonable speed.") - .addLore("").addLore("&7Current value: ").addLore("&7" + pd.getSpeed())); - ib.setItem(16, new ItemBuilder(XMaterial.BUCKET).setDisplayName("&aParticle amount") - .addAutomaticLore("&f", 30, - "The amount of particles per animation tick. A value of 3 will create a full/filled looking animation.") - .addLore("").addLore("&7Current value: ") - .addLore("&7" + pd.getAmount())); - } - - ib.open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - switch (slot) { - case 8: - cs.getParticle().deleteParticle(tier, pd); - up(); - break; - case 0: - up(); - break; - case 10: - new IGCListSelector(getCc(), getP(), this, "Particle Animation", Arrays.asList(PEAnimationType.values()), - XMaterial.BEACON, 1, null).open(); - break; - case 11: - if (VersionUtils.Version.v1_9.isServerVersionOrEarlier()) - new IGCListSelector(getCc(), getP(), this, "Particle Type", Arrays.asList(ParticleEffect.values()), - XMaterial.NETHER_STAR, 1, null).open(); - else - new IGCListSelector(getCc(), getP(), this, "Particle Type", Arrays.asList(org.bukkit.Particle.values()), - XMaterial.NETHER_STAR, 1, null).open(); - break; - case 12: - new InputMenu(getCc(), getP(), "x range", pd.getRangeX() + "", - "Distance particles will spawn in the x direction relative to the crate.", Double.class, this); - break; - case 13: - new InputMenu(getCc(), getP(), "y range", pd.getRangeY() + "", - "Distance particles will spawn in the y direction relative to the crate.", Double.class, this); - break; - case 14: - new InputMenu(getCc(), getP(), "z range", pd.getRangeZ() + "", - "Distance particles will spawn in the z direction relative to the crate.", Double.class, this); - break; - case 15: - new InputMenu(getCc(), getP(), "speed", pd.getSpeed() + "", - "Changes the speed of most of the particles. For some, like music notes, it changes the color.", - Double.class, this); - break; - case 16: - new InputMenu(getCc(), getP(), "amount", pd.getAmount() + "", - "How many particles spawn every tick (1/20th of a second).", Integer.class, this); - break; - case 20: - for (String s : colorableParticles) - if (s.equalsIgnoreCase(pd.getParticleName())) - new IGCCrateParticleColor(getCc(), getP(), this, getCrates(), pd, tier).open(); - break; - case 21: - if (pd.getParticleAnimationEffect() == null) - new InputMenu(getCc(), getP(), "x center offset", pd.getCenterX() + "", - "Adjust the center of where the particles will spawn in the x direction.", Double.class, this); - break; - case 22: - if (pd.getParticleAnimationEffect() == null) - new InputMenu(getCc(), getP(), "y center offset", pd.getCenterY() + "", - "Adjust the center of where the particles will spawn in the y direction.", Double.class, this); - break; - case 23: - if (pd.getParticleAnimationEffect() == null) - new InputMenu(getCc(), getP(), "z center offset", pd.getCenterZ() + "", - "Adjust the center of where the particles will spawn in the z direction.", Double.class, this); - break; - } - } - - @Override - public boolean handleInput(String value, String input) { - if (value.equalsIgnoreCase("amount")) { - if (Utils.isInt(input)) { - pd.setAmount(Integer.parseInt(input)); - ChatUtils.msgSuccess(getP(), "Set " + value + " to " + input + "."); - return true; - } else { - ChatUtils.msgError(getP(), input + " is not a valid integer (number)."); - } - } else if (value.equalsIgnoreCase("Particle Type")) { - if (pd.setParticle(input)) { - ChatUtils.msgSuccess(getP(), "Set " + value + " to " + input + "."); - return true; - } else { - ChatUtils.msgError(getP(), - input + " is not valid from the list of particles: " + Arrays.toString(ParticleEffect.values())); - } - } else if (value.equalsIgnoreCase("Particle Animation")) { - try { - if (input.equalsIgnoreCase("none")) { - pd.setParticleAnimationEffect(null); - ChatUtils.msgSuccess(getP(), "Set " + value + " to " + input + "."); - return true; - } else { - PEAnimationType peAnimationType = PEAnimationType.valueOf(input.toUpperCase()); - pd.setParticleAnimationEffect(peAnimationType.getAnimationEffectInstance(getCc(), pd)); - pd.setHasAnimation(true); - ChatUtils.msgSuccess(getP(), "Set " + value + " to " + input + "."); - return true; - } - } catch (Exception exc) { - ChatUtils.msgError(getP(), - input + " is not valid from the list of animations: " + Arrays.toString(PEAnimationType.values())); - return false; - } - } else if (getInputMenu().getType() == Double.class) { - if (Utils.isDouble(input)) { - Float parsedIn = Float.valueOf(input); - if (value.equalsIgnoreCase("x range")) { - pd.setRangeX(parsedIn); - } else if (value.equalsIgnoreCase("y range")) { - pd.setRangeY(parsedIn); - } else if (value.equalsIgnoreCase("z range")) { - pd.setRangeZ(parsedIn); - } else if (value.equalsIgnoreCase("x center offset")) { - pd.setCenterX(parsedIn); - } else if (value.equalsIgnoreCase("y center offset")) { - pd.setCenterY(parsedIn); - } else if (value.equalsIgnoreCase("z center offset")) { - pd.setCenterZ(parsedIn); - } else if (value.equalsIgnoreCase("speed")) { - pd.setSpeed(parsedIn); - } - ChatUtils.msgSuccess(getP(), "Set " + value + " to " + input + "."); - return true; - } else { - ChatUtils.msgError(getP(), input + " is not a valid double (number)."); - } - } - return false; - } - - -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateParticleColor.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateParticleColor.java deleted file mode 100644 index d6c7fd1..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateParticleColor.java +++ /dev/null @@ -1,117 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.crates; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.options.particles.ParticleData; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.inputmenus.InputMenu; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.entity.Player; - -public class IGCCrateParticleColor extends IGCTierMenu { - ParticleData particleData; - - public IGCCrateParticleColor(SpecializedCrates cc, Player p, IGCMenu lastMenu, Crate crates, ParticleData particleData, String tier) { - super(cc, p, lastMenu, "&7&l> &6&lSound", crates, tier); - this.particleData = particleData; - } - - @Override - public void openMenu() { - - InventoryBuilder ib = createDefault(27); - - ib.setItem(9, IGCDefaultItems.EXIT_BUTTON.getIb()); - - ItemBuilder red = new ItemBuilder(XMaterial.RED_DYE, 1); - red.setDisplayName("&cEdit the RED of RGB"); - red.addLore("").addLore("&7Current value: ").addLore("&f" + particleData.getColorRed()); - - ItemBuilder green = new ItemBuilder(XMaterial.LIME_DYE, 1); - green.setDisplayName("&aEdit the GREEN of RGB"); - green.addLore("").addLore("&7Current value: ").addLore("&f" + particleData.getColorGreen()); - - ItemBuilder blue = new ItemBuilder(XMaterial.LIGHT_BLUE_DYE, 1); - blue.setDisplayName("&bEdit the BLUE of RGB"); - blue.addLore("").addLore("&7Current value: ").addLore("&f" + particleData.getColorBlue()); - - ItemBuilder size = new ItemBuilder(XMaterial.PAPER, 1); - size.setDisplayName("&aEdit the SIZE of the redstone dust"); - size.addLore("").addLore("&7Current value: ").addLore("&f" + particleData.getSize()); - - ItemBuilder colorEnabled = new ItemBuilder(particleData.isColorEnabled() ? XMaterial.LIME_WOOL : XMaterial.RED_WOOL, 1); - colorEnabled.setDisplayName("&aEdit if color is enabled"); - colorEnabled.addLore("&7Current value: ").addLore("&f" + particleData.isColorEnabled()); - colorEnabled.addLore("").addAutomaticLore("&7", 30, "If this is enabled, the particle will" + - " be the color specified. If it is disabled, it will simply use the default minecraft particle, whether that's" + - " rainbow or just black. This will ALWAYS be enabled if using the REDSTONE particle."); - - ib.setItem(11, colorEnabled); - ib.setItem(12, red); - ib.setItem(13, green); - ib.setItem(14, blue); - - if (particleData.getParticleName().equalsIgnoreCase("REDSTONE")) - ib.setItem(16, size); - - ib.open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - switch (slot) { - case 9: - up(); - break; - case 12: - new InputMenu(getCc(), getP(), "red", particleData.getColorRed() + "", - "The RED of RGB.", Float.class, this); - break; - case 13: - new InputMenu(getCc(), getP(), "green", particleData.getColorGreen() + "", - "The GREEN of RGB.", Float.class, this); - break; - case 14: - new InputMenu(getCc(), getP(), "blue", particleData.getColorBlue() + "", - "The BLUE of RGB.", Float.class, this); - break; - case 11: - particleData.setColorEnabled(!particleData.isColorEnabled()); - open(); - break; - case 16: - if (particleData.getParticleName().equalsIgnoreCase("REDSTONE")) - new InputMenu(getCc(), getP(), "size", particleData.getSize() + "", - "The size of the redstone.", Float.class, this); - break; - } - } - - @Override - public boolean handleInput(String value, String input) { - int inputAsFloat; - try { - inputAsFloat = Integer.parseInt(input); - } catch (Exception exc) { - ChatUtils.msgError(getP(), input + " is not a valid number."); - return false; - } - - if (value.equalsIgnoreCase("red")) - particleData.setColorRed(inputAsFloat); - else if (value.equalsIgnoreCase("green")) - particleData.setColorGreen(inputAsFloat); - else if (value.equalsIgnoreCase("blue")) - particleData.setColorBlue(inputAsFloat); - else if (value.equalsIgnoreCase("size")) - particleData.setSize(inputAsFloat); - - ChatUtils.msgSuccess(getP(), "Successfully set " + value + " to " + input + "."); - return true; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateParticles.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateParticles.java deleted file mode 100644 index a1a7398..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateParticles.java +++ /dev/null @@ -1,174 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.crates; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.options.particles.BukkitParticleEffect; -import me.ztowne13.customcrates.crates.options.particles.NMSParticleEffect; -import me.ztowne13.customcrates.crates.options.particles.ParticleData; -import me.ztowne13.customcrates.crates.options.particles.ParticleEffect; -import me.ztowne13.customcrates.crates.options.particles.effects.PEAnimationType; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.InventoryUtils; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCListSelector; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.inputmenus.InputMenu; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.Utils; -import me.ztowne13.customcrates.utils.VersionUtils; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.entity.Player; - -import java.util.Arrays; -import java.util.HashMap; -import java.util.UUID; - -/** - * Created by ztowne13 on 4/2/16. - */ -public class IGCCrateParticles extends IGCTierMenu { - HashMap slots = new HashMap(); - ParticleData pd; - - public IGCCrateParticles(SpecializedCrates cc, Player p, IGCMenu lastMenu, Crate crates, String tier) { - super(cc, p, lastMenu, "&7&l> &6&lParticles", crates, tier); - } - - @Override - public void openMenu() { - - InventoryBuilder ib = createDefault(InventoryUtils.getRowsFor(4, - (crates.getSettings().getParticle().getParticles().containsKey(tier) ? - crates.getSettings().getParticle().getParticles().get(tier).size() : 0) + 9)); - - ib.setItem(9, IGCDefaultItems.EXIT_BUTTON.getIb()); - ib.setItem(8, - new ItemBuilder(XMaterial.PAPER).setDisplayName("&aCreate a new particle").setLore("&7Make sure you save") - .addLore("&7when you're done.")); - - if (crates.getSettings().getParticle().getParticles().containsKey(tier)) { - int i = 2; - for (ParticleData pd : crates.getSettings().getParticle().getParticles().get(tier)) { - if (i % 9 == 7) { - i += 4; - } - - slots.put(i, pd); - ib.setItem(i, new ItemBuilder(XMaterial.NETHER_STAR).setDisplayName("&a" + pd.getParticleName()). - setLore("&7X Range: &f" + pd.getRangeX()).addLore("&7Y Range:&f " + pd.getRangeY()) - .addLore("&7Z Range:&f " + pd.getRangeZ()) - . - addLore("&7Speed: &f" + pd.getSpeed()).addLore("&7Amount:&f " + pd.getAmount()). - addLore("&7Animation: &f" + (pd.getParticleAnimationEffect() == null ? "none" : - PEAnimationType.getFromParticleAnimationEffect(pd.getParticleAnimationEffect()) - .name())).addLore("&7X Center:&f " + pd.getCenterX()) - .addLore("&7Y Center:&f " + pd.getCenterY()).addLore("&7Z Center:&f " + pd.getCenterZ())); - i++; - } - } - - ib.open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - if (slot == 9) { - up(); - } else if (slot == 8) { - if (VersionUtils.Version.v1_9.isServerVersionOrEarlier()) - new IGCListSelector(getCc(), getP(), this, "particle type", Arrays.asList(ParticleEffect.values()), - XMaterial.NETHER_STAR, 1, null).open(); - else - new IGCListSelector(getCc(), getP(), this, "particle type", Arrays.asList(org.bukkit.Particle.values()), - XMaterial.NETHER_STAR, 1, null).open(); - } else if (getIb().getInv().getItem(slot) != null && - getIb().getInv().getItem(slot).getType().equals(Material.NETHER_STAR)) { - ParticleData pd = slots.get(slot); - new IGCCrateParticle(getCc(), getP(), this, crates, pd, tier).open(); - } - } - - @Override - public boolean handleInput(String value, String input) { - if (value.equalsIgnoreCase("particle type")) { - try { - String newName = UUID.randomUUID().getLeastSignificantBits() + ""; - - if (VersionUtils.Version.v1_7.isServerVersionOrLater() && VersionUtils.Version.v1_8.isServerVersionOrEarlier()) { - ParticleEffect pe = ParticleEffect.valueOf(input.toUpperCase()); - pd = new NMSParticleEffect(getCc(), pe, newName, false); - } else { - pd = new BukkitParticleEffect(getCc(), input.toUpperCase(), newName, false); - } - - - /*ParticleEffect pe = ParticleEffect.valueOf(input.toUpperCase()); - pd = new ParticleData(pe);*/ - Bukkit.getScheduler().scheduleSyncDelayedTask(getCc(), new Runnable() { - @Override - public void run() { - getP().closeInventory(); - } - }, 1); - - new InputMenu(getCc(), getP(), "X offset", "null", - "How far the particles can spawn, in the X direction, from the crate.", Double.class, this); - - return true; - } catch (Exception exc) { - ChatUtils.msgError(getP(), - input + " is not valid from the list of particles: " + Arrays.toString(ParticleEffect.values())); - } - } else if (value.equalsIgnoreCase("x offset")) { - if (Utils.isDouble(input)) { - pd.setRangeX(Float.valueOf(input)); - new InputMenu(getCc(), getP(), "Y offset", "null", - "How far the particles can spawn, in the Y direction, from the crate.", Double.class, this); - } else { - ChatUtils.msgError(getP(), input + " is not a valid double (number) value."); - } - } else if (value.equalsIgnoreCase("y offset")) { - if (Utils.isDouble(input)) { - pd.setRangeY(Float.valueOf(input)); - new InputMenu(getCc(), getP(), "Z offset", "null", - "How far the particles can spawn, in the Z direction, from the crate.", Double.class, this); - } else { - ChatUtils.msgError(getP(), input + " is not a valid double (number) value."); - } - } else if (value.equalsIgnoreCase("z offset")) { - if (Utils.isDouble(input)) { - pd.setRangeZ(Float.valueOf(input)); - new InputMenu(getCc(), getP(), "speed", "null", - "Changes the speed of most of the particles. For some, like music notes, it changes the color.", - Double.class, this); - } else { - ChatUtils.msgError(getP(), input + " is not a valid double (number) value."); - } - } else if (value.equalsIgnoreCase("speed")) { - if (Utils.isDouble(input)) { - pd.setSpeed(Float.valueOf(input)); - new InputMenu(getCc(), getP(), "amount", "null", "How many particles spawn every tick (1/20th of a second).", - Integer.class, this); - } else { - ChatUtils.msgError(getP(), input + " is not a valid double (number) value."); - } - } else if (value.equalsIgnoreCase("amount")) { - if (Utils.isInt(input)) { - pd.setAmount(Integer.valueOf(input)); - pd.save(cs.getFileHandler(), cs.getParticle().getPath(tier)); - - cs.getParticle().addParticle(pd, tier); - - ChatUtils.msgSuccess(getP(), "Successfully set all particle values."); - new IGCCrateParticle(getCc(), getP(), this, crates, pd, tier).open(); - } else { - ChatUtils.msgError(getP(), input + " is not a valid integer (number) value."); - } - } - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateRewards.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateRewards.java deleted file mode 100644 index 1d096b6..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateRewards.java +++ /dev/null @@ -1,148 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.crates; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.InventoryUtils; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.fileconfigs.rewards.IGCMenuAddReward; -import me.ztowne13.customcrates.interfaces.igc.fileconfigs.rewards.IGCMenuRewards; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.entity.Player; - -/** - * Created by ztowne13 on 4/3/16. - */ -public class IGCCrateRewards extends IGCMenuCrate { - boolean deleteMode = false; - int page; - - public IGCCrateRewards(SpecializedCrates cc, Player p, IGCMenu lastMenu, Crate crates, int page) { - super(cc, p, lastMenu, "&7&l> &6&lRewards PG" + page, crates); - this.page = page; - } - - @Override - public void openMenu() { - setInventoryName("&7&l> &6&lReward PG" + page); - - int slots = 0; - - if (cs.getReward().getCrateRewards() != null) { - if (cs.getReward().getCrateRewards().length - ((page - 1) * 30) > 30) { - slots = 54; - } else { - slots = InventoryUtils.getRowsFor(4, cs.getReward().getCrateRewards().length - ((page - 1) * 30)); - } - } - if (slots < 27) { - slots = 27; - } else if (slots > 54) { - slots = 54; - } - - InventoryBuilder ib = createDefault(slots); - - ib.setItem(0, IGCDefaultItems.EXIT_BUTTON.getIb()); - if (!deleteMode) { - getIb().setItem(8, new ItemBuilder(XMaterial.RED_CARPET).setDisplayName("&aEnable 'remove' mode") - .setLore("&7By enabling 'remove' mode").addLore("&7you can just click on rewards") - .addLore("&7to remove ")); - } else { - getIb().setItem(8, new ItemBuilder(XMaterial.RED_CARPET).setDisplayName("&cDisable 'remove' mode") - .setLore("&7This will stop you from").addLore("&7removing rewards")); - } - ib.setItem(17, new ItemBuilder(XMaterial.PAPER).setDisplayName("&aAdd a reward to this crate") - .setLore("&7Reminder: you must save for").addLore("&7any changes to take effect.")); - ib.setItem(26, new ItemBuilder(XMaterial.LIGHT_BLUE_DYE).setDisplayName("&aGo to the reward editor") - .setLore("&7This is a shortcut to the reward").addLore("&7menu so you can create rewards") - .addLore("&7without jumping around the menus.")); - - int toSkip = ((page - 1) * 30); - int skipped = 0; - int displayedRewards = 0; - - if (cs.getReward().getCrateRewards() != null && cs.getReward().getCrateRewards().length != 0) { - int i = 2; - for (Reward r : crates.getSettings().getReward().getCrateRewards()) { - if (toSkip > skipped || displayedRewards >= 30) { - skipped++; - continue; - } - - if (i % 9 == 7) { - i += 4; - } - - ib.setItem(i, new ItemBuilder(r.getDisplayBuilder()).setDisplayName("&a" + r.getRewardName()) - .setLore("&7- " + r.getDisplayName(true)).addLore("&7- " + r.getChance()) - .addLore("&7- " + r.getRarity())); - i++; - displayedRewards++; - } - - if (page != 1) { - ib.setItem(9, new ItemBuilder(XMaterial.ARROW).setDisplayName("&aGo up a page")); - } - - if ((cs.getReward().getCrateRewards().length / 30) + 1 != page) { - ib.setItem(18, new ItemBuilder(XMaterial.ARROW).setDisplayName("&aGo down a page")); - } - - } - ib.open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - if (getIb().getInv().getItem(slot) == null) - return; - - if (slot == 0) { - up(); - } else if (slot == 9) { - page--; - open(); - } else if (slot == 18) { - page++; - open(); - } else if (slot == 8) { - deleteMode = !deleteMode; - if (!deleteMode) { - getIb().setItem(8, new ItemBuilder(XMaterial.RED_CARPET).setDisplayName("&aEnable 'remove' mode") - .setLore("&7By enabling 'remove' mode").addLore("&7you can just click on rewards") - .addLore("&7to remove ")); - } else { - getIb().setItem(8, new ItemBuilder(XMaterial.RED_CARPET).setDisplayName("&cDisable 'remove' mode") - .setLore("&7This will stop you from").addLore("&7removing rewards")); - } - } else if (slot == 17) { - new IGCMenuAddReward(getCc(), getP(), this, crates, 1).open(); - } else if (slot == 26) { - new IGCMenuRewards(getCc(), getP(), this, 1).open(); - } else if (getIb().getInv().getItem(slot) != null) { - if (deleteMode) { - String rName = ChatUtils.removeColor(getIb().getInv().getItem(slot).getItemMeta().getDisplayName()); - cs.getReward().removeReward(rName); - open(); - } - } - } - - @Override - public boolean handleInput(String value, String input) { - if (value.equalsIgnoreCase("add reward")) { - if (cs.getReward().addReward(input)) { - ChatUtils.msgSuccess(getP(), "Added the reward " + input); - return true; - } - ChatUtils.msgError(getP(), input + " is not an existing reward OR is not fully/properly configured."); - } - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateSound.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateSound.java deleted file mode 100644 index ef1a267..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateSound.java +++ /dev/null @@ -1,118 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.crates; - -import com.cryptomorin.xseries.XMaterial; -import com.cryptomorin.xseries.XSound; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.options.sounds.SoundData; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.inputmenus.InputMenu; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.Utils; -import org.bukkit.entity.Player; - -import java.util.Optional; - -/** - * Created by ztowne13 on 4/2/16. - */ -public class IGCCrateSound extends IGCTierMenu { - SoundData sd; - - public IGCCrateSound(SpecializedCrates cc, Player p, IGCMenu lastMenu, Crate crates, SoundData sd, String tier) { - super(cc, p, lastMenu, "&7&l> &6&lSound", crates, tier); - this.sd = sd; - } - - @Override - public void openMenu() { - - InventoryBuilder ib = createDefault(27); - - ib.setItem(9, IGCDefaultItems.EXIT_BUTTON.getIb()); - ib.setItem(8, new ItemBuilder(XMaterial.RED_CARPET).setDisplayName("&cDelete this sound") - .addAutomaticLore("&7", 30, "NOTE: This action cannot be undone!")); - - ib.setItem(11, new ItemBuilder(XMaterial.NOTE_BLOCK).setDisplayName("&aSound type").setLore("&7Current value: ") - .addLore("&7" + sd.getSound().name()).addLore("").addAutomaticLore("&f", 30, - "Set the 'type' of the sound. The values for this can be found online. An example would be AMBIENT_CAVE")); - ib.setItem(13, new ItemBuilder(XMaterial.STONE_BUTTON).setDisplayName("&aSound pitch").setLore("&7Current value: ") - .addLore("&7" + sd.getPitch()).addLore("").addAutomaticLore("&f", 30, - "This is the pitch that the sound will play at. 5 is a good normal-sounding pitch.")); - ib.setItem(15, new ItemBuilder(XMaterial.LEVER).setDisplayName("&aSound volume").setLore("&7Current value: ") - .addLore("&7" + sd.getVolume()).addLore("") - .addAutomaticLore("&f", 30, "This is the volume that the sound will play at. 5 is a good 'normal' volume.")); - - ItemBuilder testSound = new ItemBuilder(XMaterial.MUSIC_DISC_13); - testSound.setDisplayName("&aPreview the sound"); - testSound.addLore("") - .addAutomaticLore("&f", 30, "Clicking this will play exactly what the sound is like when it is used!"); - ib.setItem(26, testSound); - - - ib.open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - switch (slot) { - case 8: - cs.getSound().getSounds().get(tier).remove(sd); - case 9: - up(); - break; - case 11: - new InputMenu(getCc(), getP(), "sound type", sd.getSound().name(), - "Click for a list of sounds -> https://www.spigotmc.org/wiki/cc-sounds-list/", String.class, this, - true); - break; - case 13: - new InputMenu(getCc(), getP(), "sound pitch", sd.getSound().name(), "Change the pitch of the sound.", - Integer.class, this); - break; - case 15: - new InputMenu(getCc(), getP(), "sound volume", sd.getSound().name(), "Change the volume of the sound.", - Integer.class, this); - break; - case 26: - sd.playTo(getP(), getP().getLocation()); - break; - } - } - - @Override - public boolean handleInput(String value, String input) { - if (value.equalsIgnoreCase("sound type")) { - Optional optional = XSound.matchXSound(input); - if (optional.isPresent()) { - sd.setSound(optional.get()); - ChatUtils.msgSuccess(getP(), "Set " + value + " to " + input + "."); - return true; - } else { - ChatUtils.msgError(getP(), input + - " is not a valid sound. Click for a list of sounds -> https://www.spigotmc.org/wiki/cc-sounds-list/"); - } - } else if (value.equalsIgnoreCase("sound pitch")) { - if (Utils.isInt(input)) { - sd.setPitch(Integer.parseInt(input)); - ChatUtils.msgSuccess(getP(), "Set " + value + " to " + input + "."); - return true; - } else { - ChatUtils.msgError(getP(), input + " is not a valid integer (number). Make sure it has no decimals."); - } - } else if (value.equalsIgnoreCase("sound volume")) { - if (Utils.isInt(input)) { - sd.setVolume(Integer.parseInt(input)); - ChatUtils.msgSuccess(getP(), "Set " + value + " to " + input + "."); - return true; - } else { - ChatUtils.msgError(getP(), input + " is not a valid integer (number). Make sure it has no decimals."); - } - } - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateSounds.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateSounds.java deleted file mode 100644 index f9bec6b..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCrateSounds.java +++ /dev/null @@ -1,108 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.crates; - -import com.cryptomorin.xseries.XMaterial; -import com.cryptomorin.xseries.XSound; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.options.sounds.SoundData; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.InventoryUtils; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.inputmenus.InputMenu; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.Utils; -import org.bukkit.entity.Player; - -import java.util.HashMap; -import java.util.Optional; - -/** - * Created by ztowne13 on 4/2/16. - */ -public class IGCCrateSounds extends IGCTierMenu { - HashMap slots = new HashMap<>(); - SoundData sd; - - public IGCCrateSounds(SpecializedCrates cc, Player p, IGCMenu lastMenu, Crate crates, String tier) { - super(cc, p, lastMenu, "&7&l> &6&lSounds", crates, tier); - } - - @Override - public void openMenu() { - InventoryBuilder ib = createDefault(InventoryUtils.getRowsFor(4, - (crates.getSettings().getSound().getSounds().containsKey(tier) ? crates.getSettings().getSound().getSounds().get(tier).size() : - 0) + 9)); - - ib.setItem(9, IGCDefaultItems.EXIT_BUTTON.getIb()); - ib.setItem(8, new ItemBuilder(XMaterial.PAPER).setDisplayName("&aCreate a new sound").setLore("&7Make sure you save") - .addLore("&7when you're done.")); - - if (crates.getSettings().getSound().getSounds().containsKey(tier)) { - int i = 2; - for (SoundData sd : crates.getSettings().getSound().getSounds().get(tier)) { - if (i % 9 == 7) { - i += 4; - } - - ib.setItem(i, new ItemBuilder(XMaterial.NOTE_BLOCK).setDisplayName("&a" + sd.getSound().name()) - .setLore("&7Pitch: &f" + sd.getPitch()).addLore("&7Volume: &f" + sd.getVolume())); - slots.put(i, sd); - i++; - } - } - - ib.open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - if (slot == 9) { - up(); - } else if (slot == 8) { - new InputMenu(getCc(), getP(), "sound type", "null", - "Click for a list of sounds -> https://www.spigotmc.org/wiki/cc-sounds-list/", String.class, this, true); - } else if (getIb().getInv().getItem(slot) != null && XMaterial.NOTE_BLOCK.isSimilar(getIb().getInv().getItem(slot))) { - //SoundData sd = crates.getCs().getCs().getSoundFromName(tier, Sound.valueOf(ChatUtils.removeColor(getIb().getInv().getItem(slot).getItemMeta().getDisplayName()).toUpperCase())); - SoundData sd = slots.get(slot); - new IGCCrateSound(getCc(), getP(), this, crates, sd, tier).open(); - } - } - - @Override - public boolean handleInput(String value, String input) { - if (value.equalsIgnoreCase("sound type")) { - Optional optional = XSound.matchXSound(input); - if (optional.isPresent()) { - sd = new SoundData(optional.get()); - new InputMenu(getCc(), getP(), "sound pitch", "null", "The pitch the sound will play at.", Integer.class, - this); - } else { - ChatUtils.msgError(getP(), input + - " is not a valid sound. Click for a list of sounds -> https://www.spigotmc.org/wiki/cc-sounds-list/"); - } - } else if (value.equalsIgnoreCase("sound pitch")) { - if (Utils.isInt(input)) { - sd.setPitch(Integer.parseInt(input)); - new InputMenu(getCc(), getP(), "sound volume", "null", "The volume the sound will play at.", Integer.class, - this); - } else { - ChatUtils.msgError(getP(), input + " is not a valid integer (number)."); - } - } else if (value.equalsIgnoreCase("sound volume")) { - if (Utils.isInt(input)) { - sd.setVolume(Integer.parseInt(input)); - - cs.getSound().addSound(tier, sd); - - getP().closeInventory(); - new IGCCrateSound(getCc(), getP(), this, crates, sd, tier).open(); - } else { - ChatUtils.msgError(getP(), input + " is not a valid integer (number)."); - } - } - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCratesEssentials.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCratesEssentials.java deleted file mode 100644 index ff3f6f3..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCratesEssentials.java +++ /dev/null @@ -1,287 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.crates; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.options.ObtainType; -import me.ztowne13.customcrates.crates.types.animations.CrateAnimationType; -import me.ztowne13.customcrates.crates.types.display.EntityType; -import me.ztowne13.customcrates.crates.types.display.MaterialPlaceholder; -import me.ztowne13.customcrates.crates.types.display.npcs.Citizens2NPCPlaceHolder; -import me.ztowne13.customcrates.crates.types.display.npcs.MobPlaceholder; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCListSelector; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.inputmenus.InputMenu; -import me.ztowne13.customcrates.interfaces.igc.items.IGCItemEditor; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.NPCUtils; -import me.ztowne13.customcrates.utils.Utils; -import org.bukkit.entity.Player; - -import java.util.Arrays; - -public class IGCCratesEssentials extends IGCMenuCrate { - public IGCCratesEssentials(SpecializedCrates cc, Player p, IGCMenu lastMenu, Crate crates) { - super(cc, p, lastMenu, "&7&l> &6&lThe Defaults", crates); - } - - @Override - public void openMenu() { - - InventoryBuilder ib = createDefault(27); - - ib.setItem(0, IGCDefaultItems.EXIT_BUTTON.getIb()); - - //9-17 (11-15) - ib.setItem(9, new ItemBuilder(crates.isEnabled() ? XMaterial.LIME_WOOL : XMaterial.RED_WOOL) - .setDisplayName(crates.isEnabled() ? "&aEnabled" : "&cDisabled").addLore("&7Click me to toggle the crate.") - .addLore("").addAutomaticLore("&f", 30, "Completely enable or disable the crate.")); - ib.setItem(2, new ItemBuilder(XMaterial.BOOK).setDisplayName("&aSet the crate permission").setLore("&7Current value: ") - .addLore("&7" + cs.getPermission()).addLore("") - .addAutomaticLore("&f", 30, - "The permissions that is required to open this crate. Great for monthly crates, donor crates.")); - ib.setItem(3, new ItemBuilder(XMaterial.BUCKET).setDisplayName("&aSet the obtain-method").setLore("&7Current value: ") - .addLore("&7" + cs.getObtainType().name()).addLore("") - .addAutomaticLore("&f", 30, - "STATIC: Crate stays in place forever. DYNAMIC: Crate disappears when used. LUCKYCHEST (Mine Crate): Find this crate while mining.")); - ib.setItem(4, new ItemBuilder(XMaterial.PAPER).setDisplayName("&aSet the inventory-name").setLore("&7Current value: ") - .addLore("&7" + cs.getCrateInventoryName()).addLore("").addAutomaticLore("&f", 30, - "The name of the inventory for the animation, or name of the MultiCrate. If this value is set to 'none' the inventory name in the CrateConfig.YML for that animation will be used.")); - ib.setItem(6, new ItemBuilder(XMaterial.BIRCH_BUTTON).setDisplayName("&aSet the display.type") - .setLore("&7Current value: ").addLore("&7" + cs.getPlaceholder()).addLore("") - .addAutomaticLore("&f", 30, "How the crate will appear to players (block, npc, mob, etc.)")); - - if (crates.getSettings().getPlaceholder().toString().equalsIgnoreCase("mob") || - crates.getSettings().getPlaceholder().toString().equalsIgnoreCase("npc")) { - ib.setItem(15, new ItemBuilder(XMaterial.STONE_BUTTON).setDisplayName("&aSet the " + cs.getPlaceholder() + " type") - .setLore("&7Current value: ").addLore("&7" + cs.getPlaceholder().getType()).addLore("") - .addAutomaticLore("&f", 30, "Set the type of mob it will be or playername for the NPC.")); - } - - ib.setItem(11, - new ItemBuilder(XMaterial.SNOWBALL).setDisplayName("&aSet the cooldown").setLore("&7Current value: ") - .addLore("&7" + cs.getCooldown()).addLore("").addAutomaticLore("&f", 30, - "The duration of time, in seconds, between when a player can open the crate. Set to -1 to have no cooldown.")); - ib.setItem(8, new ItemBuilder(XMaterial.CHEST).setDisplayName("&a&lEdit the crate item.").addLore("") - .addAutomaticLore("&f", 30, "Click to open the crate item editor.")); - if (!crates.isMultiCrate()) { - ib.setItem(17, - new ItemBuilder(XMaterial.TRIPWIRE_HOOK).setDisplayName("&a&lEdit the crate key.").addLore("") - .addAutomaticLore("&f", 30, - "Click to open the key item editor.")); - - ib.setItem(12, - new ItemBuilder(XMaterial.SLIME_BALL).setDisplayName("&aSet require key").setLore("&7Current value: ") - .addLore("&7" + cs.isRequireKey()).addLore("").addAutomaticLore("&f", 30, - "Does the crate require a key? Best for keyless weekly/monthly crates or DYNAMIC crates that can be placed to open without a key. Or if minecrates can be opened without needing a key.")); - - ItemBuilder cost = new ItemBuilder(XMaterial.DIAMOND); - cost.setDisplayName("&aEdit the cost."); - cost.addLore("&7Current Value:").addLore("&7" + crates.getSettings().getCost()); - cost.addLore("").addAutomaticLore("&f", 30, "This is how much it costs to open the crate, " + - "regardless of whether or not require-key is set to true or false."); - cost.addLore("").addAutomaticLore("&c", 30, "REQUIRES Vault"); - ib.setItem(5, cost); - - ItemBuilder animations = new ItemBuilder(XMaterial.ITEM_FRAME); - animations.setDisplayName("&aEdit Animation Preferences"); - animations.addAutomaticLore("&f", 30, "Edit the animation type, auto-close, and allow-skip-animation values."); - ib.setItem(26, animations); - } - - getIb().open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - if ((slot == 5 || slot == 7 || slot == 16) && crates.isMultiCrate()) { - return; - } - - switch (slot) { - case 0: - up(); - break; - case 9: - if (crates.isCanBeEnabled()) { - crates.setEnabled(!crates.isEnabled()); - getIb().setItem(9, - new ItemBuilder(crates.isEnabled() ? XMaterial.LIME_WOOL : XMaterial.RED_WOOL) - .setDisplayName(crates.isEnabled() ? "&aEnabled" : "&cDisabled") - .addLore("&7Click me to toggle the crate.")); - } else { - getIb().setItem(9, new ItemBuilder(getIb().getInv().getItem(9)).setDisplayName("&4You cannot do this") - .setLore("&4This crate cannot be enabled").addLore("&4for it failed to load,") - .addLore("&4due to a misconfiguration, on").addLore("&4startup. Please fix any errors,") - .addLore("&4reload the plugin, and try again.")); - } - break; - case 2: - new InputMenu(getCc(), getP(), "permission", cs.getPermission(), "Type 'none' to remove the permission.", - String.class, this, true); - break; - case 3: -// new InputMenu(getCc(), getP(), "obtain-method", cs.getOt().name(), -// "Available obtain methods: " + Arrays.toString(ObtainType.values()), String.class, this, true); - new IGCListSelector(getCc(), getP(), this, "Obtain Type", Arrays.asList(ObtainType.values()), - XMaterial.PAPER, 1, ObtainType.descriptors()).open(); - break; - case 4: - new InputMenu(getCc(), getP(), "inventory-name", cs.getCrateInventoryName(), - "Set to 'none' to use the inv-name from the CrateConfig.YML", String.class, this, true); - break; - case 6: -// new InputMenu(getCc(), getP(), "display.type", cs.getDcp().toString(), -// "Available display types: block, mob, npc", -// String.class, this, true); - new IGCListSelector(getCc(), getP(), this, "Display Type", - Arrays.asList("BLOCK", "MOB", "NPC"), XMaterial.PAPER, 1, - Arrays.asList("", "Requires Citizens v2", "Requires Citizens v2")).open(); - break; - case 15: - if (cs.getPlaceholder().toString().equalsIgnoreCase("npc")) { - new InputMenu(getCc(), getP(), - "display." + (cs.getPlaceholder().toString().equalsIgnoreCase("mob") ? "creature" : "name"), - cs.getPlaceholder().getType(), cs.getPlaceholder().toString().equalsIgnoreCase("mob") ? - "Available mob types: " + EntityType.enumValues().toString() : "Use a player's name", - String.class, this, true); - } else if (cs.getPlaceholder().toString().equalsIgnoreCase("mob")) { - new IGCListSelector(getCc(), getP(), this, "Mob Type", EntityType.enumValues(), - XMaterial.PAPER, 1, null).open(); - } - break; - case 11: - new InputMenu(getCc(), getP(), "cooldown", cs.getCooldown() + "", "Time is measured in seconds.", - Integer.class, this); - break; - case 8: - new IGCItemEditor(getCc(), getP(), this, crates.getSettings().getCrateItemHandler().getItem()).open(); - break; - case 17: - new IGCItemEditor(getCc(), getP(), this, crates.getSettings().getKeyItemHandler().getItem()).open(); - break; - case 12: - cs.setRequireKey(!cs.isRequireKey()); - open(); - break; - case 26: - new IGCCrateAnimation(getCc(), getP(), this, getCrates()).open(); - break; - case 5: - new InputMenu(getCc(), getP(), "cost", cs.getCost() + "", - "How much the crate will cost to open. Set to 0 to have no cost.", Integer.class, this, true); - break; - } - } - - @Override - public boolean handleInput(String value, String input) { - if (value.equalsIgnoreCase("Obtain Type")) { - try { - ObtainType ot = ObtainType.valueOf(input.toUpperCase()); - cs.setObtainType(ot); - ChatUtils.msgSuccess(getP(), "Set the obtain type to " + input); - return true; - } catch (Exception exc) { - ChatUtils.msgError(getP(), - input + " is not one of the obtain types: " + Arrays.toString(ObtainType.values())); - } - } else if (value.equalsIgnoreCase("permission")) { - if (input.equalsIgnoreCase("none")) { - cs.setPermission("no permission"); - ChatUtils.msgSuccess(getP(), "Removed the permission."); - } else { - cs.setPermission(input); - ChatUtils.msgSuccess(getP(), "Set " + value + " to " + input); - } - return true; - } else if (value.equalsIgnoreCase("Animation Type")) { - try { - CrateAnimationType ct = CrateAnimationType.valueOf(input.toUpperCase()); - cs.setCrateType(ct); - ChatUtils.msgSuccess(getP(), "Set the Animation Type to " + input); - return true; - } catch (Exception exc) { - ChatUtils.msgError(getP(), - input + " is not valid in the list of crate animations: " + Arrays.toString(CrateAnimationType.values())); - } - } else if (value.equalsIgnoreCase("inventory-name")) { - if (input.length() < 33) { - if (input.equalsIgnoreCase("null") || input.equalsIgnoreCase("none")) { - cs.setCrateInventoryName(null); - return true; - } - cs.setCrateInventoryName(input); - ChatUtils.msgSuccess(getP(), "Set the " + value + " to " + input); - return true; - } - ChatUtils.msgError(getP(), input + " as an inventory-name cannot be longer than 32 characters."); - } else if (value.equalsIgnoreCase("Display Type")) { - switch (input.toUpperCase()) { - case "BLOCK": - cs.setPlaceholder(new MaterialPlaceholder(getCc())); - return true; - case "NPC": - if (!NPCUtils.isCitizensInstalled()) { - ChatUtils.msgError(getP(), "Citizens is not installed!"); - return false; - } - cs.setPlaceholder(new Citizens2NPCPlaceHolder(getCc())); - ChatUtils.msgSuccess(getP(), "Set " + value + " to " + input); - manageClick(15); - break; - case "MOB": - if (!NPCUtils.isCitizensInstalled()) { - ChatUtils.msgError(getP(), "Citizens is not installed!"); - return false; - } - cs.setPlaceholder(new MobPlaceholder(getCc())); - ChatUtils.msgSuccess(getP(), "Set " + value + " to " + input); - manageClick(15); - break; - default: - ChatUtils.msgError(getP(), input + " is not BLOCK, NPC, or MOB"); - } - - if (input.equalsIgnoreCase("mob") || input.equalsIgnoreCase("npc")) { - getIb().setItem(15, - new ItemBuilder(XMaterial.STONE_BUTTON).setDisplayName("&aSet the " + cs.getPlaceholder() + " type") - .setLore("&7Current value: ").addLore("&7" + cs.getPlaceholder().getType())); - } - } else if (value.equalsIgnoreCase("Mob Type")) { - try { - EntityType et = EntityType.getEnum(input.toUpperCase()); - cs.getPlaceholder().setType(et.name()); - ChatUtils.msgSuccess(getP(), "Set mob type to " + input); - return true; - } catch (Exception exc) { - ChatUtils.msgError(getP(), input + " is not a valid entity type: " + EntityType.enumValues().toString()); - } - } else if (value.equalsIgnoreCase("display.name")) { - cs.getPlaceholder().setType(input); - ChatUtils.msgSuccess(getP(), "Set " + value + " to " + input); - return true; - } else if (value.equalsIgnoreCase("cooldown")) { - if (Utils.isInt(input)) { - cs.setCooldown(Integer.parseInt(input)); - ChatUtils.msgSuccess(getP(), "Set " + value + " to " + input); - return true; - } else { - ChatUtils.msgError(getP(), input + " is not a valid number."); - } - } else if (value.equalsIgnoreCase("cost")) { - if (Utils.isInt(input)) { - cs.setCost(Integer.parseInt(input)); - ChatUtils.msgSuccess(getP(), "Set " + value + " to " + input); - return true; - } else { - ChatUtils.msgError(getP(), input + " is not a valid number."); - } - } - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCratesMain.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCratesMain.java deleted file mode 100644 index 349dbd4..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCCratesMain.java +++ /dev/null @@ -1,240 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.crates; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.options.ObtainType; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.buttons.IGCButtonType; -import me.ztowne13.customcrates.interfaces.igc.crates.previeweditor.IGCCratePreviewOrRewardMenu; -import me.ztowne13.customcrates.interfaces.igc.inputmenus.InputMenu; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.entity.Player; - -import java.util.HashSet; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Created by ztowne13 on 3/26/16. - */ -public class IGCCratesMain extends IGCMenuCrate { - public IGCCratesMain(SpecializedCrates cc, Player p, IGCMenu lastMenu, Crate crates) { - super(cc, p, lastMenu, "&7&l> &6&l" + crates.getName(), crates, - new IGCButtonType[]{ - IGCButtonType.BACK - }, - new int[]{ - (crates.isMultiCrate() ? 27 : 36) - }); - } - - @Override - public void openMenu() { - - InventoryBuilder ib = createDefault(crates.isMultiCrate() ? 36 : 45); - - ib.setItem(0, IGCDefaultItems.SAVE_ONLY_BUTTON.getIb()); - ib.setItem(9, IGCDefaultItems.RELOAD_BUTTON.getIb()); - ib.setItem(crates.isMultiCrate() ? 27 : 36, IGCDefaultItems.EXIT_BUTTON.getIb()); - ib.setItem(3, new ItemBuilder(XMaterial.RED_DYE).setDisplayName("&4&lDelete this crate") - .setLore("&cThis action CANNOT be undone.").addLore("&e&oNote: This does not delete rewards").addLore("") - .addLore("&7This will delete the entire").addLore("&7file for this crate and will") - .addLore("&7erase all data for it.")); - - ItemBuilder rename = new ItemBuilder(XMaterial.WRITABLE_BOOK); - rename.setDisplayName("&aRename this crate"); - rename.addLore("&7Current Value:").addLore("&7" + getCrates().getName()); - rename.addLore("").addAutomaticLore("&f", 30, - "This WILL reload the plugin when finished, please make sure all changes are saved."); - - ib.setItem(4, rename); - - ib.setItem(8, new ItemBuilder(XMaterial.RED_CARPET).setDisplayName("&aDelete all placed instances") - .setLore("&7Click this runs the command:").addLore("&7/ccrates delallcratetype " + crates.getName()) - .addLore("").addLore("&7It deletes all crates").addLore("&7of this type that have been") - .addLore("&7placed.")); - - int errors = crates.getSettings().getStatusLogger().getFailures(); - ib.setItem(5, new ItemBuilder(XMaterial.REDSTONE_BLOCK) - .setDisplayName(errors == 0 ? "&aThis crate has no errors!" : "&c&lClick to view ERRORS") - .addLore("&7Errors: " + errors)); - - ib.setItem(10, new ItemBuilder(XMaterial.STONE_BUTTON).setDisplayName("&aThe &lEssentials") - .setLore("&7This includes things such as").addLore("&7crate / key material,") - .addLore("&7crate-animation, obtain methods").addLore("&7and more")); - ib.setItem(16, - new ItemBuilder(XMaterial.NETHER_STAR).setDisplayName("&a&lParticles").setLore("&7Modify particles for play") - .addLore("&7and open use.")); - ib.setItem(21, new ItemBuilder(XMaterial.BOOK).setDisplayName("&a&lHolograms").setLore("&7Modify the holograms.")); - - ItemBuilder sounds = new ItemBuilder(XMaterial.NOTE_BLOCK); - sounds.setDisplayName("&a&lSounds"); - if (crates.isMultiCrate()) { - sounds.addAutomaticLore("&7", 30, "Edit the sounds played when the multicrate is opened initially."); - } else { - sounds.addAutomaticLore("&7", 30, "Edit the sounds for when the crate is opened and reward is given."); - } - ib.setItem(23, sounds); - - if (!crates.isMultiCrate()) { - ib.setItem(28, new ItemBuilder(XMaterial.FIREWORK_ROCKET).setDisplayName("&a&lFireworks") - .setLore("&7Modify the fireworks.")); - ib.setItem(34, - new ItemBuilder(XMaterial.PAPER).setDisplayName("&a&lActions").setLore("&7Modify messages, broadcasts,") - .addLore("&7titles, subtitles, and").addLore("&7actionbars.")); - - ItemBuilder rewards = new ItemBuilder(XMaterial.LIGHT_BLUE_DYE); - rewards.setDisplayName("&a&lRewards"); - rewards.addAutomaticLore("&7", 30, "Edit the rewards and edit the reward preview menu."); - - ib.setItem(40, rewards); - } else { - ib.setItem(34, new ItemBuilder(XMaterial.LADDER).setDisplayName("&aMultiCrate Values") - .setLore("&7Modify the multicrate inventory and").addLore("&7other values.")); - } - - if (cs.getObtainType().equals(ObtainType.LUCKYCHEST)) { - ib.setItem(crates.isMultiCrate() ? 35 : 44, new ItemBuilder(XMaterial.ENDER_CHEST).setDisplayName("&aMine Chest") - .setLore("&7Config all values for the").addLore("&7mine chest.")); - } - - ib.open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - if (crates.isMultiCrate() && (slot == 28 || slot == 40)) { - return; - } - - switch (slot) { - case 0: - if (!crates.isMultiCrate() && - (cs.getReward().getCrateRewards() == null || cs.getReward().getCrateRewards().length == 0)) { - getIb().setItem(slot, - new ItemBuilder(getIb().getInv().getItem(slot)).setDisplayName("&cPlease add some rewards") - .setLore("&cbefore saving!")); - } else { - try { - crates.getSettings().saveAll(); - ChatUtils.msgSuccess(getP(), "Saved the file!"); - } catch (Exception exc) { - exc.printStackTrace(); - ChatUtils.msgError(getP(), "Failed to save the file!"); - } - } - break; - case 3: - if (ChatUtils.removeColor(getIb().getInv().getItem(3).getItemMeta().getDisplayName()) - .equalsIgnoreCase("Delete this crate")) { - getIb().setItem(3, new ItemBuilder(XMaterial.RED_DYE).setDisplayName("&6CONFIRM DELETE") - .setLore("&4&lTHIS CANNOT BE UNDONE!")); - } else { - getP().closeInventory(); - ChatUtils.msg(getP(), "&6&lNote: &eDeleting..."); - String path = crates.deleteCrate(); - ChatUtils.msgSuccess(getP(), "Successfully deleted file on path &e" + path); - } - break; - case 4: - new InputMenu(getCc(), getP(), "Crate name", crates.getName(), "Do not use ANY spaces or special characters", - String.class, this, true); - break; - case 5: - getP().closeInventory(); - getP().performCommand("scrates errors " + crates.getName()); - break; - case 9: - reload(); - break; -// case 27: -// if (!crates.isMultiCrate()) -// { -// return; -// } -// case 36: -// if (getLastMenu() == null) -// { -// getP().closeInventory(); -// break; -// } -// up(); -// break; - case 8: - getP().chat("/ccrates delallcratetype " + crates.getName()); - break; - case 10: - new IGCCratesEssentials(getCc(), getP(), this, crates).open(); - break; - case 16: - Set blankParticles = new HashSet<>(); - blankParticles.add("PLAY"); - if (!crates.isMultiCrate()) { - blankParticles.add("OPEN"); - } - new IGCTierSelector(getCc(), getP(), this, crates, blankParticles, - new IGCCrateParticles(getCc(), getP(), this, crates, "")).open(); - break; - case 21: - new IGCCrateHolograms(getCc(), getP(), this, crates).open(); - break; - case 23: - Set blankSounds = new HashSet<>(); - blankSounds.add("OPEN"); - new IGCTierSelector(getCc(), getP(), this, crates, blankSounds, - new IGCCrateSounds(getCc(), getP(), this, crates, "")).open(); - break; - case 28: - Set blankFireworks = new HashSet<>(); - blankFireworks.add("OPEN"); - new IGCTierSelector(getCc(), getP(), this, crates, blankFireworks, - new IGCCrateFireworks(getCc(), getP(), this, crates, "")).open(); - break; - case 34: - if (crates.isMultiCrate()) { - new IGCMultiCrateMain(getCc(), getP(), this, crates).open(); - } else { - Set blankActions = new HashSet<>(); - blankActions.add("DEFAULT"); - new IGCTierSelector(getCc(), getP(), this, crates, blankActions, - new IGCCrateActions(getCc(), getP(), this, crates, "")).open(); - } - break; - case 40: - new IGCCratePreviewOrRewardMenu(getCc(), getP(), crates, this).open(); - break; - case 44: - if (cs.getObtainType().equals(ObtainType.LUCKYCHEST)) { - new IGCMineCrate(getCc(), getP(), this, crates).open(); - } - break; - } - } - - @Override - public boolean handleInput(String value, String input) { - if (value.equalsIgnoreCase("crate name")) { - String regex = "^[a-zA-Z0-9]+$"; - Pattern pattern = Pattern.compile(regex); - Matcher matcher = pattern.matcher(input); - if (matcher.matches()) { - if (crates.rename(input)) { - ChatUtils.msgSuccess(getP(), "Successfully renamed " + crates.getName() + " to " + input); - ChatUtils.msgInfo(getP(), "Reloading the plugin to let changes take effect."); - return false; - } - ChatUtils.msgError(getP(), "Failed to rename the crate. This likely because the crate name " + input + " already exists. Please try a different name."); - return false; - } - ChatUtils.msgError(getP(), input + " is not alphanumeric (no spaces and only letters)"); - return false; - } - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCMenuCrate.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCMenuCrate.java deleted file mode 100644 index 794e833..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCMenuCrate.java +++ /dev/null @@ -1,35 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.crates; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.CrateSettings; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.buttons.IGCButtonType; -import org.bukkit.entity.Player; - -/** - * Created by ztowne13 on 3/31/16. - */ -public abstract class IGCMenuCrate extends IGCMenu { - Crate crates; - CrateSettings cs; - - public IGCMenuCrate(SpecializedCrates cc, Player p, IGCMenu lastMenu, String invName, Crate crates) { - this(cc, p, lastMenu, invName, crates, new IGCButtonType[]{}, new int[]{}); - } - - public IGCMenuCrate(SpecializedCrates cc, Player p, IGCMenu lastMenu, String invName, Crate crates, - IGCButtonType[] buttonTypes, int[] buttonSpots) { - super(cc, p, lastMenu, invName, buttonTypes, buttonSpots); - this.crates = crates; - this.cs = crates.getSettings(); - } - - public Crate getCrates() { - return crates; - } - - public CrateSettings getCs() { - return cs; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCMineCrate.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCMineCrate.java deleted file mode 100644 index 4c48b0e..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCMineCrate.java +++ /dev/null @@ -1,176 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.crates; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCListEditor; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.inputmenus.InputMenu; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.Utils; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.entity.Player; - -import java.util.Optional; - -/** - * Created by ztowne13 on 4/5/16. - */ -public class IGCMineCrate extends IGCMenuCrate { - public IGCMineCrate(SpecializedCrates cc, Player p, IGCMenu lastMenu, Crate crates) { - super(cc, p, lastMenu, "&7&l> &6&lMine Crate", crates); - } - - @Override - public void openMenu() { - - InventoryBuilder ib = createDefault(27); - - ib.setItem(9, IGCDefaultItems.EXIT_BUTTON.getIb()); - - ib.setItem(11, new ItemBuilder(XMaterial.FISHING_ROD).setDisplayName("&aChance").setLore("&7Current value: ") - .addLore("&7" + cs.getLuckyChestSettings().getChance() + "/" + cs.getLuckyChestSettings().getOutOfChance()) - .addLore("") - .addAutomaticLore("&f", 30, - "These are the odds that a crate will appear while mining. Formatted 'number/number'.")); - ib.setItem(12, new ItemBuilder(XMaterial.LIGHT_GRAY_DYE).setDisplayName("&aWhitelist") - .addLore("&7Current value: ").addLore("&7" + cs.getLuckyChestSettings().isBLWL() + "").addLore("") - .addAutomaticLore("&f", 30, "Set whether the block-list is a whitelist or not.")); - ItemBuilder bList = - new ItemBuilder(XMaterial.STONE).setDisplayName("&aEdit the block-list").setLore("&7Current values: "); - - for (Material m : cs.getLuckyChestSettings().getWhiteList()) { - bList.addLore("&7" + m.name()); - } - bList.addLore("").addAutomaticLore("&f", 30, "These are all the materials on the blacklist (or whitelist)."); - ib.setItem(13, bList); - - ItemBuilder wList = - new ItemBuilder(XMaterial.PURPLE_DYE, 1).setDisplayName("&aEdit the worlds").setLore("&7Current values: "); - for (String w : cs.getLuckyChestSettings().getWorldsRaw()) { - wList.addLore("&7" + w); - } - wList.addLore("").addAutomaticLore("&f", 30, - "These are the worlds where mine crates can be found. Remove all the worlds for ALL worlds to be allowed."); - ib.setItem(14, wList); - - ItemBuilder requirePermission = new ItemBuilder(XMaterial.BOOK); - requirePermission.setDisplayName("&aRequire Permission to Find"); - requirePermission.addLore("&7Current Value:") - .addLore("&7" + crates.getSettings().getLuckyChestSettings().isRequirePermission()); - requirePermission.addLore("").addAutomaticLore("&f", 30, - "Set whether or not the crate's permission is required for the player to find the crate."); - ib.setItem(15, requirePermission); - - ib.open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - switch (slot) { - case 9: - up(); - break; - case 11: - new InputMenu(getCc(), getP(), "chance", - cs.getLuckyChestSettings().getChance() + "/" + cs.getLuckyChestSettings().getOutOfChance(), - "Format it 'chance/out of what chance'.", String.class, this, true); - break; - case 12: - cs.getLuckyChestSettings().setBLWL(!cs.getLuckyChestSettings().isBLWL()); - open(); - break; - case 13: - new IGCListEditor(getCc(), getP(), this, "Block List", "Block", cs.getLuckyChestSettings().getWhiteList(), - XMaterial.STONE, 1, XMaterial.class, "valueOf", "That is not a valid block name. Try STONE.") - .open(); - break; - case 14: - new IGCListEditor(getCc(), getP(), this, "Worlds List", "World", cs.getLuckyChestSettings().getWorldsRaw(), - XMaterial.MAP, 1).open(); - break; - case 15: - cs.getLuckyChestSettings().setRequirePermission(!cs.getLuckyChestSettings().isRequirePermission()); - open(); - break; - case 16: - new InputMenu(getCc(), getP(), "remove worlds", cs.getLuckyChestSettings().getWorlds().toString(), - "Current valid worlds: " + Bukkit.getWorlds(), String.class, this, true); - break; - } - } - - @Override - public boolean handleInput(String value, String input) { - if (value.equalsIgnoreCase("chance")) { - try { - String[] split = input.split("/"); - if (Utils.isInt(split[0])) { - if (Utils.isInt(split[1])) { - cs.getLuckyChestSettings().setChance(Double.parseDouble(split[0])); - cs.getLuckyChestSettings().setOutOfChance(Double.parseDouble(split[1])); - ChatUtils.msgSuccess(getP(), "Set " + value + " to " + input); - return true; - } else { - ChatUtils.msgError(getP(), split[1] + " is not a valid number."); - } - } else { - ChatUtils.msgError(getP(), split[0] + " is not a valid number."); - } - } catch (Exception exc) { - ChatUtils.msgError(getP(), input + " is not formatted 'number/number' or 'chance/out of chance'"); - } - } else if (value.equalsIgnoreCase("remove block-list")) { - Optional optional = XMaterial.matchXMaterial(input); - if (optional.isPresent()) { - Material m = optional.get().parseMaterial(); - if (cs.getLuckyChestSettings().getWhiteList().contains(m)) { - cs.getLuckyChestSettings().getWhiteList().remove(m); - ChatUtils.msgSuccess(getP(), "Removed the " + input + " value from the whitelist / blacklist"); - return true; - } else { - ChatUtils.msgError(getP(), input + " does not exist in the blacklist / whitelist."); - } - } else { - ChatUtils.msgError(getP(), input + " is not a valid material."); - } - } else if (value.equalsIgnoreCase("add worlds")) { - try { - World w = Bukkit.getWorld(input); - cs.getLuckyChestSettings().getWorlds().add(w); - ChatUtils.msgSuccess(getP(), "Added " + input + " to the list of allowed worlds."); - return true; - } catch (Exception exc) { - ChatUtils.msgError(getP(), - input + " is a non-existent world from the list of worlds: " + Bukkit.getWorlds().toString()); - } - } else if (value.equalsIgnoreCase("remove worlds")) { - try { - World w = Bukkit.getWorld(input); - if (w != null) { - if (cs.getLuckyChestSettings().getWorlds().contains(w)) { - cs.getLuckyChestSettings().getWorlds().remove(w); - ChatUtils.msgSuccess(getP(), "Removed " + input + " from the list of allowed worlds."); - return true; - } else { - ChatUtils.msgError(getP(), - input + " is not currently allowed in the worlds list to be remobed. Current worlds: " + - cs.getLuckyChestSettings().getWorlds().toString()); - } - } else { - throw new Exception(); - } - } catch (Exception exc) { - ChatUtils.msgError(getP(), - input + " is a non-existent world from the list of worlds: " + Bukkit.getWorlds().toString()); - } - } - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCMultiCrateMain.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCMultiCrateMain.java deleted file mode 100644 index 8f40e90..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCMultiCrateMain.java +++ /dev/null @@ -1,88 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.crates; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.inputmenus.InputMenu; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.Utils; -import org.bukkit.entity.Player; - -/** - * Created by ztowne13 on 6/29/16. - */ -public class IGCMultiCrateMain extends IGCMenuCrate { - public IGCMultiCrateMain(SpecializedCrates cc, Player p, IGCMenu lastMenu, Crate crates) { - super(cc, p, lastMenu, "&7&l> &6&lMultiCrates Main", crates); - } - - @Override - public void openMenu() { - - InventoryBuilder ib = createDefault(9); - - ib.setItem(0, IGCDefaultItems.EXIT_BUTTON.getIb()); - ib.setItem(2, new ItemBuilder(XMaterial.PAPER).setDisplayName("&aEdit the current GUI").addLore("") - .addAutomaticLore("&f", 30, - "Design the multicrate inventory in the inventory that opens. Put the actual crates in for the crates, and normal blocks for filler blocks.")); - ib.setItem(4, - new ItemBuilder(XMaterial.BOOK).setDisplayName("&aEdit the amount of rows").setLore("&7Current value:") - .addLore("&7" + (crates.getSettings().getMultiCrateSettings().getInventory(getP(), "", false).getInv().getSize() / 9)) - .addLore("") - .addAutomaticLore("&f", 30, "Set the size (in amount of rows) of the multicrate's inventory.")); - ib.setItem(6, new ItemBuilder(XMaterial.RED_WOOL).setDisplayName("&aClear the inventory") - .setLore("&4&lWARNING: &cThis clears the entire").addLore("&cinventory.")); - - getIb().open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - switch (slot) { - case 0: - up(); - break; - case 2: - crates.getSettings().getMultiCrateSettings().getInventory(getP(), "&c&lClose to save", true).open(); - ChatUtils.msgSuccess(getP(), - "Close the inventory to save, if you don't want to save, type /scrates reload and all changes will be lost."); - break; - case 4: - new InputMenu(getCc(), getP(), "set rows", - (crates.getSettings().getMultiCrateSettings().getInventory(getP(), "", false).getInv().getSize() / 9) + "", - "Please use a number between 1 and 6", Integer.class, this); - break; - case 6: - crates.getSettings().getMultiCrateSettings().getInventory(getP(), "", false).getInv().clear(); - ChatUtils.msgSuccess(getP(), "You have cleared the inventory."); - break; - } - } - - @Override - public boolean handleInput(String value, String input) { - if (value.equalsIgnoreCase("set rows")) { - if (Utils.isInt(input)) { - InventoryBuilder oldIb = crates.getSettings().getMultiCrateSettings().getInventory(getP(), "", false); - InventoryBuilder newIb = new InventoryBuilder(getP(), Integer.parseInt(input) * 9, oldIb.getName()); - - for (int i = 0; i < Math.min(oldIb.getInv().getSize(), newIb.getInv().getSize()); i++) { - if (!(oldIb.getInv().getItem(i) == null)) { - newIb.setItem(i, oldIb.getInv().getItem(i)); - } - } - crates.getSettings().getMultiCrateSettings().setInventoryBuilder(newIb); - ChatUtils.msgSuccess(getP(), "Set " + value + " to " + input); - return true; - } else { - ChatUtils.msgError(getP(), input + " is not a valid number."); - } - } - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCTierMenu.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCTierMenu.java deleted file mode 100644 index cb551aa..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCTierMenu.java +++ /dev/null @@ -1,26 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.crates; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import org.bukkit.entity.Player; - -/** - * Created by ztowne13 on 4/2/16. - */ -public abstract class IGCTierMenu extends IGCMenuCrate { - String tier; - - public IGCTierMenu(SpecializedCrates cc, Player p, IGCMenu lastMenu, String name, Crate crates, String tier) { - super(cc, p, lastMenu, name, crates); - this.tier = tier; - } - - public String getTier() { - return tier; - } - - public void setTier(String tier) { - this.tier = tier; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCTierSelector.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCTierSelector.java deleted file mode 100644 index c2d1221..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/IGCTierSelector.java +++ /dev/null @@ -1,125 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.crates; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.InventoryUtils; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.entity.Player; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Set; - -/** - * Created by ztowne13 on 4/2/16. - */ -public class IGCTierSelector extends IGCMenuCrate { - static List allowedTiers = Arrays.asList("PLAY", "OPEN", "DEFAULT"); - - Set tiers; - IGCTierMenu igcTierMenu; - - public IGCTierSelector(SpecializedCrates cc, Player p, IGCMenu lastMenu, Crate crates, Set tiers, - IGCTierMenu igcTierMenu) { - super(cc, p, lastMenu, "&7&l> &6&lTier Selector", crates); - this.tiers = tiers; - this.igcTierMenu = igcTierMenu; - - } - - @Override - public void openMenu() { - if (tiers.size() == 1) { - igcTierMenu.setTier(tiers.iterator().next()); - igcTierMenu.open(); - return; - } - - igcTierMenu.setLastMenu(this); - - InventoryBuilder ib = createDefault(InventoryUtils.getRowsFor(4, tiers.size()) + 9); - - ib.setItem(9, IGCDefaultItems.EXIT_BUTTON.getIb()); - - int i = 2; - - ArrayList allTiers = new ArrayList<>(tiers); - for (Reward reward : crates.getSettings().getReward().getCrateRewards()) { - String tier = reward.getRarity().toUpperCase(); - if (!tier.equalsIgnoreCase("DEFAULT") && !allTiers.contains(tier)) { - allTiers.add(tier); - } - } - - for (String tier : allTiers) { - if (i % 9 == 7) { - i += 4; - } - - ItemBuilder button = new ItemBuilder(XMaterial.STONE_BUTTON); - button.setDisplayName("&a" + tier); - if (tier.equalsIgnoreCase("PLAY")) { - ItemBuilder play = button.clone(); - play.getStack().setType(XMaterial.EMERALD.parseMaterial()); - play.addAutomaticLore("&7", 30, "These are the values run while the crate is sitting, idle."); - play.addLore(""); - play.addAutomaticLore("&e", 30, - "To add a new 'tier,' change the 'rarity' of a reward in this crate to a new value."); - ib.setItem(i, play); - } else { - button.addLore("&7Rewards in this tier:"); - int listedRewards = 0; - int remaining = 0; - for (Reward reward : crates.getSettings().getReward().getCrateRewards()) { - if (!reward.getRarity().equalsIgnoreCase(tier) && - !(reward.getRarity().equalsIgnoreCase("DEFAULT") && tier.equalsIgnoreCase("OPEN"))) { - continue; - } - if (listedRewards >= 5) { - remaining++; - } else { - button.addLore("&7- &f" + reward.getRewardName()); - listedRewards++; - } - } - - if (remaining > 0) { - button.addLore("&7(and &f" + remaining + "&7 more)"); - } - - button.addLore(""); - button.addAutomaticLore("&e", 30, - "To add a new 'tier' to this crate, change the 'rarity' of any reward in this crate to a new tier value."); - ib.setItem(i, button); - } - - i++; - } - - ib.open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - if (slot == 9) { - up(); - } else if (getIb().getInv().getItem(slot) != null && !XMaterial.AIR.isSimilar(getIb().getInv().getItem(slot))) { - String tier = ChatUtils.removeColor(getIb().getInv().getItem(slot).getItemMeta().getDisplayName()); - igcTierMenu.setTier(tier); - igcTierMenu.open(); - } - } - - @Override - public boolean handleInput(String value, String input) { - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/crateanimations/IGCAnimCSGO.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/crateanimations/IGCAnimCSGO.java deleted file mode 100644 index 08f8d30..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/crateanimations/IGCAnimCSGO.java +++ /dev/null @@ -1,213 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.crates.crateanimations; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.types.animations.CrateAnimationType; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.inputmenus.InputMenu; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.Utils; -import org.bukkit.entity.Player; - -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - -/** - * Created by ztowne13 on 7/6/16. - *

- * inv-name: '&8&l> &6&l%crate%' - * tick-sound: ENTITY_PLAYER_BIG_FALL, 5, 5 - * identifier-block: REDSTONE_TORCH_ON;0 - * tick-speed-per-run: 3 - * final-crate-tick-length: 11 - * tile-update-ticks: 2 - * close-speed: 3 - * filler-blocks: - * - STAINED_GLASS_PANE;1 - * - STAINED_GLASS_PANE;2 - * - STAINED_GLASS_PANE;3 - * - STAINED_GLASS_PANE;4 - * - STAINED_GLASS_PANE;5 - * - STAINED_GLASS_PANE;6 - * - STAINED_GLASS_PANE;7 - * - STAINED_GLASS_PANE;8 - * - STAINED_GLASS_PANE;9 - */ -public class IGCAnimCSGO extends IGCAnimation { - public IGCAnimCSGO(SpecializedCrates cc, Player p, IGCMenu lastMenu) { - super(cc, p, lastMenu, "&7&l> &6&lCSGO Animation", CrateAnimationType.INV_CSGO); - } - - @Override - public void openMenu() { - - InventoryBuilder ib = createDefault(18); - - - ib.setItem(0, IGCDefaultItems.EXIT_BUTTON.getIb()); - ib.setItem(2, - new ItemBuilder(XMaterial.BOOK).setDisplayName("&ainv-name").addLore(getcVal() + getString("inv-name")) - .addLore("").addAutomaticLore("&f", 30, - "The name of the inventory when the animation runs. This is overwritten by the crate's 'inv-name' value, if it exists.")); - ib.setItem(4, new ItemBuilder(XMaterial.PAPER).setDisplayName("&atick-speed-per-run") - .addLore(getcVal()).addLore("&7" + getString("tick-speed-per-run")).addLore("") - .addAutomaticLore("&f", 30, - "The rate at which the scrolling items will slow down. A lower value will make the speed of the " + - "scroll take longer to slow down while a higher value will make the scroll slow down much quicker.")); - ib.setItem(5, new ItemBuilder(XMaterial.PAPER).setDisplayName("&afinal-crate-tick-length") - .addLore(getcVal()).addLore("&7" + getString("final-crate-tick-length")).addLore("") - .addAutomaticLore("&f", 30, - "The speed the animation must reach to end. A lower value will result in the animation ending while" + - " the scroll is still moving quickly, and a higher value will make it end when it is scrolling slower.")); - ib.setItem(6, new ItemBuilder(XMaterial.PAPER).setDisplayName("&atile-update-ticks") - .addLore(getcVal()).addLore("&7" + getString("tile-update-ticks")).addLore("").addAutomaticLore("&f", 30, - "The delay between when the random-blocks update. A lower will make the random-blocks update very " + - "quickly, and a higher value update slowly.")); - ib.setItem(7, new ItemBuilder(XMaterial.PAPER).setDisplayName("&aclose-speed") - .addLore(getcVal()).addLore("&7" + getString("close-speed")).addLore("") - .addAutomaticLore("&f", 30, - "The tick delay between the 'close' animation. Set to -1 to have no closing animation.")); - ib.setItem(11, new ItemBuilder(XMaterial.NOTE_BLOCK).setDisplayName("&atick-sound") - .addLore(getcVal()).addLore("&7" + getString("tick-sound")).addLore("") - .addAutomaticLore("&f", 30, - "The sound that is played every time the inventory updates. Set to 'none' to have no sound.")); - ib.setItem(12, new ItemBuilder(XMaterial.REDSTONE_TORCH).setDisplayName("&aidentifier-block") - .addLore(getcVal()).addLore("&7" + getString("identifier-block")).addLore("") - .addAutomaticLore("&f", 30, - "The block that will be used as the 'marker' for the winning item in the scroll wheel.")); - - ItemBuilder fillerBlocks = - new ItemBuilder(XMaterial.ENDER_CHEST).setDisplayName("&aAdd new filler-blocks").setLore("&7Current values: "); - for (String s : fc.getStringList(getPath("filler-blocks"))) { - fillerBlocks.addLore("&7- " + s); - } - - fillerBlocks.addLore("").addAutomaticLore("&f", 30, "The blocks that will fill empty space in the animation. Formatted Material;Data"); - ib.setItem(14, fillerBlocks); - ib.setItem(15, fillerBlocks.setDisplayName("&aRemove existing filler-blocks")); - - getIb().open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - switch (slot) { - case 0: - up(); - break; - case 2: - new InputMenu(getCc(), getP(), "inv-name", getString("inv-name"), "The name of the inventory", String.class, - this); - break; - case 4: - new InputMenu(getCc(), getP(), "tick-speed-per-run", getString("tick-speed-per-run"), - "How fast the animation updates the rewards.", Double.class, this); - break; - case 5: - new InputMenu(getCc(), getP(), "final-crate-tick-length", getString("final-crate-tick-length"), - "How long the animation will display.", Double.class, this); - break; - case 6: - new InputMenu(getCc(), getP(), "tile-update-ticks", getString("tile-update-ticks"), - "How fast, in ticks, the filler-blocks will update", Integer.class, this); - break; - case 7: - new InputMenu(getCc(), getP(), "close-speed", getString("close-speed"), - "How fast the 'close' animation will display. Set to -1 to not have a 'close' animation.", - Integer.class, this); - break; - case 11: - new InputMenu(getCc(), getP(), "tick-sound", getString("tick-sound"), - "Set to 'none' to have no sound. Formatted SOUND, PITCH, VOLUME. Click for a list of sounds -> https://www.spigotmc.org/wiki/cc-sounds-list/", - String.class, this, true); - break; - case 12: - new InputMenu(getCc(), getP(), "identifier-block", getString("identifier-block"), - "The block, formatted MATERIAL;ID, that identifies the middle block.", String.class, this, true); - break; - case 14: - new InputMenu(getCc(), getP(), "add filler-blocks", "Formated: MATERIAL;ID", String.class, this, true); - break; - case 15: - new InputMenu(getCc(), getP(), "remove filler-blocks", "Existing filler-blocks: " + - (fc.contains(crateAnimationType.getPrefix() + ".filler-blocks") ? - fc.getStringList(crateAnimationType.getPrefix() + ".filler-blocks") : "none"), String.class, this, true); - break; - } - } - - @Override - public boolean handleInput(String value, String input) { - Object type = getInputMenu().getType(); - if (type == Double.class) { - if (Utils.isDouble(input)) { - fc.set(getPath(value), Double.valueOf(input)); - ChatUtils.msgSuccess(getP(), "Set " + value + " to '" + input + "'"); - return true; - } else { - ChatUtils.msgError(getP(), "This is not a valid decimal value, please try again."); - } - } else if (type == Integer.class) { - if (Utils.isInt(input)) { - fc.set(getPath(value), Integer.parseInt(input)); - ChatUtils.msgSuccess(getP(), "Set " + value + " to '" + input + "'"); - return true; - } else { - ChatUtils.msgError(getP(), "This is not a valid number, please try again."); - } - } else { - if (value.equalsIgnoreCase("add filler-blocks")) { - Optional optional = XMaterial.matchXMaterial(input.replace(";", ":")); - if (optional.isPresent()) { - XMaterial dm = optional.get(); - List currentList = - fc.contains(getPath(value.substring(4))) ? fc.getStringList(getPath(value.substring(4))) : - new ArrayList<>(); - currentList.add(dm.name()); - fc.set(getPath(value.substring(4)), currentList); - return true; - } else { - ChatUtils.msgError(getP(), input + " does not have a valid material or is not formatted MATERIAL;DATA"); - } - } else if (value.equalsIgnoreCase("remove filler-blocks")) { - if (fc.contains(getPath(value.substring(7)))) { - boolean found = false; - List newList = new ArrayList<>(); - for (String s : fc.getStringList(getPath(value.substring(7)))) { - if (s.equalsIgnoreCase(input)) { - found = true; - } else { - newList.add(s); - } - } - - if (found) { - ChatUtils.msgSuccess(getP(), "Removed the " + input + " value."); - fc.set(getPath(value.substring(7)), newList); - return true; - } else { - ChatUtils.msgError(getP(), input + " does not exist in the filler / random blocks: " + - fc.getStringList(getPath(value.substring(7)))); - } - } else { - ChatUtils.msgError(getP(), "No filler blocks currently exist to remove."); - return true; - } - } else { - if (value.equalsIgnoreCase("tick-sound") && - (input.equalsIgnoreCase("null") || input.equalsIgnoreCase("none"))) { - fc.set(getPath(value), null); - } - fc.set(getPath(value), input); - ChatUtils.msgSuccess(getP(), "Set " + value + " to '" + input + "'"); - return true; - } - } - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/crateanimations/IGCAnimDiscover.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/crateanimations/IGCAnimDiscover.java deleted file mode 100644 index 308cb50..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/crateanimations/IGCAnimDiscover.java +++ /dev/null @@ -1,235 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.crates.crateanimations; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.types.animations.CrateAnimationType; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.inputmenus.InputMenu; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.Utils; -import org.bukkit.entity.Player; - -/** - * Created by ztowne13 on 7/7/16. - */ -public class IGCAnimDiscover extends IGCAnimation { - public IGCAnimDiscover(SpecializedCrates cc, Player p, IGCMenu lastMenu) { - super(cc, p, lastMenu, "&7&l> &6&lDiscover Animation", CrateAnimationType.INV_DISCOVER); - } - - @Override - public void openMenu() { - - InventoryBuilder ib = createDefault(27); - - ib.setItem(0, IGCDefaultItems.EXIT_BUTTON.getIb()); - - ib.setItem(2, - new ItemBuilder(XMaterial.BOOK).setDisplayName("&ainv-name").setLore(getcVal() + getString("inv-name")) - .addLore("").addAutomaticLore("&f", 30, - "The name of the inventory when the animation runs. This is overwritten by the crate's 'inv-name' value, if it exists.")); - ib.setItem(4, new ItemBuilder(XMaterial.PAPER).setDisplayName("&ainventory-rows") - .setLore(getcVal()).addLore("&7" + getString("inventory-rows")).addLore("") - .addAutomaticLore("&f", 30, - "The amount of rows in the inventory.")); - ib.setItem(5, new ItemBuilder(XMaterial.PAPER).setDisplayName("&aminimum-rewards") - .setLore(getcVal()).addLore("&7" + getString("minimum-rewards")).addLore("") - .addAutomaticLore("&f", 30, - "The minimum amount of rewards that could appear in the menu. Set to the same amount as the maximum-rewards for it to be the same amount every time.")); - ib.setItem(6, new ItemBuilder(XMaterial.PAPER).setDisplayName("&amaximum-rewards") - .setLore(getcVal()).addLore("&7" + getString("maximum-rewards")).addLore("") - .addAutomaticLore("&f", 30, - "The maximum amount of rewards that could appear in the menu. Set to the same amount as the minimum-rewards for it to be the same amount every time.")); - ib.setItem(7, new ItemBuilder(XMaterial.PAPER).setDisplayName("&arandom-display-duration") - .setLore(getcVal()).addLore("&7" + getString("random-display-duration")).addLore("") - .addAutomaticLore("&f", 30, "The duration in which the 'shuffling' animation will play for.")); - - boolean b = true; - try { - b = Boolean.parseBoolean(getString("count")); - } catch (Exception exc) { - - } - ib.setItem(11, new ItemBuilder(b ? XMaterial.LIME_WOOL : XMaterial.RED_WOOL).setDisplayName("&acount") - .setLore(getcVal()).addLore("&7" + b).addLore("") - .addAutomaticLore("&f", 30, - "Whether or not the cover-block's should display numbers. (i.e. whether they should be stacked items).")); - ib.setItem(12, new ItemBuilder(XMaterial.ENDER_CHEST).setDisplayName("&acover-block") - .setLore(getcVal()).addLore("&7" + getString("cover-block")).addLore("") - .addAutomaticLore("&f", 30, - "The block that the player will have to click to chose the random reward.")); - - ib.setItem(14, new ItemBuilder(XMaterial.NOTE_BLOCK).setDisplayName("&atick-sound") - .setLore(getcVal()).addLore("&7" + getString("tick-sound")).addLore("").addAutomaticLore("&f", 30, - "The sound that is played every time the inventory updates. Set to 'none' to have no sound.")); - ib.setItem(15, new ItemBuilder(XMaterial.NOTE_BLOCK).setDisplayName("&aclick-sound") - .setLore(getcVal()).addLore("&7" + getString("click-sound")).addLore("").addAutomaticLore("&f", 30, - "The sound that is played every time the player click's a cover block. Set to 'none' to have no sound.")); - ib.setItem(16, new ItemBuilder(XMaterial.NOTE_BLOCK).setDisplayName("&auncover-sound") - .setLore(getcVal()).addLore("&7" + getString("uncover-sound")).addLore("").addAutomaticLore("&f", 30, - "The sound that is played every time the player uncovers a reward. Set to 'none' to have no sound.")); - - // cover-block-name - ItemBuilder coverBlockName = new ItemBuilder(XMaterial.PAPER, 1); - coverBlockName.setDisplayName("&acover-block-name"); - coverBlockName.addLore(getcVal()).addLore("&7" + getString("cover-block-name")).addLore(""); - coverBlockName.addAutomaticLore("&f", 30, "The name of all the blocks before the user clicks anything. Use %number% for the number reward it is."); - - ItemBuilder coverBlockLore = new ItemBuilder(XMaterial.PAPER, 1); - coverBlockLore.setDisplayName("&acover-block-lore"); - coverBlockLore.addLore(getcVal()).addLore("&7" + getString("cover-block-lore")).addLore(""); - coverBlockLore.addAutomaticLore("&f", 30, "The lore of all the blocks before the user clicks them. Use %remaining-clicks% for the number of rewards remaining for the player to choose."); - - ItemBuilder rewardBlock = new ItemBuilder(XMaterial.LIME_STAINED_GLASS, 1); - rewardBlock.setDisplayName("&areward-block"); - rewardBlock.addLore(getcVal()).addLore("&7" + getString("reward-block")).addLore(""); - rewardBlock.addAutomaticLore("&f", 30, "The block that will be shown when a cover block is clicked."); - - ItemBuilder rewardBlockName = new ItemBuilder(XMaterial.PAPER, 1); - rewardBlockName.setDisplayName("&areward-block-name"); - rewardBlockName.addLore(getcVal()).addLore("&7" + getString("reward-block-name")).addLore(""); - rewardBlockName.addAutomaticLore("&f", 30, "The name of the reward block when it's shuffling."); - - ItemBuilder rewardBlockWaitingName = new ItemBuilder(XMaterial.PAPER, 1); - rewardBlockWaitingName.setDisplayName("&areward-block-waiting-name"); - rewardBlockWaitingName.addLore(getcVal()).addLore("&7" + getString("reward-block-waiting-name")).addLore(""); - rewardBlockWaitingName.addAutomaticLore("&f", 30, "The name of the reward block while it's waiting for the player to select all their rewards."); - - ItemBuilder rewardBlockUnlockName = new ItemBuilder(XMaterial.PAPER, 1); - rewardBlockUnlockName.setDisplayName("&areward-block-unlock-name"); - rewardBlockUnlockName.addLore(getcVal()).addLore("&7" + getString("reward-block-unlock-name")).addLore(""); - rewardBlockUnlockName.addAutomaticLore("&f", 30, "The name of the reward block when the user is supposed to get their final reward."); - - ib.setItem(19, coverBlockName); - ib.setItem(20, coverBlockLore); - - ib.setItem(22, rewardBlock); - ib.setItem(23, rewardBlockWaitingName); - ib.setItem(24, rewardBlockName); - ib.setItem(25, rewardBlockUnlockName); - - ib.open(); - - putInMenu(); - } - - @Override - public void handleClick(int slot) { - switch (slot) { - case 0: - up(); - break; - case 2: - new InputMenu(getCc(), getP(), "inv-name", getString("inv-name"), String.class, this); - break; - case 4: - new InputMenu(getCc(), getP(), "inventory-rows", getString("inventory-rows"), Integer.class, this); - break; - case 5: - new InputMenu(getCc(), getP(), "minimum-rewards", getString("minimum-rewards"), Integer.class, this); - break; - case 6: - new InputMenu(getCc(), getP(), "maximum-rewards", getString("maximum-rewards"), Integer.class, this); - break; - case 7: - new InputMenu(getCc(), getP(), "random-display-duration", getString("random-display-duration"), - "How many ticks the random display of green grass plane will run for.", Integer.class, this); - break; - case 11: - boolean b = !Boolean.parseBoolean(getString("count")); - fc.set(getPath("count"), b); - getIb().setItem(20, - new ItemBuilder(b ? XMaterial.LIME_WOOL : XMaterial.RED_WOOL, 1).setDisplayName("&acount") - .setLore(getcVal() + b).addLore("").addLore("&7Do the 'cover-block's display numbers?")); - break; - case 12: - new InputMenu(getCc(), getP(), "cover-block", getString("cover-block"), "Formatted: MATERIAL;DURABILITY", - String.class, this, true); - break; - case 14: - new InputMenu(getCc(), getP(), "tick-sound", getString("ticks-sound"), - "Set to 'none' to have no sound. Formatted: SOUND, VOLUME, PITCH", - String.class, this, true); - break; - case 15: - new InputMenu(getCc(), getP(), "click-sound", getString("click-sound"), - "Set to 'none' to have no sound. Formatted: SOUND, VOLUME, PITCH", - String.class, this, true); - break; - case 16: - new InputMenu(getCc(), getP(), "uncover-sound", getString("uncover-sound"), - "Set to 'none' to have no sound. Formatted: SOUND, VOLUME, PITCH", String.class, this, true); - break; - case 19: - new InputMenu(getCc(), getP(), "cover-block-name", getString("cover-block-name"), - String.class, this); - break; - case 20: - new InputMenu(getCc(), getP(), "cover-block-lore", getString("cover-block-lore"), - "User %remaining-clicks% for the amount of rewards left.", String.class, this); - break; - case 22: - new InputMenu(getCc(), getP(), "reward-block", getString("reward-block"), - "The name of the material of the reward block!", String.class, this, true); - break; - case 23: - new InputMenu(getCc(), getP(), "reward-block-waiting-name", getString("reward-block-waiting-name"), - String.class, this); - break; - case 24: - new InputMenu(getCc(), getP(), "reward-block-name", getString("reward-block-name"), - String.class, this); - break; - case 25: - new InputMenu(getCc(), getP(), "reward-block-unlock-name", getString("reward-block-unlock-name"), - String.class, this); - break; - } - } - - // - // ib.setItem(19, coverBlockName); - // ib.setItem(20, coverBlockLore); - // - // ib.setItem(22, rewardBlock); - // ib.setItem(23, rewardBlockWaitingName); - // ib.setItem(24, rewardBlockName); - // ib.setItem(25, rewardBlockUnlockName); - - @Override - public boolean handleInput(String value, String input) { - Object type = getInputMenu().getType(); - if (type == Integer.class) { - if (Utils.isInt(input)) { - fc.set(getPath(value), Integer.parseInt(input)); - ChatUtils.msgSuccess(getP(), "Set " + value + " to '" + input + "'"); - return true; - } else { - ChatUtils.msgError(getP(), "This is not a valid number, please try again."); - } - } else if (type == Boolean.class) { - if (Utils.isBoolean(input)) { - fc.set(getPath(value), Boolean.parseBoolean(input)); - ChatUtils.msgSuccess(getP(), "Set " + value + " to '" + input + "'"); - return true; - } else { - ChatUtils.msgError(getP(), "This is not a valid true / false value, please try again."); - } - } else { - - if ((value.equalsIgnoreCase("tick-sound") || value.equalsIgnoreCase("click-sound") || - value.equalsIgnoreCase("uncover-sound")) && - (input.equalsIgnoreCase("null") || input.equalsIgnoreCase("none"))) { - fc.set(getPath(value), null); - } - - fc.set(getPath(value), input); - ChatUtils.msgSuccess(getP(), "Set " + value + " to '" + input + "'"); - return true; - } - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/crateanimations/IGCAnimEnclose.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/crateanimations/IGCAnimEnclose.java deleted file mode 100644 index 6eca848..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/crateanimations/IGCAnimEnclose.java +++ /dev/null @@ -1,122 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.crates.crateanimations; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.types.animations.CrateAnimationType; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.inputmenus.InputMenu; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.Utils; -import org.bukkit.entity.Player; - -/** - * Created by ztowne13 on 7/6/16. - *

- * inv-name: '&8&l> &6&l%crate%' - * inventory-rows: 2 - * fill-block: STAINED_GLASS_PANE;1 - * tick-sound: ENTITY_PLAYER_BIG_FALL, 5, 5 - * update-speed: 5 - * reward-amount: 1 - */ -public class IGCAnimEnclose extends IGCAnimation { - public IGCAnimEnclose(SpecializedCrates cc, Player p, IGCMenu lastMenu) { - super(cc, p, lastMenu, "&7&l> &6&lEnclose Animation", CrateAnimationType.INV_ENCLOSE); - } - - @Override - public void openMenu() { - - InventoryBuilder ib = createDefault(18); - - - ib.setItem(0, IGCDefaultItems.EXIT_BUTTON.getIb()); - ib.setItem(2, - new ItemBuilder(XMaterial.BOOK).setDisplayName("&ainv-name").addLore(getcVal() + getString("inv-name")) - .addLore("").addAutomaticLore("&f", 30, - "The name of the inventory when the animation runs. This is overwritten by the crate's 'inv-name' value, if it exists.")); - ib.setItem(4, new ItemBuilder(XMaterial.PAPER).setDisplayName("&ainventory-rows") - .addLore(getcVal()).addLore("&7" + getString("inventory-rows")).addLore("") - .addAutomaticLore("&f", 30, - "The amount of rows in addition to the center row, both top and bottom. Meaning, to have 3 rows TOTAL, this value would be 1: 1 row up + 1 row down + center row.")); - ib.setItem(5, new ItemBuilder(XMaterial.PAPER).setDisplayName("&aupdate-speed") - .addLore(getcVal()).addLore("&7" + getString("update-speed")).addLore("") - .addAutomaticLore("&f", 30, - "The delay between each frame (the speed at which the animation will update and play).")); - ib.setItem(6, new ItemBuilder(XMaterial.PAPER).setDisplayName("&areward-amount") - .addLore(getcVal()).addLore("&7" + getString("reward-amount")).addLore("") - .addAutomaticLore("&f", 30, - "The amount of rewards that the player will receive from the crate. Must be an odd number of rewards, otherwise it will be rounded up.")); - ib.setItem(11, new ItemBuilder(XMaterial.NOTE_BLOCK).setDisplayName("&atick-sound") - .addLore(getcVal()).addLore("&7" + getString("tick-sound")).addLore("").addAutomaticLore("&f", 30, - "The sound that is played every time the inventory updates. Set to 'none' to have no sound.")); - ib.setItem(14, new ItemBuilder(XMaterial.ENDER_CHEST).setDisplayName("&afill-block") - .addLore(getcVal()).addLore("&7" + getString("fill-block")).addLore("") - .addAutomaticLore("&f", 30, "The block that will fill the empty space in the animation.")); - - getIb().open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - switch (slot) { - case 0: - up(); - break; - case 2: - new InputMenu(getCc(), getP(), "inv-name", getString("inv-name"), "The name of the inventory", String.class, - this); - break; - case 4: - new InputMenu(getCc(), getP(), "inventory-rows", getString("inventory-rows"), - "The amount of rows in addition to the center row, both top and bottom. Meaning, to have 3 rows TOTAL, this value would be 1: 1 row up + 1 row down + center row.", - Integer.class, this); - break; - case 5: - new InputMenu(getCc(), getP(), "update-speed", getString("minimum-rewards"), - "How fast each reward disappears (in ticks).", Integer.class, this); - break; - case 6: - new InputMenu(getCc(), getP(), "reward-amount", getString("maximum-rewards"), - "The amount of rewards that are left displayed and given to the player (must be an odd number).", - Integer.class, this); - break; - case 11: - new InputMenu(getCc(), getP(), "tick-sound", getString("tick-sound"), - "Set to 'none' to have no sound. Formatted: SOUND, PITCH, VOLUME. The sound played on every update.", - String.class, this, true); - break; - case 14: - new InputMenu(getCc(), getP(), "fill-block", getString("fill-block"), - "Formatted: MATERIAL;DURABILITY. The block that fills the empty spots", String.class, this, true); - break; - } - } - - @Override - public boolean handleInput(String value, String input) { - Object type = getInputMenu().getType(); - if (type == Integer.class) { - if (Utils.isInt(input)) { - fc.set(getPath(value), Integer.parseInt(input)); - ChatUtils.msgSuccess(getP(), "Set " + value + " to '" + input + "'"); - return true; - } else { - ChatUtils.msgError(getP(), "This is not a valid number, please try again."); - } - } else { - if (value.equalsIgnoreCase("tick-sound") && - (input.equalsIgnoreCase("null") || input.equalsIgnoreCase("none"))) { - fc.set(getPath(value), null); - } - fc.set(getPath(value), input); - ChatUtils.msgSuccess(getP(), "Set " + value + " to '" + input + "'"); - return true; - } - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/crateanimations/IGCAnimMenu.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/crateanimations/IGCAnimMenu.java deleted file mode 100644 index 6c60d9f..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/crateanimations/IGCAnimMenu.java +++ /dev/null @@ -1,99 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.crates.crateanimations; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.types.animations.CrateAnimationType; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.inputmenus.InputMenu; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.Utils; -import org.bukkit.entity.Player; - -/** - * Created by ztowne13 on 7/6/16. - *

- * inv-name: '&8&l> &6&l%crate%' - * inventory-rows: 3 - * minimum-rewards: 1 - * maximum-rewards: 8 - */ -public class IGCAnimMenu extends IGCAnimation { - public IGCAnimMenu(SpecializedCrates cc, Player p, IGCMenu lastMenu) { - super(cc, p, lastMenu, "&7&l> &6&lMenu Animation", CrateAnimationType.INV_MENU); - } - - @Override - public void openMenu() { - - InventoryBuilder ib = createDefault(9); - - - ib.setItem(0, IGCDefaultItems.EXIT_BUTTON.getIb()); - ib.setItem(2, - new ItemBuilder(XMaterial.BOOK).setDisplayName("&ainv-name").addLore(getcVal() + getString("inv-name")) - .addLore("").addAutomaticLore("&f", 30, - "The name of the inventory when the animation runs. This is overwritten by the crate's 'inv-name' value, if it exists.")); - ib.setItem(4, new ItemBuilder(XMaterial.PAPER).setDisplayName("&ainventory-rows") - .addLore(getcVal()).addLore("&7" + getString("inventory-rows")).addLore("") - .addAutomaticLore("&f", 30, - "The amount of rows that the inventory will have for random items to spawn on.")); - ib.setItem(5, new ItemBuilder(XMaterial.PAPER).setDisplayName("&aminimum-rewards") - .addLore(getcVal()).addLore("&7" + getString("minimum-rewards")).addLore("") - .addAutomaticLore("&f", 30, - "The minimum amount of rewards that could appear in the menu. Set to the same amount as the maximum-rewards for it to be the same amount every time.")); - ib.setItem(6, new ItemBuilder(XMaterial.PAPER).setDisplayName("&amaximum-rewards") - .addLore(getcVal()).addLore("&7" + getString("maximum-rewards")).addLore("") - .addAutomaticLore("&f", 30, - "The maximum amount of rewards that could appear in the menu. Set to the same amount as the minimum-rewards for it to be the same amount every time.")); - - getIb().open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - switch (slot) { - case 0: - up(); - break; - case 2: - new InputMenu(getCc(), getP(), "inv-name", getString("inv-name"), "The name of the inventory", String.class, - this); - break; - case 4: - new InputMenu(getCc(), getP(), "inventory-rows", getString("inventory-rows"), - "How many rows the menu crate has.", Integer.class, this); - break; - case 5: - new InputMenu(getCc(), getP(), "minimum-rewards", getString("minimum-rewards"), - "The low end of the random amount of rewards that will spawn.", Integer.class, this); - break; - case 6: - new InputMenu(getCc(), getP(), "maximum-rewards", getString("maximum-rewards"), - "The high end of the random amount of rewards that will spawn.", Integer.class, this); - break; - } - } - - @Override - public boolean handleInput(String value, String input) { - Object type = getInputMenu().getType(); - if (type == Integer.class) { - if (Utils.isInt(input)) { - fc.set(getPath(value), Integer.parseInt(input)); - ChatUtils.msgSuccess(getP(), "Set " + value + " to '" + input + "'"); - return true; - } else { - ChatUtils.msgError(getP(), "This is not a valid number, please try again."); - } - } else { - fc.set(getPath(value), input); - ChatUtils.msgSuccess(getP(), "Set " + value + " to '" + input + "'"); - return true; - } - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/crateanimations/IGCAnimOpenChest.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/crateanimations/IGCAnimOpenChest.java deleted file mode 100644 index 7a06171..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/crateanimations/IGCAnimOpenChest.java +++ /dev/null @@ -1,126 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.crates.crateanimations; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.types.animations.CrateAnimationType; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.inputmenus.InputMenu; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.Utils; -import org.bukkit.entity.Player; - -/** - * Created by ztowne13 on 7/6/16. - *

- * inv-name: '&8&l> &6&l%crate%' - * inventory-rows: 2 - * fill-block: STAINED_GLASS_PANE;1 - * tick-sound: ENTITY_PLAYER_BIG_FALL, 5, 5 - * update-speed: 5 - * reward-amount: 1 - */ -public class IGCAnimOpenChest extends IGCAnimation { - public IGCAnimOpenChest(SpecializedCrates cc, Player p, IGCMenu lastMenu) { - super(cc, p, lastMenu, "&7&l> &6&lOpenChest Animation", CrateAnimationType.BLOCK_CRATEOPEN); - } - - @Override - public void openMenu() { - - InventoryBuilder ib = createDefault(9); - - - ib.setItem(0, IGCDefaultItems.EXIT_BUTTON.getIb()); - - ib.setItem(3, new ItemBuilder(XMaterial.PAPER).setDisplayName("&achest-open-duration") - .addLore(getcVal()).addLore("&7" + getString("chest-open-duration")).addLore("") - .addAutomaticLore("&f", 30, "How long the chest will appear to be open for")); - ib.setItem(4, new ItemBuilder(XMaterial.REDSTONE).setDisplayName("&aearly-reward-hologram") - .addLore(getcVal()).addLore("&7" + getString("early-reward-hologram")) - .addLore("") - .addAutomaticLore("&f", 30, "Should the reward-hologram play early with the animation for added effect?") - .addLore("").addAutomaticLore("&e", 30, "Has no effect if reward-holo-attach-to-item is set to TRUE.")); - ib.setItem(5, new ItemBuilder(XMaterial.REPEATER).setDisplayName("&areward-hologram-delay") - .addLore(getcVal()).addLore("&7" + getString("reward-hologram-delay")) - .addLore("").addAutomaticLore("&f", 30, - "If displaying the early-reward-hologram, how long to wait for it to appear? Setting this to a value of 9 plays about when the item falls down.") - .addLore("").addAutomaticLore("&e", 30, "Has no effect if reward-holo-attach-to-item is set to TRUE.")); - - ItemBuilder attachTo = new ItemBuilder(XMaterial.DIAMOND); - attachTo.setDisplayName("&areward-holo-attach-to-item"); - attachTo.addLore("&7Current value:").addLore("&7" + getString("reward-holo-attach-to-item")); - attachTo.addLore("").addAutomaticLore("&f", 30, - "Instead of just playing the reward hologram early or normally, have it attach to the actual item to have a nice bounce effect."); - ib.setItem(6, attachTo); - - ItemBuilder earlyActions = new ItemBuilder(XMaterial.FIREWORK_ROCKET); - earlyActions.setDisplayName("&aearly-open-actions"); - earlyActions.addLore("&7Current value:").addLore("&7" + getString("early-open-actions")); - earlyActions.addLore("").addAutomaticLore("&f", 30, - "Play the fireworks, sounds, actions, and particles when the crate is OPENED as opposed to after it closes."); - ib.setItem(7, earlyActions); - - getIb().open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - switch (slot) { - case 0: - up(); - break; - case 3: - new InputMenu(getCc(), getP(), "chest-open-duration", getString("chest-open-duration"), - "How long the chest will appear to be open for, in ticks (20 ticks per sec).", Integer.class, this); - break; - case 4: - fc.set(getPath("early-reward-hologram"), !fc.getBoolean(getPath("early-reward-hologram"))); - open(); - break; - case 5: - new InputMenu(getCc(), getP(), "reward-hologram-delay", getString("reward-hologram-delay"), - "How long to delay (or not to delay) the early-reward-hologram from appearing.", - Integer.class, this); - break; - case 6: - fc.set(getPath("reward-holo-attach-to-item"), !fc.getBoolean(getPath("reward-holo-attach-to-item"))); - open(); - break; - case 7: - fc.set(getPath("early-open-actions"), !fc.getBoolean(getPath("early-open-actions"))); - open(); - break; - } - } - - @Override - public boolean handleInput(String value, String input) { - Object type = getInputMenu().getType(); - if (type == Integer.class) { - if (Utils.isInt(input)) { - fc.set(getPath(value), Integer.parseInt(input)); - ChatUtils.msgSuccess(getP(), "Set " + value + " to '" + input + "'"); - return true; - } else { - ChatUtils.msgError(getP(), "This is not a valid number, please try again."); - } - } else if (type == Boolean.class) { - if (Utils.isBoolean(input)) { - fc.set(getPath(value), Boolean.parseBoolean(input)); - ChatUtils.msgSuccess(getP(), "Set " + value + " to '" + input + "'"); - return true; - } else { - ChatUtils.msgError(getP(), "This is not a valid true/false value, please try again."); - } - } else { - fc.set(getPath(value), input); - ChatUtils.msgSuccess(getP(), "Set " + value + " to '" + input + "'"); - return true; - } - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/crateanimations/IGCAnimRoulette.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/crateanimations/IGCAnimRoulette.java deleted file mode 100644 index 9a8b554..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/crateanimations/IGCAnimRoulette.java +++ /dev/null @@ -1,194 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.crates.crateanimations; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.types.animations.CrateAnimationType; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.inputmenus.InputMenu; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.Utils; -import org.bukkit.entity.Player; - -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - -/** - * Created by ztowne13 on 7/6/16. - *

- * inv-name: '&8&l> &6&l%crate%' - * tick-sound: ENTITY_PLAYER_BIG_FALL, 5, 5 - * tile-update-ticks: 2 - * tick-speed-per-run: 3 - * final-crate-tick-length: 11 - * random-blocks: - * - STAINED_GLASS_PANE;1 - * - STAINED_GLASS_PANE;2 - * - STAINED_GLASS_PANE;3 - * - STAINED_GLASS_PANE;4 - * - STAINED_GLASS_PANE;5 - * - STAINED_GLASS_PANE;6 - * - STAINED_GLASS_PANE;7 - * - STAINED_GLASS_PANE;8 - * - STAINED_GLASS_PANE;9 - */ -public class IGCAnimRoulette extends IGCAnimation { - public IGCAnimRoulette(SpecializedCrates cc, Player p, IGCMenu lastMenu) { - super(cc, p, lastMenu, "&7&l> &6&lRoulette Animation", CrateAnimationType.INV_ROULETTE); - } - - @Override - public void openMenu() { - - InventoryBuilder ib = createDefault(18); - - - ib.setItem(0, IGCDefaultItems.EXIT_BUTTON.getIb()); - ib.setItem(2, - new ItemBuilder(XMaterial.BOOK).setDisplayName("&ainv-name").addLore(getcVal()) - .addLore("&7" + getString("inv-name")).addLore("").addAutomaticLore("&f", 30, - "The name of the inventory when the animation runs. This is overwritten by the crate's 'inv-name' value, if it exists.")); - ib.setItem(4, new ItemBuilder(XMaterial.PAPER).setDisplayName("&atick-speed-per-run") - .addLore(getcVal()).addLore("&7" + getString("tick-speed-per-run")).addLore("") - .addAutomaticLore("&f", 30, - "The rate at which the rolling items will slow down. A lower value will make the speed of the roll" + - " take longer to slow down while a higher value will make the roll slow down much quicker.")); - ib.setItem(5, new ItemBuilder(XMaterial.PAPER).setDisplayName("&afinal-crate-tick-length") - .addLore(getcVal()).addLore("&7" + getString("final-crate-tick-length")).addLore("") - .addAutomaticLore("&f", 30, - "The speed the animation must reach to end. A lower value will result in the animation ending while" + - " the roll is still moving quickly, and a higher value will make it end when it is rolling slower.")); - ib.setItem(6, new ItemBuilder(XMaterial.PAPER).setDisplayName("&atile-update-ticks") - .addLore(getcVal()).addLore("&7" + getString("tile-update-ticks")).addLore("").addAutomaticLore("&f", 30, - "The delay between when the random-blocks update. A lower will make the random-blocks update very " + - "quickly, and a higher value update slowly.")); - ib.setItem(11, new ItemBuilder(XMaterial.NOTE_BLOCK).setDisplayName("&atick-sound") - .addLore(getcVal()).addLore("&7" + getString("tick-sound")).addLore("") - .addAutomaticLore("&f", 30, - "The sound that is played every time the inventory updates. Set to 'none' to have no sound.")); - - ItemBuilder fillerBlocks = - new ItemBuilder(XMaterial.ENDER_CHEST).setDisplayName("&aAdd new random-blocks").setLore("&7Current values: "); - for (String s : fc.getStringList(getPath("random-blocks"))) { - fillerBlocks.addLore("&7- " + s); - } - - fillerBlocks.addLore("").addAutomaticLore("&f", 30, "The blocks that will fill empty space in the animation. Formatted Material;Data"); - ib.setItem(14, fillerBlocks); - ib.setItem(15, fillerBlocks.setDisplayName("&aRemove existing random-blocks")); - - getIb().open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - switch (slot) { - case 0: - up(); - break; - case 2: - new InputMenu(getCc(), getP(), "inv-name", getString("inv-name"), "The name of the inventory", String.class, - this); - break; - case 4: - new InputMenu(getCc(), getP(), "tick-speed-per-run", getString("tick-speed-per-run"), - "How fast the animation updates the rewards.", Double.class, this); - break; - case 5: - new InputMenu(getCc(), getP(), "final-crate-tick-length", getString("final-crate-tick-length"), - "How long the animation will display.", Double.class, this); - break; - case 6: - new InputMenu(getCc(), getP(), "tile-update-ticks", getString("tile-update-ticks"), - "How fast, in ticks, the filler-blocks will update", Integer.class, this); - break; - case 11: - new InputMenu(getCc(), getP(), "tick-sound", getString("tick-sound"), - "Set to 'none' to have no sound. Formatted 'SOUND, PITCH, VOLUME' (without the quotes). Click for a list of sounds -> https://www.spigotmc.org/wiki/cc-sounds-list/", - String.class, this, true); - break; - case 14: - new InputMenu(getCc(), getP(), "add random-blocks", "Formated: MATERIAL;ID", String.class, this, true); - break; - case 15: - new InputMenu(getCc(), getP(), "remove random-blocks", "Existing filler-blocks: " + - (fc.contains(crateAnimationType.getPrefix() + ".filler-blocks") ? - fc.getStringList(crateAnimationType.getPrefix() + ".filler-blocks") : "none"), String.class, this, true); - break; - } - } - - @Override - public boolean handleInput(String value, String input) { - Object type = getInputMenu().getType(); - if (type == Double.class) { - if (Utils.isDouble(input)) { - fc.set(getPath(value), Double.valueOf(input)); - ChatUtils.msgSuccess(getP(), "Set " + value + " to '" + input + "'"); - return true; - } else { - ChatUtils.msgError(getP(), "This is not a valid decimal value, please try again."); - } - } else if (type == Integer.class) { - if (Utils.isInt(input)) { - fc.set(getPath(value), Integer.parseInt(input)); - ChatUtils.msgSuccess(getP(), "Set " + value + " to '" + input + "'"); - return true; - } else { - ChatUtils.msgError(getP(), "This is not a valid number, please try again."); - } - } else { - if (value.equalsIgnoreCase("add random-blocks")) { - Optional optional = XMaterial.matchXMaterial(input.replace(";", ":")); - if (optional.isPresent()) { - XMaterial dm = optional.get(); - List currentList = - fc.contains(getPath(value.substring(4))) ? fc.getStringList(getPath(value.substring(4))) : - new ArrayList<>(); - currentList.add(dm.name()); - fc.set(getPath(value.substring(4)), currentList); - return true; - } else { - ChatUtils.msgError(getP(), input + " does not have a valid material or is not formatted MATERIAL;DATA"); - } - } else if (value.equalsIgnoreCase("remove random-blocks")) { - if (fc.contains(getPath(value.substring(7)))) { - boolean found = false; - List newList = new ArrayList<>(); - for (String s : fc.getStringList(getPath(value.substring(7)))) { - if (s.equalsIgnoreCase(input)) { - found = true; - } else { - newList.add(s); - } - } - - if (found) { - ChatUtils.msgSuccess(getP(), "Removed the " + input + " value."); - fc.set(getPath(value.substring(7)), newList); - return true; - } else { - ChatUtils.msgError(getP(), input + " does not exist in the filler / random blocks: " + - fc.getStringList(getPath(value.substring(7)))); - } - } else { - ChatUtils.msgError(getP(), "No filler blocks currently exist to remove."); - return true; - } - } else { - if (value.equalsIgnoreCase("tick-sound") && - (input.equalsIgnoreCase("null") || input.equalsIgnoreCase("none"))) { - fc.set(getPath(value), null); - } - fc.set(getPath(value), input); - ChatUtils.msgSuccess(getP(), "Set " + value + " to '" + input + "'"); - return true; - } - } - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/crateanimations/IGCAnimation.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/crateanimations/IGCAnimation.java deleted file mode 100644 index 74f763f..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/crateanimations/IGCAnimation.java +++ /dev/null @@ -1,32 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.crates.crateanimations; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.types.animations.CrateAnimationType; -import me.ztowne13.customcrates.interfaces.files.FileHandler; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; - -/** - * Created by ztowne13 on 7/6/16. - */ -public abstract class IGCAnimation extends IGCMenu { - FileHandler fu; - FileConfiguration fc; - CrateAnimationType crateAnimationType; - - public IGCAnimation(SpecializedCrates cc, Player p, IGCMenu lastMenu, String inventoryName, CrateAnimationType crateAnimationType) { - super(cc, p, lastMenu, inventoryName); - this.crateAnimationType = crateAnimationType; - this.fu = cc.getCrateConfigFile(); - this.fc = fu.get(); - } - - public String getString(String path) { - return fc.getString(getPath(path)); - } - - public String getPath(String value) { - return crateAnimationType.getPrefix() + "." + value; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/previeweditor/IGCCratePreviewEditor.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/previeweditor/IGCCratePreviewEditor.java deleted file mode 100644 index 4290609..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/previeweditor/IGCCratePreviewEditor.java +++ /dev/null @@ -1,121 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.crates.previeweditor; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import me.ztowne13.customcrates.crates.options.rewards.displaymenu.custom.CustomRewardDisplayer; -import me.ztowne13.customcrates.crates.options.rewards.displaymenu.custom.DisplayPage; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.crates.IGCMenuCrate; -import me.ztowne13.customcrates.interfaces.items.SaveableItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - -public class IGCCratePreviewEditor extends IGCMenuCrate { - public static String INV_NAME = "&c&lClose to Save"; - - CustomRewardDisplayer customRewardDisplayer; - DisplayPage page; - - public IGCCratePreviewEditor(SpecializedCrates specializedCrates, Player player, Crate crate, IGCMenu lastMenu, DisplayPage page) { - super(specializedCrates, player, lastMenu, INV_NAME, crate); - - this.customRewardDisplayer = (CustomRewardDisplayer) getCrates().getSettings().getDisplayer(); - this.page = page; - } - - @Override - public void openMenu() { - InventoryBuilder ib = page.buildInventoryBuilder(getP(), true, "&c&lClose to leave and Save", null, false); - - setIb(ib); - ib.open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - manageClick(slot, false, null); - } - - public void manageClick(int slot, boolean isDrag, ItemStack dragMaterial) { - int x = slot / 9; - int y = slot % 9; - - if (page.getRewards()[x][y] == null && page.getBuilders()[x][y] == null) { - if ((getP().getItemOnCursor() == null || getP().getItemOnCursor().getType().equals(Material.AIR)) && !isDrag) { - new IGCCratePreviewRewards(getCc(), getP(), this, getCrates(), 1, slot, customRewardDisplayer).open(); - } else { - SaveableItemBuilder builder = new SaveableItemBuilder(isDrag ? dragMaterial : getP().getItemOnCursor()); - - page.getBuilders()[x][y] = builder; - msg("ITEM added."); - - msgBreak(); - getIb().clear(); - page.buildInventoryBuilder(getP(), true, INV_NAME, getIb(), false); - } - } else { - boolean isReward = page.getRewards()[x][y] != null; - - if (isReward) { - page.getRewards()[x][y] = null; - msg("REWARD removed."); - } else { - getP().getInventory().addItem(page.getBuilders()[x][y].getStack()); - page.getBuilders()[x][y] = null; - msg("ITEM returned."); - } - - if (!isDrag && (getP().getItemOnCursor() != null && !getP().getItemOnCursor().getType().equals(Material.AIR))) { - SaveableItemBuilder builder = new SaveableItemBuilder(isDrag ? dragMaterial : getP().getItemOnCursor()); - - page.getBuilders()[x][y] = builder; - msg("ITEM added."); - } - - msgBreak(); - getIb().clear(); - page.buildInventoryBuilder(getP(), true, INV_NAME, getIb(), false); - } - } - - public void close() { - - } - - @Override - public boolean handleInput(String value, String input) { - String[] args = value.split(" "); - if (args.length == 3) { - if (args[0].equalsIgnoreCase("set") && args[1].equalsIgnoreCase("reward")) { - Integer slot = Integer.parseInt(args[2]); - - Reward reward = getCs().getReward().getByName(input); - - int x = slot / 9; - int y = slot % 9; - - page.getRewards()[x][y] = reward; - msg("REWARD added."); - open(); - } - } - return false; - } - - public void msg(String s) { - ChatUtils.msg(getP(), "&2&l!! &a" + s); - } - - public void msgBreak() { - ChatUtils.msg(getP(), "&2*"); - } - - public CustomRewardDisplayer getCustomRewardDisplayer() { - return customRewardDisplayer; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/previeweditor/IGCCratePreviewMenu.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/previeweditor/IGCCratePreviewMenu.java deleted file mode 100644 index fc67c00..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/previeweditor/IGCCratePreviewMenu.java +++ /dev/null @@ -1,212 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.crates.previeweditor; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.options.rewards.displaymenu.RewardDisplayType; -import me.ztowne13.customcrates.crates.options.rewards.displaymenu.custom.CustomRewardDisplayer; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCListSelector; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.crates.IGCMenuCrate; -import me.ztowne13.customcrates.interfaces.igc.inputmenus.InputMenu; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; - -import java.util.ArrayList; -import java.util.Arrays; - -public class IGCCratePreviewMenu extends IGCMenuCrate { - boolean isCustom; - - public IGCCratePreviewMenu(SpecializedCrates specializedCrates, Player player, Crate crate, IGCMenu lastMenu) { - super(specializedCrates, player, lastMenu, "&7&l> &6&lReward Preview Menu", crate); - - isCustom = getCrates().getSettings().getRewardDisplayType().equals(RewardDisplayType.CUSTOM); - } - - @Override - public void openMenu() { - InventoryBuilder ib = createDefault(18); - - ItemBuilder nameEditor = new ItemBuilder(XMaterial.PAPER, 1); - nameEditor.setDisplayName("&aInventory Name"); - nameEditor.addLore("&7Current Value:").addLore("&f" + getCrates().getSettings().getDisplayer().getInvName()); - nameEditor.addLore("").addAutomaticLore("&7", 30, "Edit the name of the reward preview menu."); - - ItemBuilder typeEditor = new ItemBuilder(XMaterial.BEACON, 1); - typeEditor.setDisplayName("&aPreview Menu Type"); - typeEditor.addLore("&7Current Value:").addLore("&f" + getCrates().getSettings().getRewardDisplayType().name()); - typeEditor.addLore("").addAutomaticLore("&7", 30, - "Edit the type of display the reward preview menu will be: from sorted to completely custom made!"); - - ItemBuilder requirePermissions = new ItemBuilder(XMaterial.BOOK); - requirePermissions.setDisplayName("&aRequire Permission"); - requirePermissions.addLore("&7Current Value:"); - requirePermissions.addLore("&f" + getCrates().getSettings().getDisplayer().isRequirePermForPreview()); - requirePermissions.addLore("").addAutomaticLore("&7", 30, - "Should the permission that is required to open the crate ALSO be required to open the reward preview menu? You would set this to 'true' " + - "if you want players who don't have the correct permission for the crate also to not be able to preview the rewards in the crate."); - - ItemBuilder forward = new ItemBuilder(XMaterial.ARROW, 1); - ItemBuilder backward = new ItemBuilder(XMaterial.ARROW, 1); - - ItemBuilder customEditor = new ItemBuilder(isCustom ? XMaterial.LADDER : XMaterial.RED_DYE, 1); - customEditor.setDisplayName((isCustom ? "&a" : "&4") + "Edit the Reward Preview"); - if (isCustom) { - customEditor.addAutomaticLore("&7", 30, "Edit the reward preview menu to be exactly how you want!"); - customEditor.addLore("") - .addAutomaticLore("&e", 30, "PLEASE READ THE 'HELP' MESSAGE THAT APPEARS TO LEARN HOW TO CONFIGURE IT."); - - backward.setDisplayName("&aSelect the backward page button"); - backward.addAutomaticLore("&7", 30, - "Put an item in preview-menu editor that will be the backward button. Select that exact item here to assign it to be the 'backward page' button."); - - forward.setDisplayName("&aSelect the forward page button"); - forward.addAutomaticLore("&7", 30, - "Put an item in preview-menu editor that will be the forward button. Select that item exact here to assign it to be the 'forward page' button."); - } else { - customEditor.addAutomaticLore("&c", 30, - "To edit the preview menu manually, please set the Preview Menu Type to CUSTOM."); - - forward.setDisplayName("&cSelect the forward page button"); - forward.addAutomaticLore("&c", 30, - "To edit the forward button manually, please set the Preview Menu Type to CUSTOM."); - - backward.setDisplayName("&cSelect the backward page button"); - backward.addAutomaticLore("&c", 30, - "To edit the backward button manually, please set the Preview Menu Type to CUSTOM."); - } - - ib.setItem(9, IGCDefaultItems.EXIT_BUTTON.getIb()); - ib.setItem(0, IGCDefaultItems.SAVE_ONLY_BUTTON.getIb()); - ib.setItem(2, nameEditor); - ib.setItem(3, requirePermissions); - ib.setItem(4, typeEditor); - ib.setItem(6, customEditor); - ib.setItem(15, forward); - ib.setItem(16, backward); - - ib.open(); - - putInMenu(); - - } - - @Override - public void handleClick(int slot) { - switch (slot) { - case 9: - up(); - break; - case 0: - getCrates().getSettings().getFileHandler().save(); - ChatUtils.msgSuccess(getP(), "Saved!"); - break; - case 2: - new InputMenu(getCc(), getP(), "inventory name", getCrates().getSettings().getDisplayer().getInvName(), - String.class, - this, false); - break; - case 3: - getCrates().getSettings().getDisplayer().setRequirePermForPreview(!getCrates().getSettings().getDisplayer().isRequirePermForPreview()); - open(); - break; - case 4: - new IGCListSelector(getCc(), getP(), this, "preview menu type", Arrays.asList(RewardDisplayType.values()), - XMaterial.PAPER, 1, RewardDisplayType.descriptions()).open(); - break; - case 6: - case 15: - case 16: - if (isCustom) { - CustomRewardDisplayer cdr; - try { - cdr = (CustomRewardDisplayer) getCrates().getSettings().getDisplayer(); - } catch (Exception exc) { - ChatUtils.msgError(getP(), "Please SAVE and RELOAD before editing."); - break; - } - - if (slot == 6) { - new IGCCratePreviewPageChooser(getCc(), getP(), getCrates(), this, 1).open(); - for (int i = 0; i < 30; i++) - ChatUtils.msg(getP(), ""); - - ChatUtils.msg(getP(), "&4&lHow to configure the CUSTOM preview menu."); - ChatUtils.msg(getP(), ""); - ChatUtils.msg(getP(), "&6&lCreating the menu."); - ChatUtils.msg(getP(), - "&eIt's very similar to just drag and drop but not exactly the same. Click any blank space " + - "with nothing in hand to bring up a reward selector to add a reward to that spot. This is just a convenience" + - " so that if you edit a rewards chance, name, lore, etc. in the future it will automatically update. You can" + - " also add any normal items you want! To do this, hold an item in your hand and click or click and drag" + - " it into the slots. It does not get placed into the inventory, it simply sets the slot you clicked to that" + - " item. So if you only want one item at a slot, make sure the stack you're holding in your cursor" + - " is only 1 item, not a stack. To remove items OR rewards, just click them with a blank cursor and they'll disappear." + - " All of the items support any customizations that rewards do (names, lores, enchants, etc.)! Just make" + - " sure you customize the items before you put them in the inventory!"); - ChatUtils.msg(getP(), "&6&lMultiple page support"); - ChatUtils.msg(getP(), - "&eIn this menu, click the 'paper' to add more pages to the preview menu. This is if " + - "you have more than 54 rewards or if you want to make it really fancy!"); - ChatUtils.msg(getP(), "&6&lForward / Backwards Buttons"); - ChatUtils.msg(getP(), - "&eIf you only have one page, you can ignore all of this: these buttons are optional" + - ". To navigate between these pages, you can add forward and backwards buttons! FIRST," + - " make sure that you create the preview menu and add some item that will be the 'forward' and some item" + - " that will be the 'backwards' button (THIS MEANS DESIGN IT ALL FIRST). Then, on the previous menu," + - " click the arrow, and choose the item that will be the forward button and click the other arrow to " + - "choose the item that will be the backwards button. This assigns that specific item to be the forward" + - " or backward button - you can move it around wherever you want or have as many of them as you want!"); - ChatUtils.msg(getP(), "&c&l!! &6&lPLEASE READ THE MESSAGE ABOVE. &c&l!!"); - ChatUtils.msg(getP(), "&c&l!! &6&lPLEASE READ THE MESSAGE ABOVE. &c&l!!"); - } else if (slot == 15) { - new IGCListSelector(getCc(), getP(), this, "Forward Button", - new ArrayList<>(cdr.getItems().keySet()), XMaterial.PAPER, 1, - cdr.getDescriptors(), new ArrayList<>(cdr.getItems().values())).open(); - } else if (slot == 16) { - new IGCListSelector(getCc(), getP(), this, "Backwards Button", - new ArrayList<>(cdr.getItems().keySet()), - XMaterial.PAPER, 1, - cdr.getDescriptors(), new ArrayList<>(cdr.getItems().values())).open(); - } - } else { - ChatUtils.msgError(getP(), - "The preview menu type is not CUSTOM. If you just changed it, you need to save and reload the plugin."); - } - break; - } - } - - @Override - public boolean handleInput(String value, String input) { - FileConfiguration fc = getCs().getFileHandler().get(); - - if (value.equalsIgnoreCase("preview menu type")) { - RewardDisplayType newType = RewardDisplayType.valueOf(input); - getCrates().getSettings().setRewardDisplayType(newType); - getCrates().getSettings().getFileHandler().get().set("reward-display.type", input); - ChatUtils.msgSuccess(getP(), "PLEASE RELOAD NOW. Set the preview menu type to '" + input + "'."); - } else if (value.equalsIgnoreCase("inventory name")) { - getCrates().getSettings().getDisplayer().setName(input); - getCrates().getSettings().getFileHandler().get().set("reward-display.name", ChatUtils.fromChatColor(input)); - ChatUtils.msgSuccess(getP(), "Set the inventory name to '" + input + "'"); - return true; - } else if (value.equalsIgnoreCase("Forward Button")) { - CustomRewardDisplayer cdr = (CustomRewardDisplayer) getCrates().getSettings().getDisplayer(); - fc.set("reward-display.custom-display.nextpageitem", input); - cdr.setNextPageItem(input); - ChatUtils.msgSuccess(getP(), "Set the forward button to " + input); - } else if (value.equalsIgnoreCase("Backwards Button")) { - CustomRewardDisplayer cdr = (CustomRewardDisplayer) getCrates().getSettings().getDisplayer(); - fc.set("reward-display.custom-display.lastpageitem", input); - cdr.setPrevPageItem(input); - ChatUtils.msgSuccess(getP(), "Set the backwards button to " + input); - } - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/previeweditor/IGCCratePreviewOrRewardMenu.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/previeweditor/IGCCratePreviewOrRewardMenu.java deleted file mode 100644 index 10bee91..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/previeweditor/IGCCratePreviewOrRewardMenu.java +++ /dev/null @@ -1,60 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.crates.previeweditor; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.crates.IGCCrateRewards; -import me.ztowne13.customcrates.interfaces.igc.crates.IGCMenuCrate; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import org.bukkit.entity.Player; - -public class IGCCratePreviewOrRewardMenu extends IGCMenuCrate { - public IGCCratePreviewOrRewardMenu(SpecializedCrates specializedCrates, Player player, Crate crate, IGCMenu lastMenu) { - super(specializedCrates, player, lastMenu, "&7&l> &6&lRewards", crate); - } - - @Override - public void openMenu() { - InventoryBuilder ib = createDefault(9); - - // Reward Editor - ItemBuilder rewardEditor = new ItemBuilder(XMaterial.LIGHT_BLUE_DYE, 1); - rewardEditor.setDisplayName("&aReward Editor"); - rewardEditor.addAutomaticLore("&7", 30, "Add, remove, and edit the rewards for this crate."); - - // Reward Preview Editor - ItemBuilder rewardPreview = new ItemBuilder(XMaterial.CHEST, 1); - rewardPreview.setDisplayName("&aReward Preview Menu Editor"); - rewardPreview.addAutomaticLore("&7", 30, "Edit the reward preview menu and everything related to it."); - - ib.setItem(0, IGCDefaultItems.EXIT_BUTTON.getIb()); - ib.setItem(3, rewardEditor); - ib.setItem(5, rewardPreview); - - ib.open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - switch (slot) { - case 0: - up(); - break; - case 3: - new IGCCrateRewards(getCc(), getP(), this, getCrates(), 1).open(); - break; - case 5: - new IGCCratePreviewMenu(getCc(), getP(), getCrates(), this).open(); - break; - } - } - - @Override - public boolean handleInput(String value, String input) { - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/previeweditor/IGCCratePreviewPageChooser.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/previeweditor/IGCCratePreviewPageChooser.java deleted file mode 100644 index 8db5d10..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/previeweditor/IGCCratePreviewPageChooser.java +++ /dev/null @@ -1,137 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.crates.previeweditor; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.options.rewards.displaymenu.custom.CustomRewardDisplayer; -import me.ztowne13.customcrates.crates.options.rewards.displaymenu.custom.DisplayPage; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.InventoryUtils; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.crates.IGCMenuCrate; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.entity.Player; - -import java.util.ArrayList; -import java.util.List; - -public class IGCCratePreviewPageChooser extends IGCMenuCrate { - int page; - List values; - CustomRewardDisplayer displayer; - - public IGCCratePreviewPageChooser(SpecializedCrates specializedCrates, Player player, Crate crate, IGCMenu lastMenu, int page) { - super(specializedCrates, player, lastMenu, "&7&l> &6&lReward Preview Menu", crate); - - this.displayer = (CustomRewardDisplayer) getCrates().getSettings().getDisplayer(); - this.page = page; - - values = new ArrayList<>(); - - values.addAll(displayer.getPages().keySet()); - } - - @Override - public void openMenu() { - - int slots = Math.min(values.size() - ((page - 1) * 28), 28); - - slots = InventoryUtils.getRowsFor(2, slots) + 9; - - setInventoryName("&7&l> &6&lPreview Menu PG" + page); - InventoryBuilder ib = createDefault(slots, 18); - - ib.setItem(9, IGCDefaultItems.EXIT_BUTTON.getIb()); - ib.setItem(0, IGCDefaultItems.SAVE_ONLY_BUTTON.getIb()); - - ItemBuilder builder = new ItemBuilder(XMaterial.PAPER); - builder.setDisplayName("&aAdd a page"); - - ib.setItem(8, builder); - - int i = 10; - int toSkip = ((page - 1) * 28); - int skipped = 0; - int displayedItems = 0; - int itemNum = (page - 1) * 28; - - int added = 0; - for (Object val : values) { - if (toSkip > skipped || displayedItems >= 28) { - skipped++; - continue; - } - - if (i % 9 == 8) { - i += 2; - } - - itemNum++; - ItemBuilder item; - - item = new ItemBuilder(XMaterial.BOOK, 1).setDisplayName("&a" + val); - - item.addLore("") - .addLore("&7&oClick to edit this page."); - - added++; - - ib.setItem(i, item); - i++; - displayedItems++; - } - - if (page != 1) { - ib.setItem(2, new ItemBuilder(XMaterial.ARROW).setDisplayName("&aGo back a page")); - } - - if (((values.size() / 28) + (values.size() % 28 == 0 ? 0 : 1) != page) && values.size() != 0) { - ib.setItem(6, new ItemBuilder(XMaterial.ARROW).setDisplayName("&aGo forward a page")); - } - - ib.open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - if (slot == 0) { - getCrates().getSettings().getFileHandler().save(); - ChatUtils.msgSuccess(getP(), "Saved!"); - } else if (slot == 9) { - up(); - } else if (slot == 2 && XMaterial.ARROW.isSimilar(getIb().getInv().getItem(slot))) { - page--; - open(); - } else if (slot == 6 && XMaterial.ARROW.isSimilar(getIb().getInv().getItem(slot))) { - page++; - open(); - } else if (slot == 8) { - for (int i = 1; i < 1000; i++) { - if (!values.contains(i)) { - DisplayPage page = new DisplayPage(displayer, i); - page.load(); - displayer.getPages().put(i, page); - - new IGCCratePreviewPageChooser(getCc(), getP(), getCrates(), getLastMenu(), 1).open(); - break; - } - } - } else if (getIb().getInv().getItem(slot) != null) { - int row = slot / 9; - int slotInRow = slot % 9; - int num = ((page - 1) * 28) + ((row - 1) * 7) + (slotInRow - 1); - - int pageNum = values.get(num); - - new IGCCratePreviewEditor(getCc(), getP(), getCrates(), this, displayer.getPages().get(pageNum)).open(); - } - } - - @Override - public boolean handleInput(String value, String input) { - return true; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/previeweditor/IGCCratePreviewRewards.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/previeweditor/IGCCratePreviewRewards.java deleted file mode 100644 index ce2887a..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/crates/previeweditor/IGCCratePreviewRewards.java +++ /dev/null @@ -1,143 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.crates.previeweditor; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.options.CReward; -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import me.ztowne13.customcrates.crates.options.rewards.displaymenu.custom.CustomRewardDisplayer; -import me.ztowne13.customcrates.crates.options.rewards.displaymenu.custom.DisplayPage; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.InventoryUtils; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.crates.IGCMenuCrate; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.entity.Player; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -public class IGCCratePreviewRewards extends IGCMenuCrate { - int page; - Crate crate; - int slot; - CustomRewardDisplayer customRewardDisplayer; - - public IGCCratePreviewRewards(SpecializedCrates cc, Player p, IGCMenu lastMenu, Crate crate, int page, int slot, - CustomRewardDisplayer customRewardDisplayer) { - super(cc, p, lastMenu, "&7&l> &6&lRewards PG" + page, crate); - this.page = page; - this.crate = crate; - this.slot = slot; - this.customRewardDisplayer = customRewardDisplayer; - } - - @Override - public void openMenu() { - - int slots; - - CReward.loadAll(getCc(), getP()); - - List rewards = getUnusedRewards(); - - if (rewards.size() - ((page - 1) * 28) >= 28) { - slots = 28; - } else { - slots = rewards.size() - ((page - 1) * 28); - } - - slots = InventoryUtils.getRowsFor(2, slots) + 9; - - - setInventoryName("&7&l> &6&lRewards PG" + page); - InventoryBuilder ib = createDefault(slots, 27); - - ib.setItem(0, IGCDefaultItems.EXIT_BUTTON.getIb()); - - int i = 10; - int toSkip = ((page - 1) * 28); - int skipped = 0; - int displayedRewards = 0; - - for (Reward r : rewards) { - if (toSkip > skipped || displayedRewards >= 28) { - skipped++; - continue; - } - - if (i % 9 == 8) { - i += 2; - } - - - r.checkIsNeedMoreConfig(); - ItemBuilder newR; - - if (!r.isNeedsMoreConfig()) - newR = new ItemBuilder(r.getDisplayBuilder().getStack()).setDisplayName("&a" + r.getRewardName()); - else - continue; - - newR.addLore("").addLore("&eClick to add to the crate."); - - ib.setItem(i, newR); - i++; - displayedRewards++; - } - - if (page != 1) { - ib.setItem(2, new ItemBuilder(XMaterial.ARROW).setDisplayName("&aGo back a page")); - } - - if ((CReward.getAllRewards().size() / 28) + (CReward.getAllRewards().size() % 28 == 0 ? 0 : 1) != page) { - ib.setItem(6, new ItemBuilder(XMaterial.ARROW).setDisplayName("&aGo forward a page")); - } - - ib.open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - if (slot == 2 && XMaterial.ARROW.isSimilar(getIb().getInv().getItem(slot))) { - page--; - open(); - } else if (slot == 6 && XMaterial.ARROW.isSimilar(getIb().getInv().getItem(slot))) { - page++; - open(); - } else if (slot == 0) { - up(); - } else if (getIb().getInv().getItem(slot) != null) { - String rName = ChatUtils.removeColor(getIb().getInv().getItem(slot).getItemMeta().getDisplayName()); - - getLastMenu().handleInput("set reward " + this.slot, rName); - } - } - - @Override - public boolean handleInput(String value, String input) { - return false; - } - - public List getUnusedRewards() { - CReward cReward = crate.getSettings().getReward(); - - List rewardsL = Arrays.asList(cReward.getCrateRewards()); - ArrayList rewards = new ArrayList<>(rewardsL); - - ArrayList toCompareRewards = new ArrayList<>(); - for (DisplayPage page : customRewardDisplayer.getPages().values()) { - toCompareRewards.addAll(page.rewardsAsList()); - } - - for (Reward reward : toCompareRewards) { - rewards.remove(reward); - } - - return rewards; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/IGCMenuConfig.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/IGCMenuConfig.java deleted file mode 100644 index 018dca0..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/IGCMenuConfig.java +++ /dev/null @@ -1,92 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.fileconfigs; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SettingsValue; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.inventory.Inventory; - -import java.util.ArrayList; - -/** - * Created by ztowne13 on 3/11/16. - */ -public class IGCMenuConfig extends IGCMenu { - ArrayList slotsWithBoolean = new ArrayList<>(); - - ItemBuilder red; - ItemBuilder green; - - public IGCMenuConfig(SpecializedCrates cc, Player p, IGCMenu lastMenu) { - super(cc, p, lastMenu, "&7&l> &6&lConfig.YML"); - - red = new ItemBuilder(XMaterial.RED_WOOL, 1); - green = new ItemBuilder(XMaterial.LIME_WOOL, 1); - } - - @Override - public void openMenu() { - InventoryBuilder ib = createDefault(27); - - ib.setItem(0, IGCDefaultItems.SAVE_ONLY_BUTTON.getIb()); - ib.setItem(9, IGCDefaultItems.RELOAD_BUTTON.getIb()); - ib.setItem(ib.getInv().getSize() - 9, IGCDefaultItems.EXIT_BUTTON.getIb()); - - int slotCounter = 2; - for (SettingsValue.Category category : SettingsValue.Category.values()) { - if ((slotCounter + 1) % 9 == 0) { - slotCounter += 3; - } - - ItemBuilder builder = new ItemBuilder(XMaterial.BOOK); - builder.setDisplayName("&a" + category.getTitle()); - builder.addAutomaticLore("&7", 30, category.getDescription()[0]); - builder.addLore(""); - builder.addAutomaticLore("&e", 30, category.getDescription()[1]); - - ib.setItem(slotCounter, builder); - - slotCounter++; - } - - ib.open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - Inventory inv = getIb().getInv(); - if (inv.getItem(slot) == null || inv.getItem(slot).getType().equals(Material.AIR)) { - return; - } - - if (slot == 0) { - getCc().getSettings().writeSettingsValues(); - ChatUtils.msgSuccess(getP(), "Config.YML saved!"); - } else if (slot == 9) { - reload(); - } else if (slot == getIb().getInv().getSize() - 9) { - up(); - } else { - String itemName = ChatUtils.removeColor(inv.getItem(slot).getItemMeta().getDisplayName()); - for (SettingsValue.Category category : SettingsValue.Category.values()) { - if (itemName.equalsIgnoreCase(category.getTitle())) { - new IGCMenuConfigCategory(getCc(), getP(), this, category).open(); - return; - } - } - } - - } - - @Override - public boolean handleInput(String value, String input) { - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/IGCMenuConfigCategory.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/IGCMenuConfigCategory.java deleted file mode 100644 index 53f48af..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/IGCMenuConfigCategory.java +++ /dev/null @@ -1,247 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.fileconfigs; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.Settings; -import me.ztowne13.customcrates.SettingsValue; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.InventoryUtils; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCListEditor; -import me.ztowne13.customcrates.interfaces.igc.IGCListSelector; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.inputmenus.InputMenu; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.Utils; -import me.ztowne13.customcrates.utils.VersionUtils; -import org.bukkit.entity.Player; -import org.bukkit.inventory.Inventory; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.List; - -/** - * Created by ztowne13 on 3/11/16. - */ -public class IGCMenuConfigCategory extends IGCMenu { - ArrayList slotsWithBoolean = new ArrayList(); - - ItemBuilder red; - ItemBuilder green; - SettingsValue.Category category; - - public IGCMenuConfigCategory(SpecializedCrates cc, Player p, IGCMenu lastMenu, SettingsValue.Category category) { - super(cc, p, lastMenu, "&7&l> &6&l" + category.getShortTitle()); - - this.category = category; - red = new ItemBuilder(XMaterial.RED_WOOL, 1); - green = new ItemBuilder(XMaterial.LIME_WOOL, 1); - } - - @Override - public void openMenu() { - - InventoryBuilder ib = createDefault(InventoryUtils.getRowsFor(2, category.getAssociatedValues().size())); - - ib.setItem(ib.getInv().getSize() - 9, IGCDefaultItems.EXIT_BUTTON.getIb()); - - int i = 2; - - SettingsValue[] sortedObj = new SettingsValue[category.getAssociatedValues().size()]; - - int back = 0; - int forward = 0; - for (SettingsValue settingsValue : category.getAssociatedValues()) { - Object val = settingsValue.getValue(getCc()); - if (val instanceof Boolean) { - sortedObj[forward] = settingsValue; - forward++; - } else { - back++; - sortedObj[sortedObj.length - back] = settingsValue; - } - } - - for (SettingsValue settingsValue : sortedObj) { - if (i % 9 == 0) { - i += 2; - } - - Object val = settingsValue.getValue(getCc()); - String combinedDescriptor = ""; - String combinedDescriptorExtra = ""; - - boolean isOntoExtra = false; - - for (String lore : settingsValue.getDescriptor()) { - if (lore.startsWith("THE")) { - isOntoExtra = true; - } - - if (isOntoExtra) { - if (combinedDescriptorExtra.equalsIgnoreCase("")) { - combinedDescriptorExtra = lore; - } else { - combinedDescriptorExtra += " " + lore; - } - } else { - if (combinedDescriptor.equalsIgnoreCase("")) { - combinedDescriptor = lore; - } else { - combinedDescriptor += " " + lore; - } - } - } - - if (val instanceof Boolean) { - ItemBuilder newBuilder = new ItemBuilder(((boolean) val ? green : red)); - newBuilder.setDisplayName("&a" + settingsValue.getEasyName()); - newBuilder.addLore("").addLore("&e" + settingsValue.getPath()); - newBuilder.addLore("&f&oCurrent value: &f" + val); - newBuilder.addLore(""); - - newBuilder.addAutomaticLore("&7", 35, combinedDescriptor); - if (!combinedDescriptorExtra.equalsIgnoreCase("")) { - newBuilder.addLore(""); - newBuilder.addAutomaticLore("&b", 35, combinedDescriptorExtra); - } - ib.setItem(i, newBuilder); - slotsWithBoolean.add(i); - } else { - boolean isCollection = val instanceof Collection; - XMaterial material; - if (val instanceof Collection) { - material = XMaterial.LIGHT_BLUE_WOOL; - } else if (settingsValue.getListValues() != null) { - material = XMaterial.MAGENTA_WOOL; - } else { - material = XMaterial.ORANGE_WOOL; - } - - ItemBuilder newBuilder = new ItemBuilder(material); - newBuilder.setDisplayName("&a" + settingsValue.getEasyName()); - newBuilder.addLore("").addLore("&e" + settingsValue.getPath()); - if (isCollection) { - newBuilder.addLore("&f&oCurrent value: &f"); - List objects = (List) val; - for (String obj : objects) - newBuilder.addLore(obj); - } else { - newBuilder.addLore("&f&oCurrent value: &f" + val); - } - - newBuilder.addLore(""); - newBuilder.addAutomaticLore("&7", 35, combinedDescriptor); - if (!combinedDescriptorExtra.equalsIgnoreCase("")) { - newBuilder.addLore(""); - newBuilder.addAutomaticLore("&b", 35, combinedDescriptorExtra); - } - - ib.setItem(i, newBuilder); - } - i++; - } - - - ib.open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - Inventory inv = getIb().getInv(); - - if (inv.getItem(slot) == null) { - return; - } - - ItemBuilder item = new ItemBuilder(inv.getItem(slot)); - if (slotsWithBoolean.contains(slot)) { - SettingsValue sv = SettingsValue.getByPath(ChatUtils.removeColorFrom(item.getLore()).get(1)); - - if (VersionUtils.Version.v1_12.isServerVersionOrEarlier()) { - item.getStack().setDurability((byte) (item.getStack().getDurability() == 5 ? 14 : 5)); - } else { - if (XMaterial.RED_WOOL.isSimilar(item.getStack())) - item.getStack().setType(XMaterial.LIME_WOOL.parseMaterial()); - else - item.getStack().setType(XMaterial.RED_WOOL.parseMaterial()); - } - - getIb().setItem(slot, item); - - sv.setValue(getCc(), item.getStack().getDurability() == 5 || XMaterial.LIME_WOOL.isSimilar(item.getStack())); - - open(); - } else if (XMaterial.ORANGE_WOOL.isSimilar(inv.getItem(slot))) { - SettingsValue sv = SettingsValue.getByPath(ChatUtils.removeColorFrom(item.getLore()).get(1)); - - new InputMenu(getCc(), getP(), sv.getPath(), sv.getValue(getCc()).toString(), sv.getObj(), this, !sv.isWithColor()); - } else if (XMaterial.LIGHT_BLUE_WOOL.isSimilar(inv.getItem(slot))) { - SettingsValue sv = SettingsValue.getByPath(ChatUtils.removeColorFrom(item.getLore()).get(1)); - new IGCListEditor(getCc(), getP(), this, "inv-reward-item-lore", "Line", (List) sv.getValue(getCc()), - XMaterial.BOOK, 1).open(); - } else if (XMaterial.MAGENTA_WOOL.isSimilar(inv.getItem(slot))) { - SettingsValue sv = SettingsValue.getByPath(ChatUtils.removeColorFrom(item.getLore()).get(1)); - - List values; - List descriptors; - - if (sv.getListValues().length != 0) { - values = Arrays.asList(sv.getListValues()); - descriptors = Arrays.asList(sv.getListValueDescriptors()); - } else { - values = new ArrayList<>(); - descriptors = new ArrayList<>(); - for (Crate crate : Crate.getLoadedCrates().values()) { - if (crate.isMultiCrate()) { - values.add(crate.getName()); - descriptors.add("Set the " + crate.getName() + " crate to be the multicrate that opens when a player types /crates."); - } - } - } - - new IGCListSelector(getCc(), getP(), this, sv.getPath(), values, - XMaterial.BOOK, 1, descriptors).open(); - } else { - if (slot == getIb().getInv().getSize() - 9) { - up(); - } - } - } - - @Override - public boolean handleInput(String value, String input) { - SettingsValue sv = SettingsValue.getByPath(value); - Settings settings = getCc().getSettings(); - String path = sv.getPath(); - - if (sv.getObj() == String.class) { - sv.setValue(getCc(), input); - ChatUtils.msgSuccess(getP(), "Set " + path + " to '" + input + "'"); - return true; - } else if (sv.getObj() == Integer.class) { - if (Utils.isInt(input)) { - sv.setValue(getCc(), Integer.parseInt(input)); - ChatUtils.msgSuccess(getP(), "Set " + path + " to '" + input + "'"); - return true; - } else { - ChatUtils.msgError(getP(), "This is not a valid number, please try again."); - } - } else if (sv.getObj() == Double.class) { - if (Utils.isDouble(input)) { - sv.setValue(getCc(), input); - ChatUtils.msgSuccess(getP(), "Set " + path + " to '" + input + "'"); - return true; - } else { - ChatUtils.msgError(getP(), "This is not a valid decimal value, please try again."); - } - } - - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/IGCMenuCrateConfig.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/IGCMenuCrateConfig.java deleted file mode 100644 index 3fc7bca..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/IGCMenuCrateConfig.java +++ /dev/null @@ -1,172 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.fileconfigs; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.types.animations.CrateAnimationType; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.files.FileHandler; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.crates.crateanimations.*; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.Utils; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; - -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - -/** - * Created by ztowne13 on 3/20/16. - */ -public class IGCMenuCrateConfig extends IGCMenu { - public IGCMenuCrateConfig(SpecializedCrates cc, Player p, IGCMenu lastMenu) { - super(cc, p, lastMenu, "&7&l> &6&lCrateConfig.YML"); - } - - @Override - public void openMenu() { - InventoryBuilder ib = createDefault(27); - - ib.setItem(18, IGCDefaultItems.EXIT_BUTTON.getIb()); - ib.setItem(0, IGCDefaultItems.SAVE_ONLY_BUTTON.getIb()); - ib.setItem(9, IGCDefaultItems.RELOAD_BUTTON.getIb()); - - ib.setItem(11, - new ItemBuilder(XMaterial.PAPER).setDisplayName("&aCSGO Animation").setLore("&7Animation name: &fINV_CSGO") - .addLore("").addLore("&7Used by crates: &f" + CrateAnimationType.INV_CSGO.getUses())); - ib.setItem(12, new ItemBuilder(XMaterial.PAPER).setDisplayName("&aRoulette Animation") - .setLore("&7Animation name: &fINV_ROULETTE").addLore("") - .addLore("&7Used by crates: &f" + CrateAnimationType.INV_ROULETTE.getUses())); - ib.setItem(13, - new ItemBuilder(XMaterial.PAPER).setDisplayName("&aMenu Animation").setLore("&7Animation name: &fINV_MENU") - .addLore("").addLore("&7Used by crates: &f" + CrateAnimationType.INV_MENU.getUses())); - ib.setItem(14, new ItemBuilder(XMaterial.PAPER).setDisplayName("&aEnclose Animation") - .setLore("&7Animation name: &fINV_ENCLOSE").addLore("") - .addLore("&7Used by crates: &f" + CrateAnimationType.INV_ENCLOSE.getUses())); - ib.setItem(15, new ItemBuilder(XMaterial.PAPER).setDisplayName("&aDiscover Animation") - .setLore("&7Animation name: &fINV_DISCOVER").addLore("") - .addLore("&7Used by crates: &f" + CrateAnimationType.INV_DISCOVER.getUses())); - ib.setItem(16, new ItemBuilder(XMaterial.PAPER).setDisplayName("&aOpen Chest Animation") - .setLore("&7Animation name: &fBLOCK_CRATEOPEN").addLore("") - .addLore("&7Used by crates: &f" + CrateAnimationType.BLOCK_CRATEOPEN.getUses())); - - ib.open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - switch (slot) { - case 18: - up(); - break; - case 0: - getCc().getCrateConfigFile().save(); - ChatUtils.msgSuccess(getP(), "CrateConfig.YML saved!"); - break; - case 9: - reload(); - break; - case 11: - new IGCAnimCSGO(getCc(), getP(), this).open(); - break; - case 12: - new IGCAnimRoulette(getCc(), getP(), this).open(); - break; - case 13: - new IGCAnimMenu(getCc(), getP(), this).open(); - break; - case 14: - new IGCAnimEnclose(getCc(), getP(), this).open(); - break; - case 15: - new IGCAnimDiscover(getCc(), getP(), this).open(); - break; - case 16: - new IGCAnimOpenChest(getCc(), getP(), this).open(); - break; - } - - } - - @Override - public boolean handleInput(String value, String input) { - Object type = getInputMenu().getType(); - if (type == Double.class) { - if (Utils.isDouble(input)) { - getCc().getCrateConfigFile().get().set(getPath(value), Double.valueOf(input)); - ChatUtils.msgSuccess(getP(), "Set " + value + " to '" + input + "'"); - return true; - } else { - ChatUtils.msgError(getP(), "This is not a valid decimal value, please try again."); - } - } else if (type == Integer.class) { - if (Utils.isInt(input)) { - getCc().getCrateConfigFile().get().set(getPath(value), Integer.parseInt(input)); - ChatUtils.msgSuccess(getP(), "Set " + value + " to '" + input + "'"); - return true; - } else { - ChatUtils.msgError(getP(), "This is not a valid number, please try again."); - } - } else { - if (value.equalsIgnoreCase("add Roulette.random-blocks") || value.equalsIgnoreCase("add CSGO.filler-blocks")) { - Optional optional = XMaterial.matchXMaterial(input.replace(";", ":")); - if (optional.isPresent()) { - XMaterial dm = optional.get(); - List currentList = - getCc().getCrateConfigFile().get().contains(getPath(value.substring(4))) - ? getCc().getCrateConfigFile().get().getStringList(getPath(value.substring(4))) - : new ArrayList<>(); - currentList.add(dm.name()); - getCc().getCrateConfigFile().get().set(getPath(value.substring(4)), currentList); - return true; - } else { - ChatUtils.msgError(getP(), input + " does not have a valid material or is not formatted MATERIAL;DATA"); - } - } else if (value.equalsIgnoreCase("remove Roulette.random-blocks") || - value.equalsIgnoreCase("remove CSGO.filler-blocks")) { - if (getCc().getCrateConfigFile().get().contains(getPath(value.substring(7)))) { - boolean found = false; - List newList = new ArrayList<>(); - for (String s : getCc().getCrateConfigFile().get().getStringList(getPath(value.substring(7)))) { - if (s.equalsIgnoreCase(input)) { - found = true; - } else { - newList.add(s); - } - } - - if (found) { - ChatUtils.msgSuccess(getP(), "Removed the " + input + " value."); - getCc().getCrateConfigFile().get().set(getPath(value.substring(7)), newList); - return true; - } else { - ChatUtils.msgError(getP(), input + " does not exist in the filler / random blocks: " + - getCc().getCrateConfigFile().get().getStringList(getPath(value.substring(7)))); - } - } else { - ChatUtils.msgError(getP(), "No filler blocks currently exist to remove."); - return true; - } - } else { - getCc().getCrateConfigFile().get().set(getPath(value), input); - ChatUtils.msgSuccess(getP(), "Set " + value + " to '" + input + "'"); - return true; - } - } - return false; - } - - public String getPath(String value) { - return "CrateType.Inventory." + value; - } - - public String getValue(String crateType, String value) { - FileHandler fu = getCc().getCrateConfigFile(); - FileConfiguration fc = fu.get(); - return fc.get("CrateType.Inventory." + crateType + "." + value).toString(); - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/IGCMenuCrateOrMulticrate.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/IGCMenuCrateOrMulticrate.java deleted file mode 100644 index ff91683..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/IGCMenuCrateOrMulticrate.java +++ /dev/null @@ -1,111 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.fileconfigs; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.CrateSettings; -import me.ztowne13.customcrates.crates.options.CReward; -import me.ztowne13.customcrates.crates.options.ObtainType; -import me.ztowne13.customcrates.crates.options.rewards.displaymenu.RewardDisplayType; -import me.ztowne13.customcrates.crates.options.rewards.displaymenu.SimpleRewardDisplayer; -import me.ztowne13.customcrates.crates.types.animations.CrateAnimationType; -import me.ztowne13.customcrates.crates.types.display.MaterialPlaceholder; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.crates.IGCCratesMain; -import me.ztowne13.customcrates.interfaces.igc.inputmenus.InputMenu; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.interfaces.items.SaveableItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.entity.Player; - -public class IGCMenuCrateOrMulticrate extends IGCMenu { - boolean multicrate = false; - - public IGCMenuCrateOrMulticrate(SpecializedCrates specializedCrates, Player p, IGCMenu lastMenu) { - super(specializedCrates, p, lastMenu, "&7&l> &6&lCrates or Multicrate "); - } - - @Override - public void openMenu() { - InventoryBuilder ib = createDefault(9); - ib.setItem(0, IGCDefaultItems.EXIT_BUTTON.getIb()); - - ItemBuilder normalCrate = new ItemBuilder(XMaterial.BOOK, 1); - normalCrate.setDisplayName("&aClassic Crate"); - normalCrate.addLore("") - .addAutomaticLore("&f", 30, "This is your normal or average crate that you're probably looking for!"); - - ItemBuilder multiCrate = new ItemBuilder(XMaterial.BOOKSHELF, 1); - multiCrate.setDisplayName("&aMulti Crate"); - multiCrate.addLore("") - .addAutomaticLore("&f", 30, "This is a crate that is an inventory and has multiple crates in it!"); - - getIb().setItem(3, normalCrate); - getIb().setItem(5, multiCrate); - - getIb().open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - if (slot == 0) - up(); - else if (slot == 3) { - new InputMenu(getCc(), getP(), "crate name", "null", "Name the crate whatever you want.", String.class, this, - true); - multicrate = false; - } else if (slot == 5) { - new InputMenu(getCc(), getP(), "crate name", "null", "Name the multicrate whatever you want.", String.class, - this, true); - multicrate = true; - } - } - - @Override - public boolean handleInput(String value, String input) { - if (value.equalsIgnoreCase("crate name")) { - if (!Crate.existsNotCaseSensitive(input)) { - if (!input.contains(" ")) { - Crate newCrate = new Crate(getCc(), input, true, multicrate); - CrateSettings cs = newCrate.getSettings(); - cs.setObtainType(ObtainType.STATIC); - cs.setPlaceholder(new MaterialPlaceholder(getCc())); - - if (!multicrate) { - cs.setCrateType(CrateAnimationType.INV_ROULETTE); - cs.setRequireKey(true); - cs.setRewardDisplayType(RewardDisplayType.IN_ORDER); - cs.setDisplayer(new SimpleRewardDisplayer(newCrate)); - } - - SaveableItemBuilder builder = new SaveableItemBuilder(XMaterial.CHEST, 1); - builder.setDisplayName(input); - - cs.getCrateItemHandler().setItem(builder); - - newCrate.setEnabled(true); - newCrate.setCanBeEnabled(false); - - if (!multicrate && !CReward.getAllRewards().isEmpty()) { - cs.getReward().addReward(CReward.getAllRewards().values().iterator().next().getRewardName()); - } - - cs.saveAll(); - newCrate.setNeedsReload(true); - - new IGCCratesMain(getCc(), getP(), this, newCrate).open(); - ChatUtils.msgSuccess(getP(), "Created a new crate with the name " + input); - // new InputMenu(getCc(), getP(), "crate obtain method", "null", "Available obtain methods: " + Arrays.toString(ObtainType.values()), String.class, this); - } else { - ChatUtils.msgError(getP(), "Crate names cannot have spaces in their names."); - } - } else { - ChatUtils.msgError(getP(), "This crate name already exists!"); - } - } - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/IGCMenuCrates.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/IGCMenuCrates.java deleted file mode 100644 index 6109ed4..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/IGCMenuCrates.java +++ /dev/null @@ -1,110 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.fileconfigs; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.InventoryUtils; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.crates.IGCCratesMain; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.entity.Player; - -import java.util.ArrayList; -import java.util.Collections; - -/** - * Created by ztowne13 on 3/20/16. - */ -public class IGCMenuCrates extends IGCMenu { - int page; - - public IGCMenuCrates(SpecializedCrates cc, Player p, IGCMenu lastMenu) { - this(cc, p, lastMenu, 1); - } - - public IGCMenuCrates(SpecializedCrates specializedCrates, Player p, IGCMenu lastMenu, int page) { - super(specializedCrates, p, lastMenu, "&7&l> &6&lCrates PG " + page); - - this.page = page; - } - - @Override - public void openMenu() { - int values = Crate.getLoadedCrates().keySet().size(); - int inThisInv = values - ((page - 1) * 30); - - InventoryBuilder ib = createDefault(InventoryUtils.getRowsFor(4, values, page), 18); - ib.setItem(0, IGCDefaultItems.EXIT_BUTTON.getIb()); - ib.setItem(8, - new ItemBuilder(XMaterial.PAPER).setDisplayName("&aCreate a new crate").setLore("&7Please set the crate and") - .addLore("&7key once you are done configuring").addLore("&7for it to save properly.")); - - ItemBuilder nextPage = new ItemBuilder(XMaterial.ARROW); - nextPage.setDisplayName("&aNext Page"); - nextPage.addLore("").addAutomaticLore("&7", 30, "Click to go to the next page of crates."); - - ItemBuilder lastPage = new ItemBuilder(XMaterial.ARROW); - lastPage.setDisplayName("&aPrevious Page"); - lastPage.addLore("").addAutomaticLore("&7", 30, "Click to go to the previous page of crates."); - - if (page != 1) - ib.setItem(9, lastPage); - if (inThisInv > 30) - ib.setItem(18, nextPage); - - - ArrayList names = new ArrayList<>(Crate.getLoadedCrates().keySet()); - Collections.sort(names); - - int i = 2; - int toSkip = ((page - 1) * 30); - int skipped = 0; - - for (String crateName : names) { - if (i % 9 == 7) { - i += 4; - } - - if (i > 54) - break; - - if (skipped < toSkip) { - skipped++; - } else { - Crate crate = Crate.getLoadedCrates().get(crateName); - ib.setItem(i, new ItemBuilder(XMaterial.CHEST).setDisplayName((crate.isEnabled() ? "&a" : "&c") + crateName) - .setLore("&7Placed crates: &f" + crate.getPlacedCount()).addLore( - "&7Errors: " + (crate.getSettings().getStatusLogger().getFailures() == 0 ? "&f" : "&c") + - crate.getSettings().getStatusLogger().getFailures())); - i++; - } - } - - getIb().open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - if (slot == 0) - up(); - else if (slot == 8) - new IGCMenuCrateOrMulticrate(getCc(), getP(), this).open(); - else if (slot == 9) - new IGCMenuCrates(getCc(), getP(), getLastMenu(), page - 1).open(); - else if (slot == 18) - new IGCMenuCrates(getCc(), getP(), getLastMenu(), page + 1).open(); - else if (getIb().getInv().getItem(slot) != null && XMaterial.CHEST.isSimilar(getIb().getInv().getItem(slot))) { - String name = ChatUtils.removeColor(getIb().getInv().getItem(slot).getItemMeta().getDisplayName()); - new IGCCratesMain(getCc(), getP(), this, Crate.getCrate(getCc(), name)).open(); - } - } - - @Override - public boolean handleInput(String value, String input) { - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/IGCMenuMessages.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/IGCMenuMessages.java deleted file mode 100644 index c52c7cc..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/IGCMenuMessages.java +++ /dev/null @@ -1,86 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.fileconfigs; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.Messages; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.InventoryUtils; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.inputmenus.InputMenu; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.entity.Player; - -import java.util.ArrayList; - -/** - * Created by ztowne13 on 3/15/16. - */ -public class IGCMenuMessages extends IGCMenu { - static int msgLoreLength = 40; - - public IGCMenuMessages(SpecializedCrates cc, Player p, IGCMenu lastMenu) { - super(cc, p, lastMenu, "&7&l> &6&lMessages.YML"); - } - - @Override - public void openMenu() { - InventoryBuilder ib = createDefault(InventoryUtils.getRowsFor(2, Messages.values().length - 1)); - ib.setItem(0, IGCDefaultItems.SAVE_ONLY_BUTTON.getIb()); - ib.setItem(9, IGCDefaultItems.RELOAD_BUTTON.getIb()); - ib.setItem(ib.getInv().getSize() - 9, IGCDefaultItems.EXIT_BUTTON.getIb()); - - ArrayList msgs = new ArrayList<>(); - - for (Messages msg : Messages.values()) { - if (msg.getMsg().equalsIgnoreCase("")) { - msgs.add(msg); - } - } - - int i = 2; - for (Messages msg : msgs) { - if (i % 9 == 0) { - i += 2; - } - - String properMsg = msg.getProperMsg(getCc()); -// ib.setItem(i, new ItemBuilder(DynamicMaterial.BOOK, 1).setName("&a" + msg.toString().toLowerCase()).addLore( -// properMsg.substring(0, properMsg.length() > msgLoreLength ? msgLoreLength : properMsg.length()) + -// (properMsg.length() > msgLoreLength ? "..." : ""))); - - ib.setItem(i, new ItemBuilder(XMaterial.BOOK, 1).setDisplayName("&a" + msg.toString().toLowerCase()) - .addAutomaticLore("&f", 30, true, properMsg).addLore("").addLore("") - .addAutomaticLore("&f", 30, "Set to 'none' to remove the message.")); - i++; - } - - ib.open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - if (slot == 0) { - getCc().getMessageFile().save(); - ChatUtils.msgSuccess(getP(), "Messages.YML saved!"); - } else if (slot == 9) { - reload(); - } else if (slot == getIb().getInv().getSize() - 9) { - up(); - } else if (!(getIb().getInv().getItem(slot) == null)) { - Messages msg = Messages.valueOf( - ChatUtils.removeColor(getIb().getInv().getItem(slot).getItemMeta().getDisplayName()).toUpperCase()); - new InputMenu(getCc(), getP(), msg.name(), msg.getProperMsg(getCc()), String.class, this); - } - } - - @Override - public boolean handleInput(String value, String input) { - Messages msg = Messages.valueOf(value.toUpperCase()); - msg.writeValue(getCc(), input); - ChatUtils.msgSuccess(getP(), "Set " + value + " to '" + input + "'"); - return true; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/IGCMenuSQL.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/IGCMenuSQL.java deleted file mode 100644 index bd23cd4..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/IGCMenuSQL.java +++ /dev/null @@ -1,98 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.fileconfigs; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.files.FileHandler; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.inputmenus.InputMenu; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; - -/** - * Created by ztowne13 on 3/20/16. - */ -public class IGCMenuSQL extends IGCMenu { - public IGCMenuSQL(SpecializedCrates cc, Player p, IGCMenu lastMenu) { - super(cc, p, lastMenu, "&7&l> &6&lCrateConfig.YML"); - } - - @Override - public void openMenu() { - - FileHandler fu = getCc().getSqlFile(); - FileConfiguration fc = fu.get(); - - InventoryBuilder ib = createDefault(27); - - ib.setItem(18, IGCDefaultItems.EXIT_BUTTON.getIb()); - ib.setItem(0, IGCDefaultItems.SAVE_ONLY_BUTTON.getIb()); - ib.setItem(9, IGCDefaultItems.RELOAD_BUTTON.getIb()); - - ib.setItem(11, new ItemBuilder(XMaterial.PAPER).setDisplayName("&aDatabase Name").addLore("&7Current Value:") - .addLore("&7" + fc.getString("database.name"))); - ib.setItem(12, new ItemBuilder(XMaterial.PAPER).setDisplayName("&aDatabase IP").addLore("&7Current Value:") - .addLore("&7" + fc.getString("database.ip"))); - ib.setItem(13, new ItemBuilder(XMaterial.PAPER).setDisplayName("&aDatabase Port").addLore("&7Current Value:") - .addLore("&7" + fc.getString("database.port"))); - ib.setItem(14, new ItemBuilder(XMaterial.PAPER).setDisplayName("&aDatabase Username").addLore("&7Current Value:") - .addLore("&7" + fc.getString("database.username"))); - ib.setItem(15, new ItemBuilder(XMaterial.PAPER).setDisplayName("&aDatabase Password").addLore("&7Current Value:") - .addLore("&7" + fc.getString("database.password"))); - - ib.open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - switch (slot) { - case 18: - up(); - ChatUtils.msgInfo(getP(), "Remember to change the store-data value in the config.yml if you want to enable SQL for storage."); - break; - case 0: - getCc().getSqlFile().save(); - ChatUtils.msgInfo(getP(), "Remember to change the store-data value in the config.yml if you want to enable SQL for storage."); - ChatUtils.msgSuccess(getP(), "SQL.YML saved! PLEASE RELOAD OR RESTART SERVER FOR CHANGES TO TAKE EFFECT."); - break; - case 9: - reload(); - ChatUtils.msgInfo(getP(), "Remember to change the store-data value in the config.yml if you want to enable SQL for storage."); - break; - case 11: - new InputMenu(getCc(), getP(), "database.name", getCc().getSqlFile().get().getString("database.name"), - String.class, this, true); - break; - case 12: - new InputMenu(getCc(), getP(), "database.ip", getCc().getSqlFile().get().getString("database.ip"), - String.class, this, true); - break; - case 13: - new InputMenu(getCc(), getP(), "database.port", getCc().getSqlFile().get().getString("database.port"), - String.class, this, true); - break; - case 14: - new InputMenu(getCc(), getP(), "database.username", getCc().getSqlFile().get().getString("database.username"), - String.class, this, true); - break; - case 15: - new InputMenu(getCc(), getP(), "database.password", getCc().getSqlFile().get().getString("database.password"), - String.class, this, true); - break; - } - - } - - @Override - public boolean handleInput(String value, String input) { - FileHandler fileHandler = getCc().getSqlFile(); - fileHandler.get().set(value, input); - - ChatUtils.msgSuccess(getP(), "Set " + value + " to " + input + "."); - return true; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/rewards/IGCDragAndDrop.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/rewards/IGCDragAndDrop.java deleted file mode 100644 index 00ea5d3..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/rewards/IGCDragAndDrop.java +++ /dev/null @@ -1,119 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.fileconfigs.rewards; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.options.CReward; -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.Utils; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - -import java.util.ArrayList; - -/** - * Created by ztowne13 on 8/7/16. - */ -public class IGCDragAndDrop extends IGCMenu { - public IGCDragAndDrop(SpecializedCrates cc, Player p, IGCMenu lastMenu) { - super(cc, p, lastMenu, "&4&lDrag and Drop"); - } - - @Override - public void openMenu() { - - InventoryBuilder ib = createDefault(54); - - ib.setItem(53, IGCDefaultItems.EXIT_BUTTON.getIb()); - ib.setItem(52, IGCDefaultItems.SAVE_ONLY_BUTTON.getIb()); - - setIb(ib); - getIb().open(); - putInMenu(); - } - - @Override // For this menu it has been repurposed to be used as the "save" function - public void handleClick(int slot) { - if (slot == 53) { - for (int i = 0; i < getIb().getInv().getSize() - 2; i++) { - ItemStack stack = getIb().getInv().getItem(i); - if (stack != null && !stack.getType().equals(Material.AIR)) { - Utils.addItemAndDropRest(getP(), stack); - } - } - ChatUtils.msgInfo(getP(), "Added all items back to your inventory."); - up(); - } else if (slot == 52) { - ArrayList cmds = new ArrayList<>(); - - for (int i = 0; i < getIb().getInv().getSize() - 2; i++) { - ItemStack stack = getIb().getInv().getItem(i); - if (stack != null && !stack.getType().equals(Material.AIR)) { - String rewardName = getNameFor(stack); - Reward r = new Reward(getCc(), rewardName); - - r.setChance(10); - r.setRarity("default"); - r.setCommands((ArrayList) cmds.clone()); - - r.setGiveDisplayItem(true); - r.setGiveDisplayItemLore(true); - r.setNeedsMoreConfig(false); - - /*if(!stack.getItemMeta().hasDisplayName()) - { - ItemMeta meta = stack.getItemMeta(); - meta.setDisplayName(rewardName); - stack.setItemMeta(meta); - - r.setGiveDisplayItemName(false); - }*/ - - ItemBuilder builderToSet = new ItemBuilder(stack); - - if (builderToSet.getLore().isEmpty() || builderToSet.getLore().size() == 0) { - for (Object s : (ArrayList) getCc().getSettings().getConfigValues() - .get("inv-reward-item-lore")) { - builderToSet.addLore(s.toString()); - } - - r.setGiveDisplayItemLore(false); - } - - r.setBuilder(builderToSet); - - r.writeToFile(); - } - } - ChatUtils.msgSuccess(getP(), "Saved! Remember to update the commands and chance's for all the rewards"); - up(); - } - } - - @Override - public boolean handleInput(String value, String input) { - return false; - } - - public String getNameFor(ItemStack stack) { - - String rewardName = ChatUtils.removeColor( - stack.hasItemMeta() && stack.getItemMeta().hasDisplayName() ? stack.getItemMeta().getDisplayName() : - stack.getType().name().toLowerCase()); - rewardName = rewardName.replaceAll(" ", "_"); - - int i = 0; - while (true) { - String name = rewardName + (i == 0 ? "" : i); - if (!CReward.rewardNameExists(getCc(), name)) { - - return name; - } - i++; - } - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/rewards/IGCMenuAddReward.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/rewards/IGCMenuAddReward.java deleted file mode 100644 index 572eb13..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/rewards/IGCMenuAddReward.java +++ /dev/null @@ -1,146 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.fileconfigs.rewards; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.options.CReward; -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.InventoryUtils; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.buttons.IGCButtonType; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.entity.Player; - -import java.util.HashMap; - -public class IGCMenuAddReward extends IGCMenu { - - int page; - Crate crate; - - public IGCMenuAddReward(SpecializedCrates cc, Player p, IGCMenu lastMenu, Crate crate, int page) { - super(cc, p, lastMenu, "&7&l> &6&lRewards PG" + page, - new IGCButtonType[]{ - IGCButtonType.REWARD_FILTER - }, - new int[]{ - 8 - }); - this.page = page; - this.crate = crate; - } - - @Override - public void openMenu() { - int slots; - - CReward.loadAll(getCc(), getP()); - - HashMap rewards = getUnusedRewards((CReward.RewardSortType) getButtons()[0].getValue()); - - slots = Math.min(rewards.size() - ((page - 1) * 28), 28); - - slots = InventoryUtils.getRowsFor(2, slots) + 9; - - - setInventoryName("&7&l> &6&lRewards PG" + page); - InventoryBuilder ib = createDefault(slots, 27); - - ib.setItem(0, IGCDefaultItems.EXIT_BUTTON.getIb()); - - int i = 10; - int toSkip = ((page - 1) * 28); - int skipped = 0; - int displayedRewards = 0; - - for (String rName : rewards.keySet()) { - if (toSkip > skipped || displayedRewards >= 28) { - skipped++; - continue; - } - - if (i % 9 == 8) { - i += 2; - } - - Reward r; - - r = rewards.get(rName); - - r.checkIsNeedMoreConfig(); - ItemBuilder newR; - - if (r.isNeedsMoreConfig()) - newR = new ItemBuilder(XMaterial.BARRIER).setDisplayName("&4&l" + rName) - .setLore("&cThis reward isn't fully configured,").addLore("&cplease fix it and reload the plugin."); - else - newR = new ItemBuilder(r.getDisplayBuilder().getStack()).setDisplayName("&a" + rName); - - newR.setLore("").addLore("&7- Name: &f" + r.getDisplayBuilder().getDisplayName(true)); - newR.addLore("&7- Chance: &f" + r.getChance()); - newR.addLore("&7- Give display item: &f" + r.isGiveDisplayItem()); - newR.addLore("&7- Give display item WITH lore: &f" + r.isGiveDisplayItemLore()); - newR.addLore("&7- Commands to run: &f" + r.getCommands().size()); - newR.addLore("&7- Rarity: &f" + r.getRarity()); - - newR.addLore("").addLore("&eClick to add to the crate."); - - ib.setItem(i, newR); - i++; - displayedRewards++; - } - - if (page != 1) { - ib.setItem(2, new ItemBuilder(XMaterial.ARROW).setDisplayName("&aGo back a page")); - } - - if ((CReward.getAllRewards().size() / 28) + (CReward.getAllRewards().size() % 28 == 0 ? 0 : 1) != page) { - ib.setItem(6, new ItemBuilder(XMaterial.ARROW).setDisplayName("&aGo forward a page")); - } - - ib.open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - if (slot == 2 && XMaterial.ARROW.isSimilar(getIb().getInv().getItem(slot))) { - page--; - open(); - } else if (slot == 6 && XMaterial.ARROW.isSimilar(getIb().getInv().getItem(slot))) { - page++; - open(); - } else if (slot == 0) { - up(); - } else if (getIb().getInv().getItem(slot) != null) { - String rName = ChatUtils.removeColor(getIb().getInv().getItem(slot).getItemMeta().getDisplayName()); - if (crate.getSettings().getReward().addReward(rName)) { - ChatUtils.msgSuccess(getP(), "Added " + rName); - open(); - } else { - ChatUtils.msgError(getP(), "Failed to add the reward, maybe it's not completely configured?"); - } - } - } - - @Override - public boolean handleInput(String value, String input) { - return false; - } - - public HashMap getUnusedRewards(CReward.RewardSortType sortType) { - CReward cReward = crate.getSettings().getReward(); - - HashMap rewards = (HashMap) CReward.getAllRewardsSorted(getCc(), sortType); - - for (Reward reward : cReward.getCrateRewards()) { - rewards.remove(reward.getRewardName()); - } - - return rewards; - } - -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/rewards/IGCMenuFallbackReward.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/rewards/IGCMenuFallbackReward.java deleted file mode 100644 index 471104c..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/rewards/IGCMenuFallbackReward.java +++ /dev/null @@ -1,86 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.fileconfigs.rewards; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.inputmenus.InputMenu; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.entity.Player; - -/** - * Created by ztowne13 on 3/22/16. - */ -public class IGCMenuFallbackReward extends IGCMenu { - Reward reward; - - public IGCMenuFallbackReward(SpecializedCrates cc, Player p, IGCMenu lastMenu, Reward reward) { - super(cc, p, lastMenu, "&7&l> &6&lFallback Reward"); - this.reward = reward; - } - - @Override - public void openMenu() { - - InventoryBuilder ib = createDefault(9); - - getIb().setItem(0, IGCDefaultItems.EXIT_BUTTON.getIb()); - - ItemBuilder fallbackPerm = new ItemBuilder(XMaterial.BOOK); - fallbackPerm.setDisplayName("&aPermission"); - fallbackPerm.addLore("&7Current Value:"); - fallbackPerm.addLore("&7" + reward.getFallbackPermission()); - fallbackPerm.addLore(""); - fallbackPerm.addAutomaticLore("&f", 30, "Set to 'none' to remove."); - fallbackPerm.addLore(""); - fallbackPerm.addAutomaticLore("&f", 30, "If a player has this permission and wins this reward," + - " they will be given the specified fallback reward instead of this reward."); - - ItemBuilder fallbackReward = new ItemBuilder(XMaterial.DIAMOND); - fallbackReward.setDisplayName("&aReward"); - fallbackReward.addLore("&7Current Value:"); - fallbackReward.addLore("&7" + reward.getFallbackRewardName()); - fallbackReward.addLore(""); - fallbackReward.addAutomaticLore("&f", 30, "If a player has the specified permission and wins this reward," + - " they will receive this specified reward instead."); - - ib.setItem(2, fallbackPerm); - ib.setItem(3, fallbackReward); - - getIb().open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - switch (slot) { - case 0: - up(); - break; - case 2: - new InputMenu(getCc(), getP(), "fallback-reward.permission", reward.getFallbackPermission(), "Set to 'none' to remove", String.class, this, true); - break; - case 3: - new IGCMenuFallbackRewardSelector(getCc(), getP(), this, reward, 1).open(); - break; - } - } - - @Override - public boolean handleInput(String value, String input) { - if (value.equalsIgnoreCase("fallback-reward.permission")) { - if (input.equalsIgnoreCase("none")) { - reward.setFallbackPermission(""); - ChatUtils.msgSuccess(getP(), "Removed the fallback reward."); - return true; - } - reward.setFallbackPermission(input); - ChatUtils.msgSuccess(getP(), "Set the fallback reward to " + input); - } - return true; - } - -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/rewards/IGCMenuFallbackRewardSelector.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/rewards/IGCMenuFallbackRewardSelector.java deleted file mode 100644 index aa3e3c5..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/rewards/IGCMenuFallbackRewardSelector.java +++ /dev/null @@ -1,124 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.fileconfigs.rewards; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.options.CReward; -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.InventoryUtils; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.entity.Player; - -import java.util.Map; - -public class IGCMenuFallbackRewardSelector extends IGCMenu { - Reward reward; - int page; - - public IGCMenuFallbackRewardSelector(SpecializedCrates cc, Player p, IGCMenu lastMenu, Reward reward, int page) { - super(cc, p, lastMenu, "&7&l> &6&lRewards PG" + page); - this.page = page; - this.reward = reward; - } - - @Override - public void openMenu() { - - int slots; - - CReward.loadAll(getCc(), getP()); - - Map rewards = CReward.getAllRewards(); - rewards.remove(reward.getRewardName()); - - slots = Math.min(rewards.size() - ((page - 1) * 28), 28); - - slots = InventoryUtils.getRowsFor(2, slots) + 9; - - - setInventoryName("&7&l> &6&lRewards PG" + page); - InventoryBuilder ib = createDefault(slots, 27); - - ib.setItem(0, IGCDefaultItems.EXIT_BUTTON.getIb()); - - int i = 10; - int toSkip = ((page - 1) * 28); - int skipped = 0; - int displayedRewards = 0; - - for (String rName : rewards.keySet()) { - if (toSkip > skipped || displayedRewards >= 28) { - skipped++; - continue; - } - - if (i % 9 == 8) { - i += 2; - } - - Reward r; - - r = rewards.get(rName); - - r.checkIsNeedMoreConfig(); - ItemBuilder newR; - - if (r.isNeedsMoreConfig()) - newR = new ItemBuilder(XMaterial.BARRIER).setDisplayName("&4&l" + rName) - .setLore("&cThis reward isn't fully configured,").addLore("&cplease fix it and reload the plugin."); - else - newR = new ItemBuilder(r.getDisplayBuilder().getStack()).setDisplayName("&a" + rName); - - newR.setLore("").addLore("&7- Name: &f" + r.getDisplayBuilder().getDisplayName(true)); - newR.addLore("&7- Chance: &f" + r.getChance()); - newR.addLore("&7- Give display item: &f" + r.isGiveDisplayItem()); - newR.addLore("&7- Give display item WITH lore: &f" + r.isGiveDisplayItemLore()); - newR.addLore("&7- Commands to run: &f" + r.getCommands().size()); - newR.addLore("&7- Rarity: &f" + r.getRarity()); - - newR.addLore("").addLore("&eClick to add to the crate."); - - ib.setItem(i, newR); - i++; - displayedRewards++; - } - - if (page != 1) { - ib.setItem(2, new ItemBuilder(XMaterial.ARROW).setDisplayName("&aGo back a page")); - } - - if ((CReward.getAllRewards().size() / 28) + (CReward.getAllRewards().size() % 28 == 0 ? 0 : 1) != page) { - ib.setItem(6, new ItemBuilder(XMaterial.ARROW).setDisplayName("&aGo forward a page")); - } - - ib.open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - if (slot == 2 && XMaterial.ARROW.isSimilar(getIb().getInv().getItem(slot))) { - page--; - open(); - } else if (slot == 6 && XMaterial.ARROW.isSimilar(getIb().getInv().getItem(slot))) { - page++; - open(); - } else if (slot == 0) { - up(); - } else if (getIb().getInv().getItem(slot) != null) { - String rName = ChatUtils.removeColor(getIb().getInv().getItem(slot).getItemMeta().getDisplayName()); - reward.setFallbackRewardName(rName); - ChatUtils.msgSuccess(getP(), "Set the fallback reward to " + rName); - up(); - } - } - - @Override - public boolean handleInput(String value, String input) { - return false; - } - -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/rewards/IGCMenuReward.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/rewards/IGCMenuReward.java deleted file mode 100644 index 2904162..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/rewards/IGCMenuReward.java +++ /dev/null @@ -1,287 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.fileconfigs.rewards; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.options.CReward; -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCListEditor; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.inputmenus.InputMenu; -import me.ztowne13.customcrates.interfaces.igc.items.IGCItemEditor; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.Utils; -import org.bukkit.entity.Player; - -/** - * Created by ztowne13 on 3/22/16. - */ -public class IGCMenuReward extends IGCMenu { - Reward reward; - boolean unsavedChanges = false; - - public IGCMenuReward(SpecializedCrates cc, Player p, IGCMenu lastMenu, String rName) { - super(cc, p, lastMenu, "&7&l> &6&l" + rName); - - if (CReward.getAllRewards().containsKey(rName)) { - reward = CReward.getAllRewards().get(rName); - } else { - reward = new Reward(getCc(), rName); - reward.loadFromConfig(); - reward.loadChance(); - CReward.getAllRewards().put(rName, reward); - } - } - - @Override - public void openMenu() { - - InventoryBuilder ib = createDefault(45); - - getIb().setItem(0, IGCDefaultItems.SAVE_BUTTON.getIb().setDisplayName("&aSave the reward to file") - .setLore("&7Save your current changes")); - getIb().setItem(36, IGCDefaultItems.EXIT_BUTTON.getIb()); - - ib.setItem(4, new ItemBuilder(XMaterial.LIGHT_BLUE_DYE, 1).setDisplayName("&a" + reward.getRewardName()).addLore("") - .addAutomaticLore("&e", 40, - "The &6&ldisplay &6&lname &6&levery &6&lplayer &6&lsees &e is not NOT the reward name " + - "- that is only an identifier to add rewards to crates. To edit the actual reward display name, please do so in the " + - "display-item editor.")); - ib.setItem(8, - new ItemBuilder(XMaterial.RED_CARPET, 1).setDisplayName("&cDelete this reward") - .addAutomaticLore("&7", 30, "You will have to confirm before deleting.")); - - //Commands - ItemBuilder commands = - new ItemBuilder(reward.getCommands() == null || reward.getCommands().isEmpty() ? XMaterial.RED_DYE : - XMaterial.COMMAND_BLOCK, 1) - .setDisplayName("&aEdit the commands") - .setLore("&7Current value: "); - if (reward.getCommands() != null && !reward.getCommands().isEmpty()) { - for (String cmds : reward.getCommands()) { - commands.addLore("&7" + cmds); - } - } else { - commands.addLore(getName(null)); - } - commands.addLore("").addAutomaticLore("&f", 30, - "Use %player% as a placeholder for the player's name. Use %amountX-Y% for a random number between X and Y. Ex: %amount1000-10000%"); - ib.setItem(22, commands); - - // Display item - ItemBuilder displayItem = new ItemBuilder(reward.getDisplayBuilder().getStack()); - displayItem.clearLore(); - displayItem.setDisplayName("&aEdit the display item"); - displayItem.addLore(""); - displayItem.addAutomaticLore("&f", 40, - "Edit things like the &edisplay &ename&f, lore, enchantments, potion effects, etc."); - ib.setItem(11, displayItem); - - // Chance - ib.setItem(23, - new ItemBuilder( - reward.getChance() == null || reward.getChance() == 0 ? XMaterial.RED_DYE : - XMaterial.FISHING_ROD, - 1) - .setDisplayName("&aEdit the chance").setLore("&7Current value: ") - .addLore("&7" + getName(reward.getChance() == 0 ? null : (reward.getChance() + ""))).addLore("") - .addAutomaticLore("&f", 30, "This is the actual chance of the lore.")); - - // Rarity Level (Tier) - ib.setItem(24, - new ItemBuilder(XMaterial.DIAMOND_BLOCK, 1) - .setDisplayName("&aEdit the rarity level") - .setLore("&7Current value: ") - .addLore("&7" + getName(reward.getRarity())).addLore("").addAutomaticLore("&f", 30, - "This is the 'tier' of the reward. If you aren't using tiers, ignore this.")); - - // Give display item - ItemBuilder giveDisplayItem = new ItemBuilder(XMaterial.ITEM_FRAME, 1); - giveDisplayItem.setDisplayName("&aGive the Display Item"); - giveDisplayItem.addLore("&7Current value: "); - giveDisplayItem.addLore("&7" + reward.isGiveDisplayItem()); - giveDisplayItem.addLore(""); - giveDisplayItem.addAutomaticLore("&f", 30, - "In addition to running the commands, should the player be given the display item when this reward is won?"); - ib.setItem(31, giveDisplayItem); - - // Give display item lore - ItemBuilder giveDisplayItemLore = new ItemBuilder(XMaterial.PAPER, 1); - giveDisplayItemLore.setDisplayName("&aGive the Display Item with Lore"); - giveDisplayItemLore.addLore("&7Current value: "); - giveDisplayItemLore.addLore("&7" + reward.isGiveDisplayItemLore()); - giveDisplayItemLore.addLore(""); - giveDisplayItemLore.addAutomaticLore("&f", 30, - "IF the display item is being given to the player, should it include it's display-item lore?"); - ib.setItem(32, giveDisplayItemLore); - - // Give display item name - ItemBuilder giveDisplayItemName = new ItemBuilder(XMaterial.BOOK, 1); - giveDisplayItemName.setDisplayName("&aGive the Display Item with its Name"); - giveDisplayItemName.addLore("&7Current value: "); - giveDisplayItemName.addLore("&7" + reward.isGiveDisplayItemName()); - giveDisplayItemName.addLore(""); - giveDisplayItemName.addAutomaticLore("&f", 30, - "IF the display item is being given to the player, should it include it's display-item name? or should the name be removed?"); - ib.setItem(33, giveDisplayItemName); - - // Fallback reward - ItemBuilder fallbackReward = new ItemBuilder(XMaterial.DIAMOND); - fallbackReward.setDisplayName("&aFallback Reward Settings"); - fallbackReward.addLore(""); - fallbackReward.addAutomaticLore("&f", 30, "Specify the fallback reward permission and" + - " the name of the fallback reward itself. A fallback reward is given IF a player has the correct permission. This is to" + - " help prevent players from winning duplicate ranks, etc."); - ib.setItem(29, fallbackReward); - - getIb().open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - if (slot == 8) { - String n = ChatUtils.removeColor(getIb().getInv().getItem(slot).getItemMeta().getDisplayName()); - if (n.equalsIgnoreCase("Confirm deletion")) { - reward.delete(true); - up(); - } else { - try { - ItemBuilder builder = new ItemBuilder(getIb().getInv().getItem(slot)).setDisplayName("&cConfirm deletion") - .setLore("&7Crates that use this reward:"); - boolean none = true; - for (String s : reward.delete(false).replace("[", "").replace("]", "").split(", ")) { - none = false; - builder.addLore("&7" + s); - } - if (none) { - builder.addLore("&7none"); - } - getIb().setItem(slot, builder); - } catch (Exception exc) { - exc.printStackTrace(); - } - } - } else if (slot == 22) { - new IGCListEditor(getCc(), getP(), this, "Commands Editor", "Command", reward.getCommands(), - XMaterial.COMMAND_BLOCK, 1).open(); - } else if (slot == 11) { - new IGCItemEditor(getCc(), getP(), this, reward.getSaveBuilder()).open(); - } else if (slot == 23) { - new InputMenu(getCc(), getP(), "chance", reward.getChance().toString(), Double.class, this); - } else if (slot == 24) { - new InputMenu(getCc(), getP(), "rarity", reward.getRarity(), String.class, this); - } else if (slot == 31) { - reward.setGiveDisplayItem(!reward.isGiveDisplayItem()); - open(); - } else if (slot == 32) { - reward.setGiveDisplayItemLore(!reward.isGiveDisplayItemLore()); - open(); - } else if (slot == 33) { - reward.setGiveDisplayItemName(!reward.isGiveDisplayItemName()); - open(); - } else if (slot == 29) { - new IGCMenuFallbackReward(getCc(), getP(), this, reward).open(); - } else if (slot == 0) { - ItemBuilder b = new ItemBuilder(getIb().getInv().getItem(slot)); - b.setDisplayName("&4&lERROR! &cPlease configure the"); - if (reward.getRewardName() == null) { - b.setLore("&creward name."); - } else if (reward.getSaveBuilder() == null) { - b.setLore("&creward item."); - } else if (reward.getChance() == null || reward.getChance() == 0) { - b.setLore("&cchance."); - } else if (reward.getRarity() == null) { - b.setLore("&crarity."); - } else { - b.setDisplayName("&2SUCCESS"); - b.setLore("&7Please reload the plugin for").addLore("&7these changes to take effect."); - reward.writeToFile(); - } - getIb().setItem(slot, b); - unsavedChanges = false; - return; - } else if (slot == 36) { - if (!unsavedChanges || ChatUtils.removeColor(getIb().getInv().getItem(slot).getItemMeta().getDisplayName()) - .equalsIgnoreCase("Are you sure?")) { - up(); - } else { - getIb().setItem(27, new ItemBuilder(getIb().getInv().getItem(slot)).setDisplayName("&4Are you sure?") - .setLore("&cYou have unsaved changes.").addLore("&7The changes will only be") - .addLore("&7temporary if not saved later").addLore("&7and will delete upon reload.")); - } - } else { - unsavedChanges = false; - return; - } - - unsavedChanges = true; - } - - @Override - public boolean handleInput(String value, String input) { - Object type = getInputMenu().getType(); - if (type == Integer.class) { - if (Utils.isInt(input)) { - if (value.equalsIgnoreCase("chance")) { - reward.setChance(Integer.parseInt(input)); - ChatUtils.msgSuccess(getP(), "Set " + value + " to '" + input + "'"); - } - } else { - ChatUtils.msgError(getP(), "This is not a valid number."); - return false; - } - } - if (type == Double.class) { - if (Utils.isDouble(input)) { - if (value.equalsIgnoreCase("chance")) { - reward.setChance(Double.parseDouble(input)); - ChatUtils.msgSuccess(getP(), "Set " + value + " to '" + input + "'"); - } - } else { - ChatUtils.msgError(getP(), "This is not a valid number."); - return false; - } - } else { - /*if(value.equalsIgnoreCase("rewardname")) - { - if(!input.contains(" ")) - { - r.setRewardName(input); - ChatUtils.msgSuccess(getP(), "Set " + value + " to '" + input + "'"); - return true; - } - ChatUtils.msgError(getP(), input + " cannot have any spaces in it."); - return false; - }*/ - if (value.equalsIgnoreCase("addcommand")) { - reward.getCommands().add(input.replace("/", "")); - ChatUtils.msgSuccess(getP(), "Added '" + input + "' to the reward commands."); - } else if (value.equalsIgnoreCase("removecommand")) { - for (String s : reward.getCommands()) { - if (s.equalsIgnoreCase(input)) { - reward.getCommands().remove(s); - ChatUtils.msgSuccess(getP(), "Removed '" + input + "' from the reward commands."); - return true; - } - } - ChatUtils.msgError(getP(), "'" + input + "' is not an existing command."); - return false; - } else if (value.equalsIgnoreCase("rarity")) { - reward.setRarity(input); - ChatUtils.msgSuccess(getP(), "Set " + value + " to '" + input + "'"); - } else if (value.equalsIgnoreCase("head-player-name")) { - reward.getSaveBuilder().setPlayerHeadName(input); - ChatUtils.msgSuccess(getP(), "Set " + value + " to '" + input + "'"); - } - } - return true; - } - - public String getName(String val) { - return reward == null || val == null ? "&cSet this value." : val; - } - -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/rewards/IGCMenuRewards.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/rewards/IGCMenuRewards.java deleted file mode 100644 index be0d58f..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/fileconfigs/rewards/IGCMenuRewards.java +++ /dev/null @@ -1,158 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.fileconfigs.rewards; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.options.CReward; -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.InventoryUtils; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.buttons.IGCButtonType; -import me.ztowne13.customcrates.interfaces.igc.inputmenus.InputMenu; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.entity.Player; - -/** - * Created by ztowne13 on 3/21/16. - */ -public class IGCMenuRewards extends IGCMenu { - int page; - - public IGCMenuRewards(SpecializedCrates cc, Player p, IGCMenu lastMenu, int page) { - super(cc, p, lastMenu, "&7&l> &6&lRewards.YML PG" + page, - new IGCButtonType[]{ - IGCButtonType.REWARD_FILTER - }, - new int[]{ - 8 - }); - this.page = page; - } - - @Override - public void openMenu() { - boolean newValues = false; - - CReward.loadAll(getCc(), getP()); - - int slots = Math.min(CReward.getAllRewards().size() - ((page - 1) * 28), 28); - - slots = InventoryUtils.getRowsFor(2, slots) + 9; - - - setInventoryName("&7&l> &6&lRewards.YML PG" + page); - InventoryBuilder ib = createDefault(slots, 27); - - ib.setItem(0, IGCDefaultItems.SAVE_ONLY_BUTTON.getIb()); - ib.setItem(9, IGCDefaultItems.RELOAD_BUTTON.getIb()); - ib.setItem(ib.getInv().getSize() - 9, IGCDefaultItems.EXIT_BUTTON.getIb()); - ib.setItem(4, - new ItemBuilder(XMaterial.PAPER).setDisplayName("&aCreate a new Reward").setLore("&7Click me to create a new") - .addLore("&7reward.")); - - ItemBuilder dragAndDrop = new ItemBuilder(XMaterial.CHEST_MINECART); - dragAndDrop.setDisplayName("&aDrag and Drop Rewards"); - dragAndDrop.addLore("").addAutomaticLore("&f", 30, - "Create up to 54 rewards at once! Add display names, lores, enchants, potion effects, amounts, and nbt-tags beforehand and have it all save at once!"); - ib.setItem(5, dragAndDrop); - - int i = 10; - int toSkip = ((page - 1) * 28); - int skipped = 0; - int displayedRewards = 0; - - for (Reward r : CReward.getAllRewardsSorted(getCc(), (CReward.RewardSortType) getButtons()[0].getValue()).values()) { - String rName = r.getRewardName(); - - if (toSkip > skipped || displayedRewards >= 28) { - skipped++; - continue; - } - - if (i % 9 == 8) { - i += 2; - } - - r.checkIsNeedMoreConfig(); - ItemBuilder newR; - - if (r.isNeedsMoreConfig()) - newR = new ItemBuilder(XMaterial.BARRIER).setDisplayName("&4&l" + rName) - .setLore("&cThis reward isn't fully configured,").addLore("&cplease fix it and reload the plugin."); - else - newR = new ItemBuilder(r.getDisplayBuilder().getStack()).setDisplayName("&a" + rName); - - newR.addLore("").addLore("&7Used by crates:").addLore(""); - for (String s : r.delete(false).replace("[", "").replace("]", "").split(", ")) { - newR.addLore("&7- &f" + s); - } - - newR.addLore("").addLore("&eClick to edit."); - - ib.setItem(i, newR); - i++; - displayedRewards++; - } - - if (page != 1) { - ib.setItem(2, new ItemBuilder(XMaterial.ARROW).setDisplayName("&aGo back a page")); - } - - if ((CReward.getAllRewards().size() / 28) + (CReward.getAllRewards().size() % 28 == 0 ? 0 : 1) != page) { - ib.setItem(6, new ItemBuilder(XMaterial.ARROW).setDisplayName("&aGo forward a page")); - } - - ib.open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - if (slot == 0) { - //getP().closeInventory(); - getCc().getRewardsFile().save(); - ChatUtils.msgSuccess(getP(), "Saved the Rewards.YML file."); - //getCc().reload(); - } else if (slot == 2 && XMaterial.ARROW.isSimilar(getIb().getInv().getItem(slot))) { - page--; - open(); - } else if (slot == 6 && XMaterial.ARROW.isSimilar(getIb().getInv().getItem(slot))) { - page++; - open(); - } else if (slot == 9) { - reload(); - } else if (slot == getIb().getInv().getSize() - 9) { - up(); - } else if (slot == 5) { - new IGCDragAndDrop(getCc(), getP(), this).open(); - } else if (slot == 4) { - new InputMenu(getCc(), getP(), "rewardName", "null", - "No spaces allowed. No duplicate names. &7&oNote: These 'reward names' will never be seen by your player: they are just an 'identifier'.", - String.class, this, true); - } else if (getIb().getInv().getItem(slot) != null) { - String rName = ChatUtils.removeColor(getIb().getInv().getItem(slot).getItemMeta().getDisplayName()); - new IGCMenuReward(getCc(), getP(), this, rName).open(); - } - } - - @Override - public boolean handleInput(String value, String input) { - if (value.equalsIgnoreCase("rewardName")) { - if (!input.contains(" ")) { - - if (!CReward.rewardNameExists(getCc(), input)) { - new IGCMenuReward(getCc(), getP(), this, input).open(); - } else { - ChatUtils.msgError(getP(), - "This name already exists. &7&oNote: These 'reward names' will never be seen by your player: they are just an identifier."); - } - } else { - ChatUtils.msgError(getP(), - "Your reward name cannot have a space. &7&oNote: These 'reward names' will never be seen by your player: they are just an identifier."); - } - } - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/inputmenus/AnvilInputMenu.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/inputmenus/AnvilInputMenu.java deleted file mode 100644 index 2eeb180..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/inputmenus/AnvilInputMenu.java +++ /dev/null @@ -1,46 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.inputmenus; - -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.entity.Player; - -/** - * Created by ztowne13 on 6/13/16. - */ -public class AnvilInputMenu extends InputMenuGUI { - public AnvilInputMenu(InputMenu im) { - super(im); - } - - public void openMenu() { - - } - - public void closeMenu(boolean saved) { - - } - - @Override - public void initMsg() { - Player p = im.getP(); - p.closeInventory(); - for (int i = 0; i < 20; i++) { - ChatUtils.msg(p, ""); - } - ChatUtils.msg(p, "&7----------------------------------------"); - ChatUtils.msg(p, "&aYou are currently editing the &f" + im.value + " &avalue."); - ChatUtils.msg(p, "&BCurrent Value: &f" + im.currentValue); - if (!im.formatExp.equalsIgnoreCase("")) { - ChatUtils.msg(p, "&a" + im.formatExp); - } - ChatUtils.msg(p, "&7----------------------------------------"); - ChatUtils.msg(p, "&6Please write the value you'd like to set it IN THE ANVIL."); - ChatUtils.msg(p, "&e&oClose the inventory to exit the current configuration session."); - ChatUtils.msg(p, "&c&oClick the paper to save your work."); - } - - @Override - public void runFor(IGCMenu igcm, String s) { - - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/inputmenus/ChatInputMenu.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/inputmenus/ChatInputMenu.java deleted file mode 100644 index 1cdd53b..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/inputmenus/ChatInputMenu.java +++ /dev/null @@ -1,47 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.inputmenus; - -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.entity.Player; - -/** - * Created by ztowne13 on 6/13/16. - */ -public class ChatInputMenu extends InputMenuGUI { - public ChatInputMenu(InputMenu im) { - super(im); - } - - @Override - public void initMsg() { - Player p = im.getP(); - - p.closeInventory(); - for (int i = 0; i < 20; i++) { - ChatUtils.msg(p, ""); - } - ChatUtils.msg(p, "&7----------------------------------------"); - ChatUtils.msg(p, "&aYou are currently editing the &f" + im.value + " &avalue."); - ChatUtils.msg(p, "&BCurrent Value: &f" + im.currentValue); - if (!im.formatExp.equalsIgnoreCase("")) { - ChatUtils.msg(p, "&a" + im.formatExp); - } - ChatUtils.msg(p, "&7----------------------------------------"); - ChatUtils.msg(p, "&6Please write the value you'd like to set it to below."); - ChatUtils.msg(p, "&e&oType 'exit' to exit the current configuration session."); - } - - @Override - public void runFor(IGCMenu igcm, String s) { - if (s.equalsIgnoreCase("exit")) { - igcm.open(); - igcm.setInputMenu(null); - } else { - - if (im.inputMenu.handleInput(im.value, s)) { - igcm.open(); - igcm.setInputMenu(null); - } - } - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/inputmenus/InputMenu.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/inputmenus/InputMenu.java deleted file mode 100644 index f98654f..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/inputmenus/InputMenu.java +++ /dev/null @@ -1,152 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.inputmenus; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - -/** - * Created by ztowne13 on 3/15/16. - */ -public class InputMenu { - SpecializedCrates cc; - Player p; - IGCMenu inputMenu; - String value; - String formatExp; - String currentValue; - boolean withoutColor; - Object type; - //SettingsValues sv; - - /*public InputMenu(SpecializedCrates cc, Player p, SettingsValues sv) - { - this.p = p; - this.sv = sv; - this.cc = cc; - }*/ - - public InputMenu(SpecializedCrates cc, Player p, String value, String currentValue, Object type, IGCMenu inputMenu) { - this(cc, p, value, currentValue, "", type, inputMenu, false); - } - - public InputMenu(SpecializedCrates cc, Player p, String value, String currentValue, Object type, IGCMenu inputMenu, - boolean withoutColor) { - this(cc, p, value, currentValue, "", type, inputMenu, withoutColor); - } - - public InputMenu(SpecializedCrates cc, Player p, String value, String currentValue, String formatExp, Object type, - IGCMenu inputMenu) { - this(cc, p, value, currentValue, formatExp, type, inputMenu, false); - } - - public InputMenu(SpecializedCrates cc, Player p, String value, String currentValue, String formatExp, Object type, - IGCMenu inputMenu, boolean withoutColor) { - this.p = p; - this.cc = cc; - this.value = value; - this.currentValue = currentValue; - this.inputMenu = inputMenu; - this.formatExp = formatExp; - this.type = type; - this.withoutColor = withoutColor; - - inputMenu.setInputMenu(this); - - initMsg(); - } - - private void initMsg() { - p.closeInventory(); - for (int i = 0; i < 20; i++) { - ChatUtils.msg(p, ""); - } - ChatUtils.msg(p, "&7----------------------------------------"); - ChatUtils.msg(p, "&aYou are currently editing the &f" + value + " &avalue."); - ChatUtils.msg(p, "&BCurrent Value: &f" + currentValue); - if (!formatExp.equalsIgnoreCase("")) { - ChatUtils.msg(p, "&d" + formatExp); - } - ChatUtils.msg(p, "&7----------------------------------------"); - ChatUtils.msg(p, "&6Please write the value you'd like to set it to below."); - ChatUtils.msg(p, "&e&oType 'exit' to exit the current configuration session."); - } - - public void runFor(IGCMenu igcm, String s) { - if (type != String.class || withoutColor) { - s = ChatUtils.removeColor(s); - } - - if (s.equalsIgnoreCase("exit")) { - reopenLater(igcm); - } else { - if (inputMenu.handleInput(value, s)) { - reopenLater(igcm); - } - } - } - - public void reopenLater(final IGCMenu igcm) { - Bukkit.getScheduler().runTaskLater(getCc(), () -> { - igcm.open(); - igcm.setInputMenu(null); - }, 1); - } - - public SpecializedCrates getCc() { - return cc; - } - - public void setCc(SpecializedCrates cc) { - this.cc = cc; - } - - public Player getP() { - return p; - } - - public void setP(Player p) { - this.p = p; - } - - public IGCMenu getInputMenu() { - return inputMenu; - } - - public void setInputMenu(IGCMenu inputMenu) { - this.inputMenu = inputMenu; - } - - public String getValue() { - return value; - } - - public void setValue(String value) { - this.value = value; - } - - public String getFormatExp() { - return formatExp; - } - - public void setFormatExp(String formatExp) { - this.formatExp = formatExp; - } - - public String getCurrentValue() { - return currentValue; - } - - public void setCurrentValue(String currentValue) { - this.currentValue = currentValue; - } - - public Object getType() { - return type; - } - - public void setType(Object type) { - this.type = type; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/inputmenus/InputMenuGUI.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/inputmenus/InputMenuGUI.java deleted file mode 100644 index 9c83cf8..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/inputmenus/InputMenuGUI.java +++ /dev/null @@ -1,27 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.inputmenus; - -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; - -/** - * Created by ztowne13 on 6/13/16. - */ -public abstract class InputMenuGUI { - InputMenu im; - - public InputMenuGUI(InputMenu im) { - this.im = im; - } - - public abstract void initMsg(); - - public abstract void runFor(IGCMenu igcm, String s); - - - public InputMenu getIm() { - return im; - } - - public void setIm(InputMenu im) { - this.im = im; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/items/IGCColoredArmour.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/items/IGCColoredArmour.java deleted file mode 100644 index fcee7c3..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/items/IGCColoredArmour.java +++ /dev/null @@ -1,95 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.items; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.inputmenus.InputMenu; -import me.ztowne13.customcrates.interfaces.items.EditableItem; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.interfaces.items.attributes.RGBColor; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.entity.Player; - -public class IGCColoredArmour extends IGCMenu { - EditableItem item; - - public IGCColoredArmour(SpecializedCrates cc, Player p, IGCMenu lastMenu, EditableItem item) { - super(cc, p, lastMenu, "&7&l> &6&lColor"); - this.item = item; - } - - @Override - public void openMenu() { - - InventoryBuilder ib = createDefault(27); - - ib.setItem(0, IGCDefaultItems.EXIT_BUTTON.getIb()); - - ItemBuilder red = new ItemBuilder(XMaterial.RED_DYE, 1); - red.setDisplayName("&cEdit the RED of RGB"); - red.addLore("").addLore("&7Current value: ").addLore("&f" + item.getColor().getRed()); - - ItemBuilder green = new ItemBuilder(XMaterial.LIME_DYE, 1); - green.setDisplayName("&aEdit the GREEN of RGB"); - green.addLore("").addLore("&7Current value: ").addLore("&f" + item.getColor().getGreen()); - - ItemBuilder blue = new ItemBuilder(XMaterial.LIGHT_BLUE_DYE, 1); - blue.setDisplayName("&bEdit the BLUE of RGB"); - blue.addLore("").addLore("&7Current value: ").addLore("&f" + item.getColor().getBlue()); - - ib.setItem(11, red); - ib.setItem(13, green); - ib.setItem(15, blue); - - ib.open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - switch (slot) { - case 0: - up(); - break; - case 11: - new InputMenu(getCc(), getP(), "red", item.getColor().getRed() + "", - "The RED of RGB.", Float.class, this); - break; - case 13: - new InputMenu(getCc(), getP(), "green", item.getColor().getGreen() + "", - "The GREEN of RGB.", Float.class, this); - break; - case 15: - new InputMenu(getCc(), getP(), "blue", item.getColor().getBlue() + "", - "The BLUE of RGB.", Float.class, this); - break; - } - } - - @Override - public boolean handleInput(String value, String input) { - int inputAsFloat; - try { - inputAsFloat = Integer.parseInt(input); - } catch (Exception exc) { - ChatUtils.msgError(getP(), input + " is not a valid number."); - return false; - } - - RGBColor rgbColor = item.getColor(); - - if (value.equalsIgnoreCase("red")) - rgbColor.setRed(inputAsFloat); - else if (value.equalsIgnoreCase("green")) - rgbColor.setGreen(inputAsFloat); - else if (value.equalsIgnoreCase("blue")) - rgbColor.setBlue(inputAsFloat); - - item.setColor(rgbColor); - - ChatUtils.msgSuccess(getP(), "Successfully set " + value + " to " + input + "."); - return true; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/igc/items/IGCItemEditor.java b/src/main/java/me/ztowne13/customcrates/interfaces/igc/items/IGCItemEditor.java deleted file mode 100644 index 5b851dc..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/igc/items/IGCItemEditor.java +++ /dev/null @@ -1,334 +0,0 @@ -package me.ztowne13.customcrates.interfaces.igc.items; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.interfaces.InventoryBuilder; -import me.ztowne13.customcrates.interfaces.igc.IGCDefaultItems; -import me.ztowne13.customcrates.interfaces.igc.IGCListEditor; -import me.ztowne13.customcrates.interfaces.igc.IGCListSelector; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.inputmenus.InputMenu; -import me.ztowne13.customcrates.interfaces.items.CompressedPotionEffect; -import me.ztowne13.customcrates.interfaces.items.EditableItem; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.interfaces.items.attributes.CompressedEnchantment; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.Utils; -import me.ztowne13.customcrates.utils.VersionUtils; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemFlag; -import org.bukkit.inventory.ItemStack; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; - -public class IGCItemEditor extends IGCMenu { - - EditableItem editableItem; - - public IGCItemEditor(SpecializedCrates cc, Player p, IGCMenu lastMenu, EditableItem editableItem) { - super(cc, p, lastMenu, "&7&l> &6&lItem Editor"); - - this.editableItem = editableItem; - } - - @Override - public void openMenu() { - editableItem.reapplyLore(); - editableItem.reapplyEnchantments(); - editableItem.reapplyPotionEffects(); - editableItem.reapplyNBTTags(); - editableItem.reapplyItemFlags(); - - InventoryBuilder ib = createDefault(45); - - ib.setItem(0, IGCDefaultItems.EXIT_BUTTON.getIb()); - - // Lore - ItemBuilder lore = new ItemBuilder(XMaterial.WRITABLE_BOOK, 1); - lore.setDisplayName("&aEdit the lore"); - lore.addLore("&7Current value:"); - for (String loreLine : editableItem.getLore()) - lore.addLore("&7- " + loreLine); - lore.addLore("").addAutomaticLore("&f", 30, - "Edit the lore of the display item. Remove all lines and leave the lore blank to use the default lore in the config.yml"); - - // Display name - ItemBuilder displayName = new ItemBuilder(XMaterial.PAPER, 1); - displayName.setDisplayName("&aEdit the display name"); - displayName.addLore("&7Current value:").addLore("&7" + editableItem.getDisplayName(false)); - displayName.addLore("").addAutomaticLore("&f", 30, "Set the display name of the display item."); - - // Enchantments - ItemBuilder enchantments = new ItemBuilder(XMaterial.ENCHANTING_TABLE, 1); - enchantments.setDisplayName("&aEdit the enchantments"); - enchantments.addLore("&7Current value:"); - for (CompressedEnchantment enchantment : editableItem.getEnchantments()) - enchantments.addLore("&7- " + enchantment.toString()); - enchantments.addLore("") - .addAutomaticLore("&f", 30, "Edit the enchantments of the display item. FORMATTED: enchantment;level"); - - // NBT Tags - ItemBuilder nbtTags = new ItemBuilder(XMaterial.NAME_TAG, 1); - nbtTags.setDisplayName("&aEdit the nbt-tags"); - nbtTags.addLore("&7Current value:"); - for (String tag : editableItem.getNBTTags()) - nbtTags.addLore("&7- " + tag); - nbtTags.addLore("").addAutomaticLore("&f", 30, - "Edit the NBT Tags of an item."); - - // Glow - ItemBuilder glow = - new ItemBuilder(editableItem.isGlowing() ? XMaterial.NETHER_STAR : XMaterial.QUARTZ, 1); - glow.setDisplayName("&aEdit if the item is glowing"); - glow.addLore("&7Current value:").addLore("&7" + editableItem.isGlowing()); - glow.addLore("").addAutomaticLore("&f", 30, - "This will toggle whether or not the display item will have a glowing effect. For enchanted items, if this value is true, the enchantments will be hidden."); - glow.addLore("").addAutomaticLore("&e&l", 30, "Same as HIDE ENCHANTS"); - - XMaterial editableItemDM = XMaterial.matchXMaterial(editableItem.getStack()); - - // Player head - ItemBuilder playerHead = new ItemBuilder(XMaterial.PLAYER_HEAD, 1); - if (editableItemDM.equals(XMaterial.PLAYER_HEAD)) { - playerHead.setDisplayName("&aEdit the player-head's name."); - playerHead.addLore("&7Current value:").addLore("&7" + editableItem.getPlayerHeadName()); - playerHead.addLore("") - .addAutomaticLore("&f", 30, "Edit the name of the player head to apply a skin to the skull."); - } else { - playerHead.setDisplayName("&cEdit the player-head's name"); - playerHead.addLore("").addLore("&cCurrent item is not a skull."); - } - - // Potion - ItemBuilder potion = new ItemBuilder(XMaterial.POTION, 1); - if (editableItemDM.name().contains("POTION")) { - potion.setDisplayName("&aEdit the potion effects"); - potion.addLore("&7Current value:"); - for (CompressedPotionEffect potionEffect : editableItem.getPotionEffects()) - potion.addLore("&7- " + potionEffect.toString()); - potion.addLore("").addAutomaticLore("&f", 30, - "Edit the potion effects of the display item. FORMATTED: potioneffect;duration;amplifier"); - } else { - potion.setDisplayName("&cEdit the potion effects"); - potion.addLore("").addLore("&cCurrent item is not a potion."); - } - - // Amount - ItemBuilder amount = new ItemBuilder(XMaterial.STONE_BUTTON, 1); - amount.setDisplayName("&aEdit the amount."); - amount.addLore("&7Current value:"); - amount.addLore("&7" + editableItem.getStack().getAmount()); - amount.addLore("").addAutomaticLore("&f", 30, "Edit the amount of in the stack of items."); - - // Edit item - ItemBuilder item = new ItemBuilder(editableItem); - item.clearLore(); - item.setDisplayName("&aEdit the item material"); - item.addLore("&7Current value:").addLore("&7" + editableItemDM.name()); - item.addLore("").addAutomaticLore("&f", 30, - "Edit ONLY the material of this item, none of the other values will be changed."); - - // Edit everything - ItemBuilder everything = new ItemBuilder(editableItem); - everything.clearLore(); - everything.setDisplayName("&aEdit EVERYTHING"); - everything.addLore("").addAutomaticLore("&f", 30, "Edit EVERYTHING AT ONCE. This will update all of these " + - "values to the item you are HOLDING IN HAND. The only value it will not effect is the 'glowing' effect, everything " + - "else will be updated: name, lore, enchants, etc. Therefore, everything will be overwritten!"); - - // Edit attributes - ItemBuilder attributes = new ItemBuilder(XMaterial.REDSTONE, 1); - attributes.setDisplayName("&aEdit the Item Flags"); - attributes.addLore("").addAutomaticLore("&f", 30, "Edit the attributes of the item such as HIDE_ENCHANTS, " + - "HIDE_ATTRIBUTES, etc."); - attributes.addLore("").addAutomaticLore("&c", 30, "Note: If glow is set to true, HIDE_ENCHANTS will ALWAYS" + - " be true unless glow: false."); - - // Edit color - ItemBuilder color = new ItemBuilder(XMaterial.LIGHT_BLUE_DYE, 1); - if (item.isColorable()) { - color.setDisplayName("&aEdit the armour Color"); - color.addLore("&7Current Value:") - .addLore("&7" + item.getColor().getRed() + ", " + item.getColor().getGreen() + ", " + item.getColor().getBlue()); - color.addLore("").addAutomaticLore("&f", 30, "Edit the red, green, and blue values of the colored armour."); - } else { - color.setDisplayName("&cEdit the armour Color"); - color.addLore("").addLore("&cThis item is not colorable."); - } - - // Damage - ItemBuilder damage = new ItemBuilder(XMaterial.GOLDEN_AXE); - damage.setDamage(20); - damage.setDisplayName("&aEdit the item damage"); - damage.addLore("&7Current Value: "); - damage.addLore("&7" + item.getDamage()); - damage.addLore(""); - damage.addAutomaticLore("&f", 30, - "This is to set the damage of an item, NOT TO SET THE DATA VALUE. " + - "If you want a 'damaged' item like red wool or acacia log (for example)," + - " use RED_WOOL or ACACIA_LOG - EVEN ON 1.8-1.12. This value is ONLY to damage things like swords."); - - ib.setItem(10, everything); - ib.setItem(11, item); - ib.setItem(13, displayName); - ib.setItem(14, lore); - ib.setItem(15, enchantments); - ib.setItem(16, glow); - ib.setItem(22, nbtTags); - ib.setItem(23, amount); - ib.setItem(24, potion); - ib.setItem(25, attributes); - ib.setItem(31, playerHead); - ib.setItem(32, color); - ib.setItem(33, damage); - - ib.open(); - putInMenu(); - } - - @Override - public void handleClick(int slot) { - switch (slot) { - case 0: - up(); - break; - case 10: - ItemStack stack; - if (VersionUtils.Version.v1_9.isServerVersionOrLater()) - stack = getP().getInventory().getItemInMainHand(); - else - stack = getP().getItemInHand(); - - if (!stack.getType().equals(Material.AIR)) { - editableItem.setStack(stack.clone()); - editableItem.updateFromItem(); - open(); - } else { - ChatUtils.msgError(getP(), "You are not holding anything in your hand!"); - } - break; - case 11: - new InputMenu(getCc(), getP(), "item material", - XMaterial.matchXMaterial(editableItem.getStack()).toString(), Material.class, this); - break; - case 13: - new InputMenu(getCc(), getP(), "displayname", editableItem.getDisplayName(false), String.class, this); - break; - case 14: - new IGCListEditor(getCc(), getP(), this, "Lore", "Line", editableItem.getLore(), XMaterial.PAPER, 1) - .open(); - break; - case 15: - new IGCListEditor(getCc(), getP(), this, "Enchantments", "Enchantment", editableItem.getEnchantments(), - XMaterial.ENCHANTED_BOOK, 1, CompressedEnchantment.class, "fromString", - "That is not formatted ENCHANTMENT;LEVEL or either the enchantment name is wrong or the level is not a number.") - .open(); - break; - case 16: - editableItem.setGlowing(!editableItem.isGlowing()); - open(); - break; - case 22: - new IGCListEditor(getCc(), getP(), this, "NBT Tags", "Tag", editableItem.getNBTTags(), - XMaterial.NAME_TAG, 1).open(); - break; - case 23: - new InputMenu(getCc(), getP(), "amount", editableItem.getStack().getAmount() + "", Integer.class, this); - break; - case 24: - if (XMaterial.matchXMaterial(editableItem.getStack()).name().contains("POTION")) - new IGCListEditor(getCc(), getP(), this, "Potion Effects", "Potion", editableItem.getPotionEffects(), - XMaterial.GLASS_BOTTLE, 1, CompressedPotionEffect.class, "fromString", - "That is not formatted POTIONTYPE;DURATION;AMPLIFIER or either the potion effect name " + - "is incorrect, or either the duration or amplifier aren't numbers.").open(); - else - ChatUtils.msgError(getP(), "The current item is not a potion."); - break; - case 25: - List descriptors = new ArrayList<>(); - List builders = new ArrayList<>(); - for (ItemFlag flag : ItemFlag.values()) { - descriptors.add(""); - if (editableItem.getItemFlags().contains(flag)) - builders.add(new ItemBuilder(XMaterial.LIME_WOOL, 1)); - else - builders.add(new ItemBuilder(XMaterial.RED_WOOL, 1)); - } - new IGCListSelector(getCc(), getP(), this, "Item Flags", Arrays.asList(ItemFlag.values()), - XMaterial.PAPER, 1, - descriptors, builders).open(); - break; - case 31: - if (XMaterial.PLAYER_HEAD.isSimilar(editableItem.getStack())) - new InputMenu(getCc(), getP(), "player-head-name", editableItem.getPlayerHeadName(), String.class, - this, true); - else - ChatUtils.msgError(getP(), "The current item is not a player head or skull."); - break; - case 32: - if (editableItem.isColorable()) { - new IGCColoredArmour(getCc(), getP(), this, editableItem).open(); - } else { - ChatUtils.msgError(getP(), "The current item is not a colorable piece of armor"); - } - break; - case 33: - new InputMenu(getCc(), getP(), "damage", editableItem.getDamage() + "", Integer.class, this); - break; - } - } - - @Override - public boolean handleInput(String value, String input) { - if (value.equalsIgnoreCase("item material")) { - Optional optional = XMaterial.matchXMaterial(input); - if (optional.isPresent()) { - XMaterial dynamicMaterial = optional.get(); - dynamicMaterial.setType(editableItem.getStack()); - ChatUtils.msgSuccess(getP(), "Set the " + value + " to " + input); - return true; - } else { - ChatUtils.msgError(getP(), input + " is not a valid material name."); - } - } else if (value.equalsIgnoreCase("displayname")) { - editableItem.setDisplayName(input); - ChatUtils.msgSuccess(getP(), "Set the " + value + " to " + input); - return true; - } else if (value.equalsIgnoreCase("player-head-name")) { - editableItem.setPlayerHeadName(input); - ChatUtils.msgSuccess(getP(), "Set the " + value + " to " + input); - return true; - } else if (value.equalsIgnoreCase("amount")) { - if (Utils.isInt(input)) { - editableItem.getStack().setAmount(Integer.parseInt(input)); - ChatUtils.msgSuccess(getP(), "Set the amount to " + input); - return true; - } else { - ChatUtils.msgError(getP(), input + " is not a valid number."); - } - } else if (value.equalsIgnoreCase("damage")) { - if (Utils.isInt(input)) { - editableItem.setDamage(Integer.parseInt(input)); - ChatUtils.msgSuccess(getP(), "Set the damage to " + input); - return true; - } else { - ChatUtils.msgError(getP(), input + " is not a valid number."); - } - } else if (value.equalsIgnoreCase("Item Flags")) { - ItemFlag flag = ItemFlag.valueOf(input); - if (editableItem.getItemFlags().contains(flag)) { - editableItem.removeItemFlag(flag); - ChatUtils.msgSuccess(getP(), "Removed flag: " + flag.name()); - } else { - editableItem.addItemFlag(flag); - ChatUtils.msgSuccess(getP(), "Added flag: " + flag.name()); - } - } - return false; - } - -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/items/CompressedPotionEffect.java b/src/main/java/me/ztowne13/customcrates/interfaces/items/CompressedPotionEffect.java deleted file mode 100644 index 60fc619..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/items/CompressedPotionEffect.java +++ /dev/null @@ -1,46 +0,0 @@ -package me.ztowne13.customcrates.interfaces.items; - -import me.ztowne13.customcrates.utils.VersionUtils; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.PotionMeta; -import org.bukkit.potion.Potion; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; - -public class CompressedPotionEffect extends PotionEffect { - public CompressedPotionEffect(PotionEffectType potionEffectType, int duration, int amplifier) { - super(potionEffectType, duration, amplifier); - } - - public static CompressedPotionEffect fromString(String value) { - String[] split = value.split(";"); - - PotionEffectType potionEffectType = PotionEffectType.getByName(split[0]); - int duration = Integer.parseInt(split[1]); - int amplifier = Integer.parseInt(split[2]); - - return new CompressedPotionEffect(potionEffectType, duration, amplifier); - } - - ItemStack applyTo(ItemStack stack) { - if (VersionUtils.Version.v1_9.isServerVersionOrLater()) { - if (stack.getItemMeta() instanceof PotionMeta) { - PotionMeta potionMeta = (PotionMeta) stack.getItemMeta(); - - potionMeta.addCustomEffect(this, true); - stack.setItemMeta(potionMeta); - } - } else { - Potion pot = Potion.fromItemStack(stack); - pot.getEffects().add(this); - pot.apply(stack); - } - - return stack; - } - - @Override - public String toString() { - return getType().getName() + ";" + getDuration() + ";" + getAmplifier(); - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/items/EditableItem.java b/src/main/java/me/ztowne13/customcrates/interfaces/items/EditableItem.java deleted file mode 100644 index 2d1ab75..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/items/EditableItem.java +++ /dev/null @@ -1,71 +0,0 @@ -package me.ztowne13.customcrates.interfaces.items; - -import me.ztowne13.customcrates.interfaces.items.attributes.CompressedEnchantment; -import me.ztowne13.customcrates.interfaces.items.attributes.RGBColor; -import org.bukkit.inventory.ItemFlag; -import org.bukkit.inventory.ItemStack; - -import java.util.List; - -public interface EditableItem { - ItemStack getStack(); - - EditableItem setStack(ItemStack stack); - - EditableItem setDisplayName(String displayName); - - String getDisplayName(boolean useMaterialWhenNull); - - String getPlayerHeadName(); - - void setPlayerHeadName(String name); - - /** - * These functions are handled outside of the ItemStack - **/ - - void reapplyColor(); - - void reapplyNBTTags(); - - void reapplyPotionEffects(); - - void reapplyEnchantments(); - - void reapplyItemFlags(); - - void reapplyLore(); - - boolean isGlowing(); - - void setGlowing(boolean glow); - - List getNBTTags(); - - List getEnchantments(); - - List getPotionEffects(); - - List getLore(); - - List getItemFlags(); - - RGBColor getColor(); - - void setColor(RGBColor color); - - boolean isColorable(); - - void addItemFlag(ItemFlag flag); - - void removeItemFlag(ItemFlag flag); - - int getDamage(); - - void setDamage(int damage); - - /** - * Clears all the currently set values and updates them based on the current itemstack. - */ - void updateFromItem(); -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/items/ItemBuilder.java b/src/main/java/me/ztowne13/customcrates/interfaces/items/ItemBuilder.java deleted file mode 100644 index 5e41782..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/items/ItemBuilder.java +++ /dev/null @@ -1,569 +0,0 @@ -package me.ztowne13.customcrates.interfaces.items; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.interfaces.items.attributes.BukkitGlowEffect; -import me.ztowne13.customcrates.interfaces.items.attributes.CompressedEnchantment; -import me.ztowne13.customcrates.interfaces.items.attributes.RGBColor; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.VersionUtils; -import org.apache.commons.lang.WordUtils; -import org.bukkit.Bukkit; -import org.bukkit.Color; -import org.bukkit.OfflinePlayer; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.ItemFlag; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.*; -import org.bukkit.potion.Potion; -import org.bukkit.potion.PotionData; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionType; - -import java.util.*; - -public class ItemBuilder implements EditableItem { - private ItemStack stack; - - private boolean glowing = false; - private RGBColor rgbColor; - private List enchantments = null; - private List potionEffects = null; - private List nbtTags = null; - private List lore; - private List flags = null; - - public ItemBuilder(EditableItem builder) { - glowing = builder.isGlowing(); - stack = new ItemStack(builder.getStack()); - updateFromItem(); - } - - public ItemBuilder(ItemStack fromStack) { - stack = fromStack.clone(); - updateFromItem(); - } - - public ItemBuilder(XMaterial material) { - create(material, 1); - } - - public ItemBuilder(XMaterial material, int amount) { - create(material, amount); - } - - public void reset() { - getEnchantments().clear(); - getNBTTags().clear(); - getLore().clear(); - getPotionEffects().clear(); - getItemFlags().clear(); - rgbColor = null; - } - - public void updateFromItem() { - reset(); - - List cachedTags = NBTTagBuilder.getFrom(stack, false); - - // Enchantments - Map enchants; - if (getItemMeta() instanceof EnchantmentStorageMeta) { - EnchantmentStorageMeta meta = (EnchantmentStorageMeta) getItemMeta(); - enchants = meta.getStoredEnchants(); - } else { - enchants = stack.getEnchantments(); - } - enchants.forEach(this::addEnchantment); - - // Potion Effects - if (stack.hasItemMeta() && getItemMeta() instanceof PotionMeta) { - PotionMeta pm = (PotionMeta) getItemMeta(); - - if (VersionUtils.Version.v1_9.isServerVersionOrLater()) { - PotionData baseData = pm.getBasePotionData(); - if (baseData.getType().getEffectType() != null) { - addPotionEffect( - new CompressedPotionEffect(baseData.getType().getEffectType(), baseData.isExtended() ? 1 : 0, - baseData.isUpgraded() ? 1 : 0)); - } - - for (PotionEffect pe : pm.getCustomEffects()) { - addPotionEffect(new CompressedPotionEffect(pe.getType(), pe.getDuration(), pe.getAmplifier())); - } - } else { - Potion pot = Potion.fromItemStack(stack); - - try { - Potion toClearPot = Potion.fromItemStack(stack); - toClearPot.getEffects().clear(); - toClearPot.apply(stack); - } catch (Exception exc) { - // IGNORED - } - - addPotionEffect(new CompressedPotionEffect(pot.getType().getEffectType(), 1, 1)); - - ArrayList toAdd = new ArrayList<>(); - - for (PotionEffect pe : pot.getEffects()) { - toAdd.add(new CompressedPotionEffect(pe.getType(), pe.getDuration(), pe.getAmplifier())); - } - - for (CompressedPotionEffect effect : toAdd) { - addPotionEffect(effect); - } - } - } - - // NBT Tags - for (String tags : cachedTags) { - addNBTTag(tags); - } - - // Lore - if (stack.hasItemMeta() && stack.getItemMeta().hasLore()) { - for (String line : stack.getItemMeta().getLore()) - addLore(line); - } - - // Item Flags - if (stack.hasItemMeta()) { - for (ItemFlag flag : stack.getItemMeta().getItemFlags()) - addItemFlag(flag); - } - - // Coloured Armor - if (getItemMeta() instanceof LeatherArmorMeta) { - LeatherArmorMeta meta = (LeatherArmorMeta) getItemMeta(); - RGBColor newColor = - new RGBColor(meta.getColor().getRed(), meta.getColor().getGreen(), meta.getColor().getBlue()); - setColor(newColor); - } - } - - private void create(XMaterial material, int amount) { - stack = material.parseItem(); - stack.setAmount(amount); - if (material.name().endsWith("_SPAWN_EGG") && VersionUtils.Version.v1_12.isServerVersionOrEarlier()) - addNBTTag("EntityTag " + material.name().replace("_SPAWN_EGG", "")); - } - - public ItemMeta getItemMeta() { - if (getStack().getItemMeta() == null) { - return Bukkit.getItemFactory().getItemMeta(getStack().getType()); - } - return getStack().getItemMeta(); - } - - public void setItemMeta(ItemMeta itemMeta) { - getStack().setItemMeta(itemMeta); - } - - @Override - public ItemBuilder setDisplayName(String name) { - ItemMeta im = getItemMeta(); - if (im != null) { - if (name == null) { - im.setDisplayName(null); - } else { - im.setDisplayName(ChatUtils.toChatColor(name)); - } - setItemMeta(im); - } - return this; - } - - public void removeDisplayName() { - ItemMeta im = getItemMeta(); - if (im != null) { - im.setDisplayName(null); - setItemMeta(im); - } - } - - public String getDisplayNameFromChatColor(boolean useMaterialWhenNull) { - return ChatUtils.fromChatColor(getDisplayName(useMaterialWhenNull)); - } - - @Override - public String getDisplayName(boolean useMaterialWhenNull) { - if (useMaterialWhenNull) { - return hasDisplayName() ? getItemMeta().getDisplayName() : - WordUtils.capitalizeFully(getStack().getType().name().replace("_", " ")); - } - - return getItemMeta().getDisplayName(); - } - - public boolean hasDisplayName() { - return getItemMeta() != null && - getDisplayName(false) != null && - !getDisplayName(false).equalsIgnoreCase(""); - } - - public String getName(boolean strippedOfColor) { - return strippedOfColor ? ChatUtils.removeColor(getItemMeta().getDisplayName()) : getItemMeta().getDisplayName(); - } - - public ItemBuilder addLore(String s) { - getLore().add(s); - reapplyLore(); - return this; - } - - public ItemBuilder addAutomaticLore(String lineColor, int charLength, String lore) { - return addAutomaticLore(lineColor, charLength, false, lore); - } - - public ItemBuilder addAutomaticLore(String lineColor, int charLength, boolean maintainColor, String lore) { - String[] split = lore.split(" "); - int lineSize = 0; - StringBuilder currentLine = new StringBuilder(); - String lastLine = ""; - - for (String word : split) { - int wordLength = word.length(); - if (lineSize + wordLength <= charLength) { - lineSize += wordLength + 1; - currentLine.append(word).append(" "); - } else { - if (maintainColor) { - lineColor = ChatUtils.lastChatColor(lastLine); - } - String line = lineColor + currentLine.substring(0, currentLine.length() - 1); - addLore(line); - currentLine = new StringBuilder(word + " "); - lineSize = wordLength; - lastLine = line; - - - } - } - if (maintainColor) { - lineColor = ChatUtils.lastChatColor(lastLine); - } - if (lineSize != 0) - addLore(lineColor + currentLine.substring(0, currentLine.length() - 1)); - - return this; - } - - public ItemBuilder clearLore() { - getLore().clear(); - reapplyLore(); - return this; - } - - @Override - public List getLore() { - if (lore == null) - lore = new ArrayList<>(); - return lore; - } - - public ItemBuilder setLore(String s) { - clearLore(); - addLore(s); - - return this; - } - - @Override - public void reapplyLore() { - ItemMeta im = getItemMeta(); - - ArrayList colorizedLore = new ArrayList<>(); - for (String line : getLore()) - colorizedLore.add(ChatUtils.toChatColor(line)); - - im.setLore(colorizedLore); - setItemMeta(im); - } - - public void addEnchantment(Enchantment enchantment, int level) { - addEnchantment(new CompressedEnchantment(enchantment, level)); - } - - public void addEnchantment(CompressedEnchantment compressedEnchantment) { - getEnchantments().add(compressedEnchantment); - reapplyEnchantments(); - } - - public void addPotionEffect(CompressedPotionEffect compressedPotionEffect) { - getPotionEffects().add(compressedPotionEffect); - reapplyPotionEffects(); - } - - public void addNBTTag(String tag) { - getNBTTags().add(tag); - reapplyNBTTags(); - } - - public boolean hasNBTTag(String tag) { - for (String tagParsed : getNBTTags()) { - if (tagParsed.split(" ")[0].equalsIgnoreCase(tag)) { - return true; - } - } - return false; - } - - @Override - public void addItemFlag(ItemFlag flag) { - getItemFlags().add(flag); - reapplyItemFlags(); - } - - @Override - public void removeItemFlag(ItemFlag flag) { - getItemFlags().remove(flag); - reapplyItemFlags(); - } - - @Override - public String getPlayerHeadName() { - if (XMaterial.PLAYER_HEAD.isSimilar(getStack())) { - SkullMeta skullMeta = (SkullMeta) getItemMeta(); - return skullMeta.getOwner(); - } - - return null; - } - - @Override - public void setPlayerHeadName(String name) { - if (XMaterial.PLAYER_HEAD.isSimilar(getStack()) && Character.isLetterOrDigit(name.charAt(0))) { - SkullMeta skullMeta = (SkullMeta) getItemMeta(); - try { - UUID uuid = UUID.fromString(name); - OfflinePlayer op = Bukkit.getOfflinePlayer(uuid); - skullMeta.setOwningPlayer(op); - } catch (Exception exc) { - skullMeta.setOwner(name); - - } - setItemMeta(skullMeta); - } - } - - @Override - public boolean isGlowing() { - return glowing; - } - - @Override - public void setGlowing(boolean glow) { - BukkitGlowEffect ge = new BukkitGlowEffect(stack); - if (glow) - stack = ge.apply(); - else - stack = ge.remove(); - glowing = glow; - } - - @Override - public List getNBTTags() { - if (nbtTags == null) - nbtTags = new ArrayList<>(); - - return nbtTags; - } - - @Override - public void reapplyNBTTags() { - for (String tag : getNBTTags()) { - stack = NBTTagBuilder.applyTo(stack, tag); - } - } - - @Override - public List getItemFlags() { - if (flags == null) - flags = new ArrayList<>(); - - return flags; - } - - @Override - public void reapplyItemFlags() { - ItemMeta itemMeta = getItemMeta(); - - for (ItemFlag flag : itemMeta.getItemFlags()) { - itemMeta.removeItemFlags(flag); - } - - for (ItemFlag flag : getItemFlags()) { - itemMeta.addItemFlags(flag); - } - - setItemMeta(itemMeta); - } - - @Override - public List getEnchantments() { - if (enchantments == null) - enchantments = new ArrayList<>(); - - return enchantments; - } - - @Override - public void reapplyEnchantments() { - for (Enchantment enchantment : stack.getEnchantments().keySet()) - getItemMeta().removeEnchant(enchantment); - - for (CompressedEnchantment compressedEnchantment : getEnchantments()) { - compressedEnchantment.applyTo(this); - } - } - - @Override - public List getPotionEffects() { - if (potionEffects == null) - potionEffects = new ArrayList<>(); - - return potionEffects; - } - - @Override - public void reapplyPotionEffects() { - boolean first = true; - - if (!(getItemMeta() instanceof PotionMeta)) { - return; - } - - PotionMeta pm = (PotionMeta) getItemMeta(); - pm.clearCustomEffects(); - - if (!getPotionEffects().isEmpty()) { - - CompressedPotionEffect firstVal = getPotionEffects().get(0); - if (VersionUtils.Version.v1_9.isServerVersionOrLater()) { - boolean isOld = (firstVal.getAmplifier() == 1 && firstVal.getDuration() == 1); - - PotionData potionData = - new PotionData(PotionType.getByEffect(firstVal.getType()), firstVal.getDuration() == 1 && !isOld, - firstVal.getAmplifier() == 1 && !isOld); - pm.setBasePotionData(potionData); - } else { - Potion pot = new Potion(PotionType.getByEffect(firstVal.getType()), firstVal.getAmplifier() == 0 ? 1 : 2, - XMaterial.SPLASH_POTION.isSimilar(stack)); - pot.apply(stack); - first = false; - } - } - - setItemMeta(pm); - - for (CompressedPotionEffect compressedPotionEffect : getPotionEffects()) { - if (!first) - stack = compressedPotionEffect.applyTo(stack); - first = false; - } - } - - @Override - public void reapplyColor() { - if (isColorable() && getColor() != null) { - LeatherArmorMeta meta = (LeatherArmorMeta) getItemMeta(); - meta.setColor(Color.fromRGB(getColor().getRed(), getColor().getGreen(), getColor().getBlue())); - setItemMeta(meta); - } - } - - @Override - public RGBColor getColor() { - if (isColorable()) { - if (rgbColor == null) { - RGBColor newRGBColor = new RGBColor(160, 101, 64); - setColor(newRGBColor); - } - return rgbColor; - } - return null; - } - - @Override - public void setColor(RGBColor rgbColor) { - this.rgbColor = rgbColor; - reapplyColor(); - } - - @Override - public boolean isColorable() { - return getItemMeta() instanceof LeatherArmorMeta; - } - - @Override - public int hashCode() { - return Objects.hash(stack, glowing, rgbColor, enchantments, potionEffects, nbtTags, lore, flags); - } - - @Override - public boolean equals(Object obj) { - if (!(obj instanceof ItemBuilder)) { - return false; - } - - ItemBuilder compare = (ItemBuilder) obj; - - boolean loreEquals = true; - - if (getLore().size() == compare.getLore().size()) { - for (int i = 0; i < getLore().size(); i++) { - if (!getLore().get(i).equals(compare.getLore().get(i))) - loreEquals = false; - } - } else { - loreEquals = false; - } - - return !(!compare.hasDisplayName() && hasDisplayName()) - && !(compare.hasDisplayName() && !hasDisplayName()) - && ((!compare.hasDisplayName() && !hasDisplayName()) || - (compare.getDisplayName(false).equals(getDisplayName(false)))) - && loreEquals - && compare.getStack().getType().equals(getStack().getType()) - && compare.getStack().getAmount() == getStack().getAmount(); - } - - public ItemBuilder clone() { - return new ItemBuilder(this); - } - - @Override - public int getDamage() { - if (VersionUtils.Version.v1_13.isServerVersionOrLater() && getItemMeta() instanceof Damageable) { - Damageable meta = (Damageable) getItemMeta(); - return meta.getDamage(); - } else if (VersionUtils.Version.v1_12.isServerVersionOrEarlier()) { - return getStack().getDurability(); - } - return 0; - } - - @Override - public void setDamage(int damage) { - if (damage == 0 && getDamage() == 0) { - return; - } - - if (VersionUtils.Version.v1_13.isServerVersionOrLater() && getItemMeta() instanceof Damageable) { - Damageable meta = (Damageable) getItemMeta(); - meta.setDamage(damage); - setItemMeta((ItemMeta) meta); - } else if (VersionUtils.Version.v1_12.isServerVersionOrEarlier()) { - getStack().setDurability((short) damage); - } - } - - public ItemStack getStack() { - return stack; - } - - public ItemBuilder setStack(ItemStack stack) { - this.stack = stack; - return this; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/items/NBTTagBuilder.java b/src/main/java/me/ztowne13/customcrates/interfaces/items/NBTTagBuilder.java deleted file mode 100644 index eb4c3bd..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/items/NBTTagBuilder.java +++ /dev/null @@ -1,210 +0,0 @@ -package me.ztowne13.customcrates.interfaces.items; - -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.ReflectionUtilities; -import me.ztowne13.customcrates.utils.Utils; -import me.ztowne13.customcrates.utils.VersionUtils; -import org.bukkit.inventory.ItemStack; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Set; - -/** - * Created by ztowne13 on 6/11/16. - */ -public class NBTTagBuilder { - private static final String[] excludedTags = new String[]{ - "display", - "Enchantments", - "ench", - "HideFlags", - "Potion", - "StoredEnchantments", - "Damage", - - // Don't work - "pages" - }; - private static final String[] booleanTags = new String[]{ - "Unbreakable" - }; - - public static Class getCraftItemStack() { - try { - return Class.forName("org.bukkit.craftbukkit." + VersionUtils.getVersionRaw() + ".inventory.CraftItemStack"); - } catch (Exception exc) { - ChatUtils.log("Failed to load CraftItemStack. Please check plugin is up to date."); - } - return null; - } - - public static Object getNMSItemStack(ItemStack stack) { - try { - return getCraftItemStack().getMethod("asNMSCopy", ItemStack.class).invoke(getCraftItemStack(), stack); - } catch (Exception exc) { - ChatUtils.log("Failed to load NMS ItemStack. Please check plugin is up to date."); - } - return null; - } - - public static Object getNewNBTTagCompound() { - try { - return Class.forName("net.minecraft.server." + VersionUtils.getVersionRaw() + ".NBTTagCompound").newInstance(); - } catch (Exception exc) { - exc.printStackTrace(); - ChatUtils.log("Failed to create new NBT Tag Compound. Please check plugin is up to date."); - } - return null; - } - - public static Object getNBTTagCompound(Object nmsStack) { - try { - Class clazz = nmsStack.getClass(); - Method method = clazz.getMethod("getTag"); - return method.invoke(nmsStack); - } catch (Exception exc) { - exc.printStackTrace(); - ChatUtils.log("Failed to get existing NBT Tag Compound. Please check plugin is up to date."); - } - return null; - } - - public static ItemStack applyTo(ItemStack item, String tag) { - - Object stack = getNMSItemStack(item); - - if (stack == null) { - return item; - } - - Object tagCompound = getNBTTagCompound(stack); - if (tagCompound == null) { - tagCompound = getNewNBTTagCompound(); - } - - String[] args = tag.split(" "); - String key = null; - String value = null; - - try { - key = args[0]; - - StringBuilder remainingValue = new StringBuilder(); - for (int i = 1; i < args.length; i++) { - remainingValue.append(args[i]).append(" "); - } - remainingValue = new StringBuilder(remainingValue.substring(0, remainingValue.length() - 1)); - - value = remainingValue.toString().replace(",Properties:\\{textures:\\[0:\\{Value:", ",Properties:{textures:[{Value:"); - } catch (Exception exc) { - exc.printStackTrace(); - ChatUtils.log("Tag " + tag + - " is not formatted 'TagType Tag' (without the quotes). Try using the in-game config, it does NBT tags automatically!"); - } - - try { - if (value.startsWith("[") && value.endsWith("]")) { - Class clazz = ReflectionUtilities.getNMSClass("MojangsonParser"); - Object comp = clazz.getMethod("parse", String.class).invoke(clazz, "{" + key + ":" + value + "}"); - Object nbtBase = ReflectionUtilities.getMethod(comp.getClass(), "get", String.class).invoke(comp, key); - - tagCompound.getClass().getMethod("set", String.class, ReflectionUtilities.getNMSClass("NBTBase")) - .invoke(tagCompound, key, nbtBase); - } else if (value.startsWith("{") && value.endsWith("}")) { - Class clazz = ReflectionUtilities.getNMSClass("MojangsonParser"); - Object newComp = clazz.getMethod("parse", String.class).invoke(clazz, value); - - tagCompound.getClass().getMethod("set", String.class, ReflectionUtilities.getNMSClass("NBTBase")) - .invoke(tagCompound, key, newComp); - } else if ((value.startsWith("'") && value.endsWith("'")) || (value.startsWith("\"") && value.endsWith("\""))) { - value = ChatUtils.stripQuotes(value); - - if (value.equalsIgnoreCase("1b")) { - tagCompound.getClass().getMethod("setInt", String.class, int.class) - .invoke(tagCompound, key, 1); - } else { - tagCompound.getClass().getMethod("setString", String.class, String.class) - .invoke(tagCompound, key, value); - } - } else if (Utils.isInt(value)) { - tagCompound.getClass().getMethod("setInt", String.class, int.class) - .invoke(tagCompound, key, Integer.parseInt(value)); - } else if (Utils.isDouble(value)) { - tagCompound.getClass().getMethod("setDouble", String.class, double.class) - .invoke(tagCompound, key, Double.valueOf(value)); - } else { - tagCompound.getClass().getMethod("setString", String.class, String.class) - .invoke(tagCompound, key, value); - } - } catch (Exception exc) { - ChatUtils.log("Failed to apply '" + key + " " + value + "' tag. Please check plugin is up to date."); - exc.printStackTrace(); - } - - try { - stack.getClass().getMethod("setTag", tagCompound.getClass()).invoke(stack, tagCompound); - ItemStack toReturn = (ItemStack) getCraftItemStack().getMethod("asBukkitCopy", stack.getClass()) - .invoke(getCraftItemStack(), stack); - - return toReturn; - } catch (Exception exc) { - exc.printStackTrace(); - ChatUtils.log("Failed to get apply final Tag. Please check plugin is up to date."); - } - return null; - } - - public static List getFrom(ItemStack item, boolean ignoreExcluded) { - List list = new ArrayList<>(); - - Object stack = getNMSItemStack(item); - - if (stack == null) { - return list; - } - - Object tagCompound = getNBTTagCompound(stack); - - try { - Set keys = (Set) tagCompound.getClass().getMethod( - VersionUtils.Version.v1_13.isServerVersionOrLater() ? "getKeys" : "c").invoke(tagCompound); - - for (String key : keys) { - boolean toSkip = false; - for (String excludedTag : excludedTags) { - if (key.equalsIgnoreCase(excludedTag)) { - toSkip = true; - break; - } - } - - if (!toSkip || ignoreExcluded) { - Object nbtBase; - if (Arrays.asList(booleanTags).contains(key)) { - nbtBase = tagCompound.getClass().getMethod("getBoolean", String.class).invoke(tagCompound, key); - if ((boolean) nbtBase) - list.add(key + " " + 1); - else - list.add(key + " " + 0); - } else { - nbtBase = tagCompound.getClass().getMethod("get", String.class).invoke(tagCompound, key); - String baseAsString = nbtBase.toString(); -// if(key.equalsIgnoreCase("pages")) -// { -// baseAsString = baseAsString.replaceAll("\\\\\\\\", "\\\\");; -// baseAsString = baseAsString.replace("\\\"", "\""); -// } - list.add(key + " " + baseAsString); - } - - } - } - } catch (Exception exc) { - //exc.printStackTrace(); - } - return list; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/items/SaveableItem.java b/src/main/java/me/ztowne13/customcrates/interfaces/items/SaveableItem.java deleted file mode 100644 index 2f586e9..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/items/SaveableItem.java +++ /dev/null @@ -1,13 +0,0 @@ -package me.ztowne13.customcrates.interfaces.items; - -import me.ztowne13.customcrates.interfaces.files.FileHandler; -import me.ztowne13.customcrates.interfaces.logging.StatusLogger; -import me.ztowne13.customcrates.interfaces.logging.StatusLoggerEvent; - -public interface SaveableItem extends EditableItem { - void saveItem(FileHandler fileHandler, String prefix, boolean allowUnnamedItems); - - boolean loadItem(FileHandler fileHandler, String prefix, StatusLogger statusLogger, StatusLoggerEvent itemFailure, - StatusLoggerEvent improperEnchant, StatusLoggerEvent improperPotion, - StatusLoggerEvent improperGlow, StatusLoggerEvent improperAmount, StatusLoggerEvent invalidItemFlag); -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/items/SaveableItemBuilder.java b/src/main/java/me/ztowne13/customcrates/interfaces/items/SaveableItemBuilder.java deleted file mode 100644 index e6528f8..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/items/SaveableItemBuilder.java +++ /dev/null @@ -1,354 +0,0 @@ -package me.ztowne13.customcrates.interfaces.items; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.interfaces.files.FileHandler; -import me.ztowne13.customcrates.interfaces.items.attributes.CompressedEnchantment; -import me.ztowne13.customcrates.interfaces.items.attributes.RGBColor; -import me.ztowne13.customcrates.interfaces.logging.StatusLogger; -import me.ztowne13.customcrates.interfaces.logging.StatusLoggerEvent; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.Utils; -import me.ztowne13.customcrates.utils.VersionUtils; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.inventory.ItemFlag; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.Damageable; - -import java.util.ArrayList; -import java.util.Optional; - -public class SaveableItemBuilder extends ItemBuilder implements SaveableItem { - public SaveableItemBuilder(ItemBuilder builder) { - super(builder); - } - - public SaveableItemBuilder(ItemStack fromStack) { - super(fromStack); - } - - public SaveableItemBuilder(XMaterial material) { - super(material); - } - - public SaveableItemBuilder(XMaterial material, int amount) { - super(material, amount); - } - - @Override - public void saveItem(FileHandler fileHandler, String prefix, boolean allowUnnamedItems) { - FileConfiguration fc = fileHandler.get(); - short durability = getStack().getDurability(); - try { - XMaterial dynMat = XMaterial.matchXMaterial(getStack()); - fc.set(prefix + ".material", dynMat.name()); - fc.set(prefix + ".damage", - durability == 0 || - dynMat.getData() != 0 || - VersionUtils.Version.v1_13.isServerVersionOrLater() - ? null : durability); - } catch (Exception exc) { - if (VersionUtils.Version.v1_12.isServerVersionOrEarlier()) { - getStack().setDurability((short) 0); - fc.set(prefix + ".material", XMaterial.matchXMaterial(getStack()).name()); - fc.set(prefix + ".damage", durability); - } else { - exc.printStackTrace(); - } - } - - fc.set(prefix + ".glow", isGlowing()); - fc.set(prefix + ".amount", getStack().getAmount()); - fc.set(prefix + ".player-head-name", getPlayerHeadName()); - if (VersionUtils.Version.v1_13.isServerVersionOrLater() && getItemMeta() instanceof Damageable) { - fc.set(prefix + ".damage", ((Damageable) getItemMeta()).getDamage()); - } - - if (!hasDisplayName()) { - fc.set(prefix + ".name", null); - } else { - fc.set(prefix + ".name", getDisplayNameFromChatColor(false)); - } - - // Enchantments - if (!getEnchantments().isEmpty()) { - ArrayList enchants = new ArrayList<>(); - for (CompressedEnchantment enchant : getEnchantments()) - enchants.add(enchant.toString()); - - fc.set(prefix + ".enchantments", enchants); - } else - fc.set(prefix + ".enchantments", null); - - // Potion Effects - if (!getPotionEffects().isEmpty()) { - ArrayList parsedPots = new ArrayList<>(); - for (CompressedPotionEffect potion : getPotionEffects()) - parsedPots.add(potion.toString()); - - fc.set(prefix + ".potion-effects", parsedPots); - } else - fc.set(prefix + ".potion-effects", null); - - // Lore - if (!getLore().isEmpty()) - fc.set(prefix + ".lore", ChatUtils.fromColor(getLore())); - else - fc.set(prefix + ".lore", null); - - // NBT Tags - if (!getNBTTags().isEmpty()) - fc.set(prefix + ".nbt-tags", getNBTTags()); - else - fc.set(prefix + ".nbt-tags", null); - - // Item Flags - if (!getItemFlags().isEmpty()) { - ArrayList flags = new ArrayList<>(); - for (ItemFlag flag : getItemFlags()) - flags.add(flag.name()); - - fc.set(prefix + ".item-flags", flags); - } else - fc.set(prefix + ".item-flags", null); - - // Leather armour color - if (isColorable() && getColor() != null) { - fc.set(prefix + ".color.red", getColor().getRed()); - fc.set(prefix + ".color.green", getColor().getGreen()); - fc.set(prefix + ".color.blue", getColor().getBlue()); - } - - } - - public boolean loadItem(FileHandler fileHandler, String prefix) { - return loadItem(fileHandler, prefix, null, null, null, null, null, null, null); - } - - @Override - public boolean loadItem(FileHandler fileHandler, String prefix, StatusLogger statusLogger, StatusLoggerEvent itemFailure, - StatusLoggerEvent improperEnchant, StatusLoggerEvent improperPotion, - StatusLoggerEvent improperGlow, StatusLoggerEvent improperAmount, - StatusLoggerEvent invalidItemFlag) { - FileConfiguration fc = fileHandler.get(); - - convertOldConfigurations(fileHandler, prefix); - - short foundMaterialDurability; - - // material - if (!fc.contains(prefix + ".material")) { - if (itemFailure != null) - itemFailure.log(statusLogger, "The '" + prefix + ".material' value does not exist."); - return false; - } else { - String mat = fc.getString(prefix + ".material"); - - Optional optional = XMaterial.matchXMaterial(mat.replace(";", ":")); - - if (optional.isPresent()) { - XMaterial dynamicMaterial = optional.get(); - foundMaterialDurability = dynamicMaterial.getData(); - setStack(dynamicMaterial.parseItem()); - - if (dynamicMaterial.equals(XMaterial.AIR)) { - return true; - } - } else { - if (itemFailure != null) - itemFailure.log(statusLogger, mat + " is not a valid material."); - return false; - } - } - - - if (fc.contains(prefix + ".damage") && foundMaterialDurability == 0) { - if (Utils.isInt(fc.getString(prefix + ".damage"))) { - int damage = Integer.parseInt(fc.getString(prefix + ".damage")); - setDamage(damage); - } - } - - // Name - if (!fc.contains(prefix + ".name")) { - setDisplayName(null); - } - setDisplayName(fc.getString(prefix + ".name")); - - // Lore - if (fc.contains(prefix + ".lore")) - for (String line : fc.getStringList(prefix + ".lore")) - addLore(line); - - // Enchantments - if (fc.contains(prefix + ".enchantments")) { - for (String unparsedEnchant : fc.getStringList(prefix + ".enchantments")) { - try { - CompressedEnchantment compressedEnchantment = CompressedEnchantment.fromString(unparsedEnchant); - addEnchantment(compressedEnchantment); - } catch (Exception exc) { - if (improperEnchant != null) - improperEnchant.log(statusLogger, unparsedEnchant + - " is not formatted enchant;level or either the enchant is not a valid enchantment or the level is not a number."); - } - } - } - - // Glow - - if (fc.contains(prefix + ".glow") && getEnchantments().isEmpty()) { - String unparsedGlow = fc.getString(prefix + ".glow"); - if (Utils.isBoolean(unparsedGlow)) - setGlowing(Boolean.parseBoolean(unparsedGlow)); - else if (improperGlow != null) - improperGlow - .log(statusLogger, "The '" + prefix + ".glow' value is not a proper true/false value"); - } - - // Potion Effects - if (fc.contains(prefix + ".potion-effects")) { - for (String unparsedPotion : fc.getStringList(prefix + ".potion-effects")) { - try { - CompressedPotionEffect compressedPotionEffect = CompressedPotionEffect.fromString(unparsedPotion); - addPotionEffect(compressedPotionEffect); - } catch (Exception exc) { - exc.printStackTrace(); - if (improperPotion != null) - improperPotion.log(statusLogger, unparsedPotion + - " is not formatted potiontype;duration;amplifier or either the potion is not a valid potion type or the duration/amplifier is not a number."); - } - } - } - - // NBT Tags - if (fc.contains(prefix + ".nbt-tags")) - for (String line : fc.getStringList(prefix + ".nbt-tags")) - addNBTTag(line); - - // Item Flags - if (fc.contains(prefix + ".item-flags")) { - for (String line : fc.getStringList(prefix + ".item-flags")) { - try { - ItemFlag flag = ItemFlag.valueOf(line); - addItemFlag(flag); - } catch (Exception exc) { - if (invalidItemFlag != null) - invalidItemFlag.log(statusLogger, line + " is an invalid flag."); - } - } - } - - // Amount - - if (fc.contains(prefix + ".amount")) { - String unparsedAmount = fc.getString(prefix + ".amount"); - if (Utils.isInt(unparsedAmount)) - getStack().setAmount(Integer.parseInt(unparsedAmount)); - else if (improperAmount != null) - improperAmount.log(statusLogger, "The '" + prefix + ".amount' value is not a valid number."); - } - - // Player Head Name - - if (fc.contains(prefix + ".player-head-name")) { - // If the head has the SkullOwner tag, it LIKELY doesn't need a player-head name. So, don't save the player-head - // name, otherwise it will overwrite the tag. - if (!hasNBTTag("SkullOwner")) { - setPlayerHeadName(fc.getString(prefix + ".player-head-name")); - } - } - - // Leather armour color - - if (fc.contains(prefix + ".color") && isColorable()) { - int red = 0; - int green = 0; - int blue = 0; - - String unparsedRed = fc.getString(prefix + ".color.red"); - String unparsedGreen = fc.getString(prefix + ".color.green"); - String unparsedBlue = fc.getString(prefix + ".color.blue"); - - if (Utils.isInt(unparsedRed)) { - red = Integer.parseInt(unparsedRed); - } - if (Utils.isInt(unparsedGreen)) { - green = Integer.parseInt(unparsedGreen); - } - if (Utils.isInt(unparsedBlue)) { - blue = Integer.parseInt(unparsedBlue); - } - - setColor(new RGBColor(red, green, blue)); - } - - return true; - } - - public void convertOldConfigurations(FileHandler fileHandler, String prefix) { - convertOldEnchantType(fileHandler, prefix); - convertOldItemType(fileHandler, prefix); - } - - public void convertOldItemType(FileHandler fileHandler, String prefix) { - FileConfiguration fc = fileHandler.get(); - - if (fc.contains(prefix)) { - if (!fc.isConfigurationSection(prefix)) { - ChatUtils.log("Converting old item format to new item format..."); - - String original = fc.getString(prefix); - String[] args = original.split(";"); - - String materialName = args[0].toUpperCase(); - String byteName = args.length > 1 ? args[1] : "0"; - - Optional optional = XMaterial.matchXMaterial(materialName + ":" + byteName); - - if (optional.isPresent()) { - XMaterial m = optional.get(); - - SaveableItemBuilder newItem = new SaveableItemBuilder(m, 1); - newItem.saveItem(fileHandler, prefix, true); - ChatUtils.log("Successfully converted " + original); - fileHandler.save(); - } else { - ChatUtils.log("Failed to convert " + fc.getString(prefix) + ", it is likely not a proper material."); - } - } - } - - } - - public void convertOldEnchantType(FileHandler fileHandler, String prefix) { - FileConfiguration fc = fileHandler.get(); - if (fc.contains(prefix + ".enchantment") && !fc.contains(prefix + ".enchantments")) { - ChatUtils.log("Converting old enchantment format to new enchantment format..."); - try { - boolean isSet = !fc.getStringList(prefix + ".enchantment").isEmpty(); - ArrayList newEnchs = new ArrayList<>(); - if (isSet) { - for (String line : fc.getStringList(prefix + ".enchantment")) { - try { - CompressedEnchantment compressedEnchantment = CompressedEnchantment.fromString(line); - newEnchs.add(compressedEnchantment.toString()); - } catch (Exception exc) { - - } - } - } else { - String enchant = fc.getString(prefix + ".enchantment"); - CompressedEnchantment compressedEnchantment = CompressedEnchantment.fromString(enchant); - newEnchs.add(compressedEnchantment.toString()); - } - - fc.set(prefix + ".enchantment", null); - fc.set(prefix + ".enchantments", newEnchs); - ChatUtils.log("Success. Saving..."); - fileHandler.save(); - ChatUtils.log("Saved."); - } catch (Exception exc) { - ChatUtils.log("Failed."); - } - } - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/items/attributes/BukkitGlowEffect.java b/src/main/java/me/ztowne13/customcrates/interfaces/items/attributes/BukkitGlowEffect.java deleted file mode 100644 index 70233d7..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/items/attributes/BukkitGlowEffect.java +++ /dev/null @@ -1,35 +0,0 @@ -package me.ztowne13.customcrates.interfaces.items.attributes; - -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.ItemFlag; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; - - -/** - * Created by ztown on 2/17/2017. - */ -public class BukkitGlowEffect { - private final ItemStack stack; - - public BukkitGlowEffect(ItemStack stack) { - this.stack = stack; - } - - public ItemStack apply() { - stack.addUnsafeEnchantment(Enchantment.DURABILITY, 0); - ItemMeta im = stack.getItemMeta(); - im.addItemFlags(ItemFlag.HIDE_ENCHANTS); - stack.setItemMeta(im); - return stack; - } - - public ItemStack remove() { - ItemMeta im = stack.getItemMeta(); - im.removeItemFlags(ItemFlag.HIDE_ENCHANTS); - im.removeEnchant(Enchantment.DURABILITY); - stack.setItemMeta(im); - - return stack; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/items/attributes/CompressedEnchantment.java b/src/main/java/me/ztowne13/customcrates/interfaces/items/attributes/CompressedEnchantment.java deleted file mode 100644 index 85f1dd8..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/items/attributes/CompressedEnchantment.java +++ /dev/null @@ -1,52 +0,0 @@ -package me.ztowne13.customcrates.interfaces.items.attributes; - -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.meta.EnchantmentStorageMeta; - -public class CompressedEnchantment { - private final Enchantment enchantment; - private final int level; - - public CompressedEnchantment(Enchantment enchantment, int level) { - this.enchantment = enchantment; - this.level = level; - } - - public static CompressedEnchantment fromString(String value) throws Exception { - String[] split = value.split(";"); - - Enchantment enchantment = Enchantment.getByName(split[0].toUpperCase()); - if (enchantment == null) - throw new Exception(); - - int level = Integer.parseInt(split[1]); - - return new CompressedEnchantment(enchantment, level); - } - - public void applyTo(ItemBuilder itemBuilder) { - if (itemBuilder.getItemMeta() instanceof EnchantmentStorageMeta) { - EnchantmentStorageMeta meta = (EnchantmentStorageMeta) itemBuilder.getItemMeta(); - meta.addStoredEnchant(enchantment, level, true); - - itemBuilder.setItemMeta(meta); - return; - } - - itemBuilder.getStack().addUnsafeEnchantment(enchantment, level); - } - - @Override - public String toString() { - return enchantment.getName() + ";" + level; - } - - public Enchantment getEnchantment() { - return enchantment; - } - - public int getLevel() { - return level; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/items/attributes/RGBColor.java b/src/main/java/me/ztowne13/customcrates/interfaces/items/attributes/RGBColor.java deleted file mode 100644 index f3570f3..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/items/attributes/RGBColor.java +++ /dev/null @@ -1,41 +0,0 @@ -package me.ztowne13.customcrates.interfaces.items.attributes; - -public class RGBColor { - private int red; - private int green; - private int blue; - - public RGBColor() { - this(0, 0, 0); - } - - public RGBColor(int red, int green, int blue) { - this.red = red; - this.blue = blue; - this.green = green; - } - - public int getRed() { - return red; - } - - public void setRed(int red) { - this.red = red; - } - - public int getGreen() { - return green; - } - - public void setGreen(int green) { - this.green = green; - } - - public int getBlue() { - return blue; - } - - public void setBlue(int blue) { - this.blue = blue; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/logging/StatusLogger.java b/src/main/java/me/ztowne13/customcrates/interfaces/logging/StatusLogger.java deleted file mode 100644 index ababad8..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/logging/StatusLogger.java +++ /dev/null @@ -1,136 +0,0 @@ -package me.ztowne13.customcrates.interfaces.logging; - -import me.ztowne13.customcrates.SettingsValue; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.Bukkit; -import org.bukkit.command.CommandSender; -import org.bukkit.command.ConsoleCommandSender; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class StatusLogger { - private final SpecializedCrates instance; - - private int failures; - - private Map> completedEvents = new HashMap<>(); - private Map> failedEvents = new HashMap<>(); - - public StatusLogger(SpecializedCrates instance) { - this.instance = instance; - } - - public void addEvent(boolean success, String section, String event, String cause) { - failures += success ? 0 : 1; - Map> map = success ? getCompletedEvents() : getFailedEvents(); - List list = map.getOrDefault(section, new ArrayList<>()); - list.add(event + "%CAUSE%" + cause); - map.put(section, list); - } - - public void logAll() { - logAll(Bukkit.getConsoleSender(), false); - } - - public void logAll(CommandSender sender, boolean forceOnlyFailures) { - ArrayList hasLogged = new ArrayList<>(); - for (String s : getCompletedEvents().keySet()) { - if (!hasLogged.contains(s.toUpperCase())) { - logSection(sender, s, forceOnlyFailures); - hasLogged.add(s.toUpperCase()); - } - } - - for (String s : getFailedEvents().keySet()) { - if (!hasLogged.contains(s.toUpperCase())) { - logSection(sender, s, forceOnlyFailures); - hasLogged.add(s.toUpperCase()); - } - } - - if (getFailedEvents().isEmpty() && - SettingsValue.LOG_SUCCESSES.getValue(instance).toString().equalsIgnoreCase("FAILURES")) { - ChatUtils.log(" &a+&f Success: there were no issues."); - } - } - - public void logSection(CommandSender sender, String section, boolean forceOnlyFailures) { - boolean hasLoggedHeader = false; - String toLog = SettingsValue.LOG_SUCCESSES.getValue(instance).toString(); - - if (!toLog.equalsIgnoreCase("NOTHING") || forceOnlyFailures) { - if (!toLog.equalsIgnoreCase("FAILURES") && !forceOnlyFailures) { - hasLoggedHeader = true; - logValue(sender, " " + section); - for (String checkSec : getCompletedEvents().keySet()) { - if (checkSec.equalsIgnoreCase(section)) { - for (String s : getCompletedEvents().get(checkSec)) { - String[] split = s.split("%CAUSE%"); - String event = split[0]; - logValue(sender, " &a+&f " + event); - } - } - } - } - - for (String checkSec : getFailedEvents().keySet()) { - if (checkSec.equalsIgnoreCase(section)) { - if (!hasLoggedHeader) { - logValue(sender, " " + section); - hasLoggedHeader = true; - } - - for (String s : getFailedEvents().get(checkSec)) { - String[] parsedEvent = s.split("%CAUSE%"); - String event = parsedEvent[0]; - String cause = parsedEvent[1]; - - logValue(sender, " &c-&f " + event); - - if (cause.equalsIgnoreCase("NONE")) { - continue; - } - - logValue(sender, " &7CAUSE: " + cause); - } - } - } - } - } - - public void logValue(CommandSender sender, String s) { - if (sender instanceof ConsoleCommandSender) { - ChatUtils.log(s); - return; - } - sender.sendMessage(ChatUtils.toChatColor(s)); - } - - public Map> getCompletedEvents() { - return completedEvents; - } - - public void setCompletedEvents(Map> completedEvents) { - this.completedEvents = completedEvents; - } - - public Map> getFailedEvents() { - return failedEvents; - } - - public void setFailedEvents(Map> failedEvents) { - this.failedEvents = failedEvents; - } - - public int getFailures() { - return failures; - } - - public void setFailures(int failures) { - this.failures = failures; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/logging/StatusLoggerEvent.java b/src/main/java/me/ztowne13/customcrates/interfaces/logging/StatusLoggerEvent.java deleted file mode 100644 index a000942..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/logging/StatusLoggerEvent.java +++ /dev/null @@ -1,748 +0,0 @@ -package me.ztowne13.customcrates.interfaces.logging; - -import me.ztowne13.customcrates.crates.Crate; - -/** - * Created by ztowne13 on 6/12/16. - */ -public enum StatusLoggerEvent { - ACTION_ADD(true, "Actions", "Added action $?$ with tier $?$", ""), - - FIREWORK_ADD(true, "Fireworks", "Added firework $?$ with tier $?$", ""), - - FIREWORK_DATA_INVALIDCOLOR(false, "Fireworks", "Failed to completely load firework $?$", - "$?$ is not a valid $?$ color."), - - FIREWORK_DATA_SUCCESS(true, "Fireworks", "Successfully loaded firework $?$", "NONE"), - - FIREWORK_DATA_PARTIALSUCCESS(false, "Fireworks", "Failed to completely load firework $?$", "$?$"), - - FIREWORK_DATA_FAILURE(false, "Fireworks", "Failed to completely load firework $?$", - "Improperly formatted COLOR;COLOR, FADE;FADE, TRAIL, FLICKER, TYPE, POWER"), - - HOLOGRAM_ANIMATION_TYPE_FAILURE_NONEXISTENT(false, "Holograms", "Failed to load the hologram's animation.", - "The hologram.animation.type value does not exist."), - - HOLOGRAM_ANIMATION_TYPE_FAILURE_INVALID(false, "Holograms", "Failed to load the hologram's animation.", - "$?$ is not a valid Animation type."), - - HOLOGRAM_ANIMATION_SPEED_FAILURE_NONEXISTENT(false, "Holograms", "Failed to load the hologram's animation.", - "The hologram.animation.speed value does not exist."), - - HOLOGRAM_ANIMATION_SPEED_FAILURE_INVALID(false, "Holograms", "Failed to load the hologram's animation.", - "$?$ is not a valid number / speed."), - - HOLOGRAM_ANIMATION_PREFIXES_DISABLED(false, "Holograms", - "Disabled hologram animation and changed the animation type to NULL.", - "The prefixes are invalid and thus the animation won't work."), - - HOLOGRAM_ANIMATION_PREFIXES_NONEXISTENT(false, "Holograms", "Failed to load the hologram's animation.", - "The hologram.animation.prefixes value does not exist."), - - HOLOGRAM_ANIMATION_PREFIXES_MISFORMATTED(false, "Holograms", "Failed to load the hologram's animation.", - "The hologram.animation.prefixes value is not a properly formatted list."), - - HOLOGRAM_ADDLINE_SUCCESS(true, "Hologram", "Added hologram line $?$", "NONE"), - - @Deprecated - HOLOGRAM_ADDLINE_FAIL_TOMANY(false, "Hologram", "Failed to add hologram line $?$", - "Maximum lines for a hologram is: $?$"), - - HOLOGRAM_REWARD_HOLOGRAM(true, "Hologram", "Added the reward-hologram $?$", "NONE"), - - HOLOGRAM_REWARD_HOLOGRAM_DURATION_SUCCESS(true, "Hologram", "Added the reward-hologram's duration.", "NONE"), - - HOLOGRAM_REWARD_HOLOGRAM_DURATION_INVALID(true, "Hologram", "Failed to load the reward-hologram's duration", - "It is not a valid integer."), - - HOLOGRAM_REWARD_HOLOGRAM_YOFFSET_SUCCESS(true, "Hologram", "Added the reward-hologram's Y-Offset.", "NONE"), - - HOLOGRAM_REWARD_HOLOGRAM_YOFFSET_INVALID(true, "Hologram", "Failed to load the reward-hologram's Y-Offset", - "It is not a valid integer."), - - LUCKYCHEST_CHANCE_MISFORMATTED(false, "Lucky Chest", "Failed to load the 'chance' setting.", - "Not properly formatted 'INTEGER/INTEGER'"), - - LUCKYCHEST_CHANCE_NONEXISTENT(false, "Lucky Chest", "The lucky chest 'chance' variable doesn't exist.", "NONE"), - - LUCKYCHEST_BLWL_INVALID(false, "Lucky Chest", "Failed to load the 'is-block-list-whitelist' setting.", - "Not specified as 'true' or 'false'"), - - LUCKYCHEST_REQUIRE_PERMISSION_INVALID(false, "Lucky Chest", "Failed to load the 'require-permission' setting.", - "Not specified as 'true' or 'false'"), - - LUCKYCHEST_BLWL_NONEXISTENT(false, "Lucky Chest", - "The lucky chest 'is-block-list-whitelist' variable doesn't exist and has defaulted to 'true'.", "NONE"), - - LUCKYCHEST_REQUIRE_PERMISSION_NONEXISTENT(false, "Lucky Chest", - "The lucky chest 'require-permission' value doesn't exist and has defaulted to 'true'.", "NONE"), - - LUCKYCHEST_WORLD_INVALID(false, "Lucky Chest", "$?$ is not a valid world for the lucky chests to spawn in.", "NONE"), - - LUCKYCHEST_BLOCKLIST_INVALIDBLOCK(false, "Lucky Chest", - "Failed to load the material '$?$' for the 'block-list' setting.", - "Not a valid material such as DIRT."), - - LUCKYCHEST_BLOCKLIST_INVALID(false, "Lucky Chest", "Failed to load the 'block-list' setting.", - "Not a proper STRING list."), - - LUCKYCHEST_BLOCKLIST_NONEXISTENT(false, "Lucky Chest", - "The lucky chest 'block-list' variable doesn't exist and will allow ALL blocks for Lucky Chests.", "NONE"), - - LUCKYCHEST_NOVALUES(false, "Lucky Chest", "This crate is a lucky chest but does is not properly set up.", - "Does not contain any of the required 'lucky-chest' settings."), - - PARTICLE_ADD_SUCCESS(true, "Particles", "Added particle $?$", ""), - - PARTICLE_INVALID(false, "Particles", "Particle string '$?$' is invalid", "Particle effect '$?$' is invalid"), - - PARTICLE_STRING_INVALID(false, "Particles", "Particle string '$?$' is invalid", "NONE"), - - PARTICLE_ANIMATION_INVALID(false, "Particles", - "The particle animation '$?$' is invalid and will thus not have an animation.", "NONE"), - - PARTICLE_ANIMATION_COLOR_INVALID(false, "Particles", - "The particle animation '$?$''s R/G/B colors are invalid and will thus not have an color.", "NONE"), - - REWARD_ADD_SUCCESS(true, "Rewards", "Added reward $?$", "NONE"), - - REWARD_ADD_FAILURE_SPACE(false, "Rewards", "Failed to add reward $?$", "It cannot have any spaces in its name!"), - - REWARDS_PATH_NONEXISTENT(false, "Rewards", "The 'rewards' path does not exist in the config", "NONE"), - - REWARDS_EMPTY(false, "Rewards", "The rewards are configured improperly, disabling crate.", "There are no rewards in the 'rewards' list."), - - - REWARD_CHANCE_NONEXISTENT(false, "Rewards", "Failed to load CHANCE for reward: $?$", - "The 'chance' value does not exist."), - - REWARD_NAME_NONEXISTENT(false, "Rewards", "Failed to load NAME for reward: $?$", "The 'name' value does not exist."), - - REWARD_RARITY_NONEXISTENT(false, "Rewards", "Failed to load RARITY for reward: $?$", - "The 'rarity' value does not exist."), - - REWARD_ITEM_NONEXISTENT(false, "Rewards", "Failed to load ITEM for reward: $?$", - "The 'item' value does not exist or is misconfigured."), - - REWARD_ITEM_AIR(false, "Rewards", "Failed to load the reward $?$", "The item cannot be AIR."), - - REWARD_COMMAND_INVALID(false, "Rewards", "Failed to load COMMANDS for reward: $?$", - "The 'commands' value does not exist or is not a valid list."), - - REWARD_ENCHANT_INVALID(false, "Rewards", "Failed to load specified enchantments for reward.", "$?$"), - - REWARD_POTION_INVALID(false, "Rewards", "Failed to load specified potion effect", - "'$?$'"), - - REWARD_AMOUNT_INVALID(false, "Rewards", "Failed to load amount for reward $?$", "It is not a valid number."), - - REWARD_ITEM_FAILURE(false, "Rewards", "Failed to load a reward menu item.", "$?$"), - - REWARD_ENCHANTMENT_ADD_FAILURE(false, "Rewards", "Failed to load the a rewar item enchantment.", "$?$"), - - REWARD_POTION_ADD_FAILURE(false, "Rewards", "Failed to load the a reward item.", "$?$"), - - REWARD_GLOW_FAILURE(false, "Rewards", "Failed to load the reward item glow value.", "$?$"), - - REWARD_AMOUNT_FAILURE(false, "Rewards", "Failed to load the reward item amount value.", "$?$"), - - REWARD_FLAG_FAILURE(false, "Rewards", "Failed to load the reward item-flags value.", "$?$"), - - SOUND_NONEXISTENT(false, "Sounds", "The sound value: $?$ is improperly setup.", "Sound '$?$' is invalid."), - - SOUND_PITCH_INVALID(false, "Sounds", "Failed to load pitch for sound $?$", "$?$ is not a valid number."), - - SOUND_PITCH_NONEXISTENT(false, "Sounds", "Failed to load pitch for sound $?$", "The PITCH value does not exist."), - - SOUND_VOLUME_INVALID(false, "Sounds", "Failed to load volume for sound $?$", "$?$ is not a valid number."), - - SOUND_VOLUME_NONEXISTENT(false, "Sounds", "Failed to load volume for sound $?$", "The VOLUME value does not exist."), - - SOUND_ADD_SUCCESS(true, "Sounds", "Successfully loaded the sound $?$", "NONE"), - - SOUND_ADD_IMPROPER_SETUP(false, "Sounds", "The sound value: $?$ is not set up properly.", - "It does not have a valid SOUND, PITCH, or VOLUME"), - - MULTICRATEINVENTORY_OBJECTS_INVALID(false, "MultiCrate Inventory", "Failed to load the MultiCrate object: $?$", "$?$"), - - MULTICRATEINVENTORY_OBJECTS_MISCONFIGURED(false, "MultiCrate Inventory", "The MultiCrate object list is invalid.", - "Missing the 'gui.objects' value or the list is misconfigured."), - - MULTICRATEINVENTORY_ROW_MISCONFIGURED(false, "MultiCrate Inventory", "The 'gui.row' value is misconfigured", - "Missing the 'gui.objects' value or the list is misconfigured."), - - MULTICRATEINVENTORY_NONEXISTENT(false, "MultiCrate Inventory", "Both the 'gui.row' and 'gui.objects' value are missing", - "The values are nonexistent"), - - MULTICRATE_ITEM_FAILURE(false, "MultiCrate Inventory", "Failed to load a multi crate menu item.", "$?$"), - - MULTICRATE_ENCHANTMENT_ADD_FAILURE(false, "MultiCrate Inventory", "Failed to load the multicrate item's enchantment.", "$?$"), - - MULTICRATE_POTION_ADD_FAILURE(false, "MultiCrate Inventory", "Failed to load the multicrate item's potion.", "$?$"), - - MULTICRATE_GLOW_FAILURE(false, "Rewards", "Failed to load the multicrate item's glow value.", "$?$"), - - MULTICRATE_AMOUNT_FAILURE(false, "Rewards", "Failed to load the multicrate item's amount value.", "$?$"), - - MULTICRATE_FLAG_FAILURE(false, "Rewards", "Failed to load the multicrate item's item-flags value.", "$?$"), - - SETTINGS_CRATE_LORE_ADDLINE_SUCCESS(true, "Settings", "Added line to the crate's lore: $?$", "NONE"), - - SETTINGS_CRATE_ENCHANTMENT_ADD_SUCCESS(true, "Settings", "Added enchantment $?$ to the crate", "NONE"), - - SETTINGS_CRATE_ENCHANTMENT_ADD_FAILURE(false, "Settings", "Failed to load the 'crate.enchantment' value.", "$?$"), - - SETTINGS_CRATE_POTION_ADD_FAILURE(false, "Settings", "Failed to load the 'crate.potion-effects' value.", "$?$"), - - SETTINGS_CRATE_GLOW_FAILURE(false, "Settings", "Failed to load the 'crate.glow' value.", "$?$"), - - SETTINGS_CRATE_AMOUNT_FAILURE(false, "Settings", "Failed to load the 'crate.amount' value.", "$?$"), - - SETTINGS_CRATE_FLAG_FAILURE(false, "Settings", "Failed to load the 'crate.item-flags' value.", "$?$"), - - SETTINGS_CRATE_SUCCESS(true, "Settings", "Set up crate item.", "NONE"), - - SETTINGS_CRATE_FAILURE_DISABLE(false, "Settings", "Failed to load the crate settings for the crate... disabling", - "NONE"), - - SETTINGS_CRATE_FAILURE_INDIVIDUAL(false, "Settings", - "Failed to place an instance of this crate. This message will not appear again.", "$?$"), - - SETTINGS_CRATE_FAILURE(false, "Settings", "Failed to load the crate item.", "$?$"), - - SETTINGS_KEY_LORE_ADDLINE(true, "Settings", "Added line to the key's lore: $?$", "NONE"), - - SETTINGS_KEY_ENCHANTMENT_ADD_SUCCESS(true, "Settings", "Added enchantment $?$ to the key", "NONE"), - - SETTINGS_KEY_ENCHANTMENT_ADD_FAILURE(false, "Settings", "Failed to load the 'key.enchantment' value.", "$?$"), - - SETTINGS_KEY_POTION_ADD_FAILURE(false, "Settings", "Failed to load the 'key.potion-effects' value.", "$?$"), - - SETTINGS_KEY_GLOW_FAILURE(false, "Settings", "Failed to load the 'key.glow' value.", "$?$"), - - SETTINGS_KEY_AMOUNT_FAILURE(false, "Settings", "Failed to load the 'key.amount' value.", "$?$"), - - SETTINGS_KEY_FLAG_FAILURE(false, "Settings", "Failed to load the 'key.item-flags' value.", "$?$"), - - SETTINGS_KEY_SUCCESS(true, "Settings", "Set up key item.", "NONE"), - - SETTINGS_KEY_REQUIRE_NONEXISTENT(false, "Settings", "Failed to load the 'key.require' value", - "The 'key.require' value does not exist."), - - SETTINGS_KEY_FAILURE_DISABLE(false, "Settings", "Failed to load the key settings for the crate... disabling the crate", - "NONE"), - - SETTINGS_KEY_FAILURE(false, "Settings", "Failed to load the key item.", "$?$"), - - SETTINGS_OBTAINMETHOD_SUCCESS(true, "Settings", "Loaded the 'obtain-method' value.", "NONE"), - - SETTINGS_OBTAINMETHOD_INVALID(false, "Settings", "Failed to load the 'obtain-method' value.", - "$?$ is not a valid ObtainType."), - - SETTINGS_OBTAINMETHOD_NONEXISTENT(false, "Settings", "The 'obtain-method' value does not exist.", "NONE"), - - SETTINGS_ANIMATION_SUCCESS(true, "Settings", "Loaded the 'open.crate-animation' value.", "NONE"), - - SETTINGS_ANIMATION_INVALID(false, "Settings", "Failed to load the 'open.crate-animation' value.", - " $?$ is not a valid type."), - - SETTINGS_ANIMATION_NONEXISTENT(false, "Settings", "The 'open.crate-animation' value does not exist.", "NONE"), - - SETTINGS_COOLDOWN_SUCCESS(true, "Settings", "Loaded the 'cooldown' value", "NONE"), - - SETTINGS_COOLDOWN_INVALID(false, "Settings", "Failed to load the 'cooldown' value.", - "It is not of a valid integer (number) type."), - - SETTINGS_COST_SUCCESS(true, "Settings", "Loaded the 'cost' value", "NONE"), - - SETTINGS_COST_INVALID(false, "Settings", "Failed to load the 'cost' value.", - "It is not of a valid integer (number) type."), - - SETTINGS_FASTTRACK_SUCCESS(true, "Settings", "Loaded the 'allow-skip-animation' value", "NONE"), - - SETTINGS_FASTTRACK_INVALID(false, "Settings", "Failed to load the 'allow-skip-animation' value.", - "It is not of a valid integer (number) type."), - - SETTINGS_DISPLAYTYPE_SUCCESS(true, "Settings", "Loaded the 'display.type' crate value.", "NONE"), - - SETTINGS_DISPLAYTYPE_NONEXISTENT(false, "Settings", - "Failed to find a crate display type, settings default to block and re-loading values.", - "Value does not exist."), - - SETTINGS_DISPLAYTYPE_INVALID(false, "Settings", "Failed to load the 'display.type' value.", - "$?$ is not BLOCK, MOB, or NPC"), - - SETTINGS_DISPLAYTYPE_FAIL_NOCITIZENS(false, "Settings", "Failed to set the display type to NPC / MOB", - "The 'Citizens' plugin is not installed."), - - SETTINGS_DISPLAYTYPE_CREATURE_SUCCESS(true, "Settings", "Loaded the 'display.creature' value.", "NONE"), - - SETTINGS_DISPLAYTYPE_CREATURETYPE_INVALID(false, "Settings", "Failed to load the 'display.creature' value.", - "$?$ is not a valid, or usable, creature type."), - - SETTINGS_DISPLAYTYPE_CREATURETYPE_NONEXISTENT(false, "Settings", "Failed to load the 'display.creature' value.", - "It does not exist while type is set to MOB."), - - SETTINGS_DISPLAYTYPE_DISPLAYNAME_SUCCESS(true, "Settings", "Loaded the 'display.name' value.", "NONE"), - - SETTINGS_DISPLAYTYPE_DISPLAYNAME_NONEXISTENT(false, "Settings", "Failed to load the 'display.name' value.", - "It does not exist while type is set to NPC"), - - SETTINGS_INVENTORYNAME_SUCCESS(true, "Settings", "Loaded the 'inventory-name' value", "NONE"), - - SETTINGS_INVENTORYNAME_NONEXISTENT(false, "Settings", "Failed to load the 'inventory-name' value.", - "It does not exist. You may want to add 'inventory-name' followed by the crate's inventory's name, but it is not required."), - - SETTINGS_INVENTORYNAME_INVALID(false, "Settings", "Failed to load the 'inventory-name' value.", - "The name is longer than 32 characters (Automatically shortening)."), - - SETTINGS_PERMISSION_SUCCESS(true, "Settings", "Loaded the 'permission' value", "NONE"), - - SETTINGS_REWARD_DISPLAYER_SUCCESS(true, "Settings", "Loaded the 'reward-displayer' value", "NONE"), - - SETTINGS_REWARD_DISPLAYER_NONEXISTENT(false, "Settings", "Failed to load the 'reward-displayer' value.", - "It does not exist. You can IGNORE this error if you'd like. To get rid, set the reward preview menu type."), - - SETTINGS_REWARD_DISPLAYER_INVALID(false, "Settings", "Failed to load the 'reward-displayer' value.", - "$?$ is not a valid reward display type."), - - SETTINGS_REWARD_DISPLAYER_ITEM_FAILURE(false, "Settings", "Failed to load a reward preview menu item.", "$?$"), - - SETTINGS_REWARD_DISPLAYER_ENCHANTMENT_ADD_FAILURE(false, "Settings", - "Failed to load the a reward preview menu item enchantment.", "$?$"), - - SETTINGS_REWARD_DISPLAYER_POTION_ADD_FAILURE(false, "Settings", "Failed to load the a reward preview menu item.", "$?$"), - - SETTINGS_REWARD_DISPLAYER_GLOW_FAILURE(false, "Settings", "Failed to load the reward preview menu item glow value.", - "$?$"), - - SETTINGS_REWARD_DISPLAYER_AMOUNT_FAILURE(false, "Settings", "Failed to load the reward preview menu item amount value.", - "$?$"), - - SETTINGS_REWARD_DISPLAYER_FLAG_FAILURE(false, "Settings", "Failed to load the reward preview menu item-flags value.", - "$?$"), - - SETTINGS_AUTOCLOSE_SUCCESS(true, "Settings", "Loaded the 'auto-close' value", "NONE"), - - SETTINGS_HOLOGRAMOFFSET_SUCCESS(true, "Settings", "Loaded the 'hologram-offset' value", ""), - - SETTINGS_HOLOGRAMOFFSET_FAILURE(false, "Settings", "The hologram-offset value failed to load", - "The value is not a valid double (number)."), - - ANIMATION_VALUE_NONEXISTENT(false, "Animation", "Failed to load the $?$ value.", "The value does not exist"), - - ANIMATION_MENU_INVNAME_SUCCESS(true, "Animation", "Successfully loaded the Menu animation animation inv-name.", "NONE"), - - ANIMATION_MENU_MINIMUM_REWARDS_SUCCESS(true, "Animation", - "Successfully loaded the Menu animation animation minimum-rewards value.", "NONE"), - - ANIMATION_MENU_MINIMUM_REWARDS_INVALID(false, "Animation", - "Failed to load the Menu animation animation minimum-rewards.", "It is not a valid integer"), - - ANIMATION_MENU_MAXIMUM_REWARDS_SUCCESS(true, "Animation", - "Successfully loaded the Menu animation animation maximum-rewards.", "NONE"), - - ANIMATION_MENU_MAXIMUM_REWARDS_INVALID(false, "Animation", - "Failed to load the Menu animation animation maximum-rewards value.", "It is not a valid integer"), - - ANIMATION_MENU_INVENTORY_ROWS_SUCCESS(true, "Animation", "Successfully loaded the Menu animation inventory-rows value.", - "NONE"), - - ANIMATION_MENU_INVENTORY_ROWS_INVALID(false, "Animation", - "Failed to load the Menu animation animation inventory-rows value.", "It is not a valid integer"), - - ANIMATION_ENCLOSEMENT_INVNAME_SUCCESS(true, "Animation", "Successfully loaded the enclose animation animation inv-name.", - "NONE"), - - ANIMATION_ENCLOSEMENT_INVROWS_SUCCESS(true, "Animation", - "Successfully loaded the enclose animation animation inventory-rows.", ""), - - ANIMATION_ENCLOSEMENT_INVROWS_INVALID(false, "Animation", "Failed to load the enclose animation inventory-rows.", - "It is either nonexistent or not a valid number."), - - ANIMATION_ENCLOSEMENT_FILLBLOCK_SUCCESS(true, "Animation", "Successfully loaded the enclose animation fill-block value.", - ""), - - ANIMATION_ENCLOSEMENT_FILLBLOCK_INVALID_MATERIAL(false, "Animation", - "Failed to load the enclose animation fill-block value.", - "$?$ is an invalid material."), - - ANIMATION_ENCLOSEMENT_FILLBLOCK_INVALID_BYTE(false, "Animation", - "Failed to load the enclose animation fill-block value.", - "$?$ is an invalid integer value."), - - ANIMATION_ENCLOSEMENT_FILLBLOCK_INVALID(false, "Animation", "Failed to load the enclose animation fill-block value.", - "$?$"), - - ANIMATION_ENCLOSEMENT_UPDATESPEED_SUCCESS(true, "Animation", "Successfully loaded the enclose animation update-speed.", - ""), - - ANIMATION_ENCLOSEMENT_UPDATESPEED_INVALID(false, "Animation", "Failed to load the enclose animation update-speed.", - "It is either nonexistent or not a valid number."), - - ANIMATION_ENCLOSEMENT_REWARDAMOUNT_SUCCESS(true, "Animation", "Successfully loaded the enclose animation reward-amount.", - ""), - - ANIMATION_ENCLOSEMENT_REWARDAMOUNT_INVALID(false, "Animation", "Failed to load the enclose animation reward-amount.", - "It is either nonexistent or not a valid number."), - - ANIMATION_ENCLOSEMENT_TICKSOUND_SOUND_SUCCESS(true, "Animation", "Loaded the enclose animation tick-sound SOUND.", - "NONE"), - - ANIMATION_ENCLOSEMENT_TICKSOUND_SOUND_FAILURE(false, "Animation", "Failed to load the enclose tick-sound.", - "The sound specified is not a valid sound, or doesn't exist."), - - ANIMATION_ENCLOSEMENT_TICKSOUND_VOLUMEPITCH_FAILURE(false, "Animation", - "Failed to load the enclose animation VOLUME and PITCH.", - "The values do not exist. (NOTE: These values are non-critical)"), - - ANIMATION_ENCLOSEMENT_TICKSOUND_VOLUME_SUCCESS(true, "Animation", "Loaded the enclose tick-sound VOLUME.", "NONE"), - - ANIMATION_ENCLOSEMENT_TICKSOUND_VOLUME_INVALID(false, "Animation", - "Failed to load the enclose animation tick-sound VOLUME.", "$?$ is not a valid number."), - - ANIMATION_ENCLOSEMENT_TICKSOUND_PITCH_SUCCESS(true, "Animation", "Loaded the enclose tick-sound PITCH.", "NONE"), - - ANIMATION_ENCLOSEMENT_TICKSOUND_PITCH_INVALID(false, "Animation", "Failed to load the enclose tick-sound PITCH.", - "$?$ + is not a valid number."), - - ANIMATION_DISCOVER_INVNAME_SUCCESS(true, "Animation", "Successfully loaded the discover animation inv-name.", - "NONE"), - - ANIMATION_DISCOVER_COVER_BLOCK_NAME_SUCCESS(true, "Animations", - "Successfully loaded the discover animation cover-block-name value.", "NONE"), - - ANIMATION_DISCOVER_COVER_BLOCK_LORE_SUCCESS(true, "Animations", - "Successfully loaded the discover animation cover-block-lore value.", "NONE"), - - ANIMATION_DISCOVER_REWARD_BLOCK_NAME_SUCCESS(true, "Animations", - "Successfully loaded the discover animation reward-block-name value.", "NONE"), - - ANIMATION_DISCOVER_REWARD_BLOCK_UNBLOCK_NAME_SUCCESS(true, "Animations", - "Successfully loaded the discover animation reward-block-unblock-name value.", "NONE"), - - ANIMATION_DISCOVER_REWARD_BLOCK_WAITING_NAME_SUCCESS(true, "Animations", - "Successfully loaded the discover animation reward-block-waiting-name value.", "NONE"), - - ANIMATION_DISCOVER_INVNAME_INVALID(false, "Animation", "Failed to load the discover animation inv-name value.", - "The inv-name value does not exist."), - - ANIMATION_DISCOVER_MINREWARDS_SUCCESS(true, "Animation", "Successfully loaded the discover animation min-rewards value.", - ""), - - ANIMATION_DISCOVER_MINREWARDS_INVALID(false, "Animation", "Failed to loaded the discover animation min-rewards value.", - "It is either nonexistent or an invalid number."), - - ANIMATION_DISCOVER_MAXREWARDS_SUCCESS(true, "Animation", "Successfully loaded the discover animation max-rewards value.", - ""), - - ANIMATION_DISCOVER_MAXREWARDS_INVALID(false, "Animation", "Failed to loaded the discover animation max-rewards value.", - "It is either nonexistent or an invalid number."), - - ANIMATION_DISCOVER_INVROWS_SUCCESS(true, "Animation", "Successfully loaded the discover animation inventory-rows value.", - ""), - - ANIMATION_DISCOVER_INVROWS_INVALID(false, "Animation", "Failed to loaded the discover animation inventory-rows value.", - "It is either nonexistent or an invalid number."), - - ANIMATION_DISCOVER_RANDDISPLAYLOCATION_SUCCESS(true, "Animation", - "Successfully loaded the discover animation random-display-duration value.", ""), - - ANIMATION_DISCOVER_RANDDISPLAYLOCATION_INVALID(false, "Animation", - "Failed to load the discover animation random-display-duration value.", - "It is either nonexistent or an invalid number."), - - ANIMATION_DISCOVER_COUNT_SUCCESS(true, "Animation", "Successfully loaded the discover animation count value.", ""), - - ANIMATION_DISCOVER_COUNT_INVALID(false, "Animation", "Failed to load the discover animation count value.", - "It is either nonexistent or an invalid true / false value."), - - ANIMATION_DISCOVER_COVERBLOCK_MATERIAL_INVALID(false, "Animation", "Failed to load the discover animation cover-block.", - "$?$ is an invalid material."), - - ANIMATION_DISCOVER_COVERBLOCK_DURABILITY_INVALID(false, "Animation", - "Failed to load the durability for the discover animation cover-block", "$?$ is an invalid number."), - - ANIMATION_DISCOVER_COVERBLOCK_INVALID(false, "Animation", "Failed to load the discover animation cover-block value.", - "It is nonexistent or not formatted MATERIAL;DURABILITY"), - - ANIMATION_DISCOVER_COVERBLOCK_SUCCESS(true, "Animation", "Successfully loaded the discover animation cover-block value.", - ""), - - ANIMATION_DISCOVER_REWARDBLOCK_MATERIAL_INVALID(false, "Animation", - "Failed to load the discover animation reward-block.", - "$?$ is an invalid material."), - - ANIMATION_DISCOVER_REWARDBLOCK_DURABILITY_INVALID(false, "Animation", - "Failed to load the durability for the discover animation reward-block", "$?$ is an invalid number."), - - ANIMATION_DISCOVER_REWARDBLOCK_INVALID(false, "Animation", "Failed to load the discover animation reward-block value.", - "It is nonexistent or not formatted MATERIAL;DURABILITY"), - - ANIMATION_DISCOVER_REWARDBLOCK_SUCCESS(true, "Animation", - "Successfully loaded the discover animation reward-block value.", - ""), - - ANIMATION_DISCOVER_TICKSOUND_SOUND_SUCCESS(true, "Animation", - "Successfully loaded the discover animation tick-sound SOUND", ""), - - ANIMATION_DISCOVER_TICKSOUND_SOUND_FAILURE(false, "Animation", "Failed to loud the discover animation tick-sound SOUND", - "The sound is invalid."), - - ANIMATION_DISCOVER_TICKSOUND_VOLUME_SUCCESS(true, "Animation", - "Successfully loaded the discover animation tick-sound VOLUME", ""), - - ANIMATION_DISCOVER_TICKSOUND_VOLUME_INVALID(false, "Animation", - "Failed to load the discover animation tick-sound VOLUME", "$?$ is not a valid number."), - - ANIMATION_DISCOVER_TICKSOUND_PITCHVOL_INVALID(false, "Animation", - "Failed to load the discover animation tick-sound VOLUME and PITCH", - "The sound is not formatted SOUND, VOLUME, PITCH"), - - ANIMATION_DISCOVER_TICKSOUND_PITCH_SUCCESS(true, "Animation", - "Successfully loaded the discover animation tick-sound PITCH", ""), - - ANIMATION_DISCOVER_TICKSOUND_PITCH_INVALID(false, "Animation", "Failed to load the discover animation tick-sound PITCH", - "$?$ is not a valid number."), - - ANIMATION_DISCOVER_CLICKSOUND_SOUND_SUCCESS(true, "Animation", - "Successfully loaded the discover animation click-sound SOUND", ""), - - ANIMATION_DISCOVER_CLICKSOUND_SOUND_FAILURE(false, "Animation", - "Failed to loud the discover animation click-sound SOUND", "The sound is invalid."), - - ANIMATION_DISCOVER_CLICKSOUND_VOLUME_SUCCESS(true, "Animation", - "Successfully loaded the discover animation click-sound VOLUME", ""), - - ANIMATION_DISCOVER_CLICKSOUND_VOLUME_INVALID(false, "Animation", - "Failed to load the discover animation click-sound VOLUME", "$?$ is not a valid number."), - - ANIMATION_DISCOVER_CLICKSOUND_PITCHVOL_INVALID(false, "Animation", - "Failed to load the discover animation click-sound VOLUME and PITCH", - "The sound is not formatted SOUND, VOLUME, PITCH"), - - ANIMATION_DISCOVER_CLICKSOUND_PITCH_SUCCESS(true, "Animation", - "Successfully loaded the discover animation click-sound PITCH", ""), - - ANIMATION_DISCOVER_CLICKSOUND_PITCH_INVALID(false, "Animation", - "Failed to load the discover animation click-sound PITCH", "$?$ is not a valid number."), - - ANIMATION_DISCOVER_UNCOVERSOUND_SOUND_SUCCESS(true, "Animation", - "Successfully loaded the discover animation uncover-sound SOUND", ""), - - ANIMATION_DISCOVER_UNCOVERSOUND_SOUND_FAILURE(false, "Animation", - "Failed to loud the discover animation uncover-sound SOUND", "The sound is invalid."), - - ANIMATION_DISCOVER_UNCOVERSOUND_VOLUME_SUCCESS(true, "Animation", - "Successfully loaded the discover animation uncover-sound VOLUME", ""), - - ANIMATION_DISCOVER_UNCOVERSOUND_VOLUME_INVALID(false, "Animation", - "Failed to load the discover animation uncover-sound VOLUME", "$?$ is not a valid number."), - - ANIMATION_DISCOVER_UNCOVERSOUND_PITCHVOL_INVALID(false, "Animation", - "Failed to load the discover animation uncover-sound VOLUME and PITCH", - "The sound is not formatted SOUND, VOLUME, PITCH"), - - ANIMATION_DISCOVER_UNCOVERSOUND_PITCH_SUCCESS(true, "Animation", - "Successfully loaded the discover animation uncover-sound PITCH", ""), - - ANIMATION_DISCOVER_UNCOVERSOUND_PITCH_INVALID(false, "Animation", - "Failed to load the discover animation uncover-sound PITCH", "$?$ is not a valid number."), - - ANIMATION_CSGO_INVNAME_SUCCESS(true, "Animation", "Successfully loaded the CSGO animation inv-name value.", "NONE"), - - ANIMATION_CSGO_TICKSOUND_SOUND_SUCCESS(true, "Animation", "Loaded the CSGO animation tick-sound SOUND.", "NONE"), - - ANIMATION_CSGO_TICKSOUND_SOUND_FAILURE(false, "Animation", "Failed to load the CSGO tick-sound.", - "The sound specified is not a valid sound, or doesn't exist."), - - ANIMATION_CSGO_TICKSOUND_VOLUMEPITCH_FAILURE(false, "Animation", "Failed to load the CSGO animation VOLUME and PITCH.", - "The values do not exist. (NOTE: These values are non-critical)"), - - ANIMATION_CSGO_TICKSOUND_VOLUME_SUCCESS(true, "Animation", "Loaded the CSGO tick-sound VOLUME.", "NONE"), - - ANIMATION_CSGO_TICKSOUND_VOLUME_INVALID(false, "Animation", "Failed to load the CSGO animation tick-sound VOLUME.", - "$?$ is not a valid number."), - - ANIMATION_CSGO_TICKSOUND_PITCH_SUCCESS(true, "Animation", "Loaded the CSGO tick-sound PITCH.", "NONE"), - - ANIMATION_CSGO_TICKSOUND_PITCH_INVALID(false, "Animation", "Failed to load the CSGO tick-sound PITCH.", - "$?$ + is not a valid number."), - - ANIMATION_CSGO_IDBLOCK_SUCCESS(true, "Animation", "Loaded the CSGO identifier-block.", "NONE"), - - ANIMATION_CSGO_IDBLOCK_INVALID(false, "Animations", "Failed to load the CSGO identifier-block.", - "$?$ is an invalid material or the byte value is not a number."), - - ANIMATION_CSGO_IDBLOCK_NONEXISTENT(false, "Animation", "Failed to load the CSGO identifier-block value.", - "The identifier-block value does not exist."), - - ANIMATION_CSGO_IDBLOCK_INVALID_MATERIAL(false, "Animation", "Failed to load the CSGO identifier-block value.", - "$?$ is not a valid material."), - - ANIMATION_CSGO_IDBLOCK_INVALID_BYTE(false, "Animation", "Failed to load the CSGO identifier-block value.", - "$?$ is not a valid integer."), - - ANIMATION_CSGO_FINALTICKLENGTH_SUCCESS(true, "Animation", "Loaded the CSGO final-crate-tick-length value.", "NONE"), - - ANIMATION_CSGO_FINALTICKLENGTH_INVALID(false, "Animation", "Failed to load the CSGO final-crate-tick-length.", - "The value does not exist or is not a valid number."), - - ANIMATION_CSGO_GLASSUPDATE_SUCCESS(true, "Animation", "Loaded the CSGO tile-update-ticks", "NONE"), - - ANIMATION_CSGO_GLASSUPDATE_INVALID(false, "Animation", "Failed to load the CSGO tile-update-ticks", - "The value is not a valid number or is nonexistent."), - - ANIMATION_CSGO_CLOSESPEED_SUCCESS(true, "Animation", "Loaded the CSGO close-speed", "NONE"), - - ANIMATION_CSGO_CLOSESPEED_INVALID(false, "Animation", "Failed to load the CSGO close-speed", - "The value is not a valid number or is nonexistent."), - - ANIMATION_CSGO_TICKSPEED_SUCCESS(true, "Animation", "Loaded the CSGO tick-speed-per-run value.", "NONE"), - - ANIMATION_CSGO_TICKSPEED_INVALID(false, "Animation", "Failed to load the CSGO tick-speed-per-run value.", - "It value does not exist or is not a valid number."), - - ANIMATION_CSGO_FILLERBLOCK_MATERIAL_INVALID(false, "Animation", "Failed to load the $?$ CSGO filler-block material.", - "That material does not exist."), - - ANIMATION_CSGO_FILLERBLOCK_MATERIAL_SUCCESS(true, "Animation", "Loaded the $?$ CSGO filler-block material.", "NONE"), - - ANIMATION_CSGO_FILLERBLOCK_ITEM_INVALID(false, "Animation", "Failed to load the CSGO filler-block item: $?$", - "It doesn't have a valid MATERIAL, or ID, or is not formatted MATERIAL;ID"), - - ANIMATION_CSGO_FILLERBLOCK_NONEXISTENT(false, "Animation", "Failed to load the CSGO filler-blocks.", - "The filler-blocks value does not exist."), - - ANIMATION_ROULETTE_INVNAME_SUCCESS(true, "Animation", "Successfully loaded the Roulette animation inv-name value.", - "NONE"), - - ANIMATION_ROULETTE_TICKSOUND_SOUND_SUCCESS(true, "Animation", "Loaded the Roulette animation tick-sound SOUND.", "NONE"), - - ANIMATION_ROULETTE_TICKSOUND_SOUND_FAILURE(false, "Animation", "Failed to load the Roulette tick-sound.", - "The sound specified is not a valid sound, or doesn't exist."), - - ANIMATION_ROULETTE_TICKSOUND_VOLUMEPITCH_FAILURE(false, "Animation", - "Failed to load the Roulette animation VOLUME and PITCH.", - "The values do not exist. (NOTE: These values are non-critical)"), - - ANIMATION_ROULETTE_TICKSOUND_VOLUME_SUCCESS(true, "Animation", "Loaded the Roulette tick-sound VOLUME.", "NONE"), - - ANIMATION_ROULETTE_TICKSOUND_VOLUME_INVALID(false, "Animation", - "Failed to load the Roulette animation tick-sound VOLUME.", "$?$ is not a valid number."), - - ANIMATION_ROULETTE_TICKSOUND_PITCH_SUCCESS(true, "Animation", "Loaded the Roulette tick-sound PITCH.", "NONE"), - - ANIMATION_ROULETTE_TICKSOUND_PITCH_INVALID(false, "Animation", "Failed to load the Roulette tick-sound PITCH.", - "$?$ + is not a valid number."), - - ANIMATION_ROULETTE_FINALTICKLENGTH_SUCCESS(true, "Animation", "Loaded the roulette final-crate-tick-length value.", - "NONE"), - - ANIMATION_ROULETTE_FINALTICKLENGTH_INVALID(false, "Animation", "Failed to load the roulette final-crate-tick-length.", - "The value does not exist or is not a valid number."), - - ANIMATION_ROULETTE_GLASSUPDATE_SUCCESS(true, "Animation", "Loaded the Roulette tile-update-ticks", "NONE"), - - ANIMATION_ROULETTE_GLASSUPDATE_INVALID(false, "Animation", "Failed to load the Roulette tile-update-ticks", - "The value is not a valid number or is nonexistent."), - - ANIMATION_ROULETTE_TICKSPEED_SUCCESS(true, "Animation", "Loaded the roulette tick-speed-per-run value.", "NONE"), - - ANIMATION_ROULETTE_TICKSPEED_INVALID(false, "Animation", "Failed to load the roulette tick-speed-per-run value.", - "It value does not exist or is not a valid number."), - - ANIMATION_ROULETTE_RANDOMBLOCK_MATERIAL_NONEXISTENT(false, "Animation", - "Failed to load the $?$ roulette random-block material.", "That material does not exist."), - - ANIMATION_ROULETTE_RANDOMBLOCK_MATERIAL_SUCCESS(true, "Animation", "Loaded the $?$ roulette random-block material.", - "NONE"), - - ANIMATION_ROULETTE_RANDOMBLOCK_ITEM_INVALID(false, "Animation", "Failed to load the roulette random-block item: $?$", - "It doesn't have a valid MATERIAL, or ID, or is not formatted MATERIAL;ID"), - - ANIMATION_ROULETTE_RANDOMBLOCK_NONEXISTENT(false, "Animation", "Failed to load the roulette random-blocks.", - "The random-blocks value does not exist."), - - ANIMATION_OPENCHEST_CHEST_OPEN_DURATION_INVALID(false, "Animation", - "Failed to load the openchest chest-open-duration value.", "It is either nonexistent or an invalid number."), - - ANIMATION_OPENCHEST_CHEST_OPEN_DURATION_SUCCESS(true, "Animation", - "Successfully loaded the chestopen chest-open-duration value.", "NONE"), - - ANIMATION_OPENCHEST_EARLY_REWARD_SUCCESS(true, "Animation", - "Successfully loaded the open chest early-reward-hologram value.", "NONE"), - - ANIMATION_OPENCHEST_EARLY_REWARD_INVALID(false, "Animation", - "Failed to load the open chest early-reward-hologram value.", - "It is either nonexistent or not a valid true/false value."), - - ANIMATION_OPENCHEST_REWARD_HOLO_DELAY_SUCCESS(true, "Animation", - "Successfully loaded the open chest reward-holo-delay value.", "NONE"), - - ANIMATION_OPENCHEST_REWARD_HOLO_DELAY_INVALID(false, "Animation", - "Failed to load the open chest reward-holo-delay value.", - "It is either nonexistent or not a valid decimal value."), - - ANIMATION_OPENCHEST_ATTACH_TO_SUCCESS(true, "Animation", - "Successfully loaded the open chest reward-holo-attach-to-item value.", "NONE"), - - ANIMATION_OPENCHEST_ATTACH_TO_INVALID(false, "Animation", - "Failed to load the open chest reward-holo-attach-to-item value.", - "It is either nonexistent or not a valid true/false value."), - - ANIMATION_OPENCHEST_EARLY_OPEN_ACTIONS_SUCCESS(true, "Animation", - "Successfully loaded the open chest early-open-actions value.", "NONE"), - - ANIMATION_OPENCHEST_EARLY_OPEN_ACTIONS_INVALID(false, "Animation", - "Faield to load the open chest early-open-actions value.", - "It is either nonexistent or not a valid true/false value."); - - - private final boolean success; - private final String event; - private final String cause; - private final String section; - - StatusLoggerEvent(boolean success, String section, String event, String cause) { - this.success = success; - this.event = event; - this.section = section; - - if (cause.equalsIgnoreCase("")) { - this.cause = "NONE"; - } else { - this.cause = cause; - } - } - - public void log(Crate crate) { - log(crate.getSettings().getStatusLogger()); - } - - public void log(Crate crate, String... args) { - log(crate.getSettings().getStatusLogger(), args); - } - - public void log(StatusLogger statusLogger, String... args) { - String eventDup = event; - String causeDup = cause; - int i = 0; - while (eventDup.contains("$?$")) { - int x = eventDup.indexOf("$?$"); - eventDup = eventDup.substring(0, x) + args[i] + - (x + 3 < eventDup.length() ? eventDup.substring(x + 3) : ""); - - i++; - } - - while (causeDup.contains("$?$")) { - int x = causeDup.indexOf("$?$"); - causeDup = causeDup.substring(0, x) + args[i] + - (x + 3 < causeDup.length() ? causeDup.substring(x + 3) : ""); - i++; - } - - statusLogger.addEvent(success, section, eventDup, causeDup); - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/logging/UpdateChecker.java b/src/main/java/me/ztowne13/customcrates/interfaces/logging/UpdateChecker.java deleted file mode 100644 index 55a3fa5..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/logging/UpdateChecker.java +++ /dev/null @@ -1,107 +0,0 @@ -package me.ztowne13.customcrates.interfaces.logging; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.Bukkit; - -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.net.HttpURLConnection; -import java.net.URL; -import java.nio.charset.StandardCharsets; - -/** - * Created by ztowne13 on 7/7/16. - */ -public class UpdateChecker { - private final SpecializedCrates instance; - private String latestVersion; - private boolean needsUpdate = false; - - public UpdateChecker(SpecializedCrates instance) { - this.instance = instance; - - if (Boolean.parseBoolean(instance.getSettings().getConfigValues().get("notify-updates").toString())) { - updateMostRecentVersion(); - } - } - - public void updateMostRecentVersion() { - Bukkit.getScheduler().runTaskAsynchronously(instance, () -> { - try { - HttpURLConnection con = - (HttpURLConnection) new URL("http://www.spigotmc.org/api/general.php").openConnection(); - con.setDoOutput(true); - con.setRequestMethod("POST"); - con.getOutputStream() - .write(("key=98BE0FE67F88AB82B4C197FAF1DC3B69206EFDCC4D3B80FC83A00037510B99B4&resource=" + 9047) - .getBytes(StandardCharsets.UTF_8)); - String version = new BufferedReader(new InputStreamReader(con.getInputStream())).readLine(); - if (version.length() <= 7) { - latestVersion = version; - } - updateNeedsUpdate(); - } catch (Exception ex) { - ex.printStackTrace(); - ChatUtils.log("Failed to check for a update on spigot."); - } - }); - } - - public void updateNeedsUpdate() { - String thisVersion = instance.getDescription().getVersion(); - - String[] splitCurrent = latestVersion.split("\\."); - String[] splitThis = thisVersion.split("\\."); - for (int i = 0; i < 4; i++) { - int currentI = splitCurrent.length <= i ? 0 : Integer.parseInt(splitCurrent[i]); - int thisI = splitThis.length <= i ? 0 : Integer.parseInt(splitThis[i]); - - if (currentI == thisI) { - continue; - } else if (currentI > thisI) { - ChatUtils.log(new String[]{ - "There is an update for Specialized Crates! You are currently on version " + thisVersion + - " but an update for version " + latestVersion + " is available."}); - //notifyPlayers(); - needsUpdate = true; - } - return; // If the plugin is a newer version - } - } - -// public void notifyPlayers() -// { -// for (final Player p : Bukkit.getOnlinePlayers()) -// { -// if (p.hasPermission(Bukkit.getPluginCommand("scrates").getPermission())) -// { -// Bukkit.getScheduler().scheduleSyncDelayedTask(cc, new Runnable() -// { -// @Override -// public void run() -// { -// Messages.NEEDS_UPDATE.msgSpecified(cc, p, new String[]{"%version%"}, -// new String[]{cc.getUpdateChecker().getLatestVersion()}); -// } -// }, 1); -// } -// } -// } - - public String getLatestVersion() { - return latestVersion; - } - - public void setLatestVersion(String latestVersion) { - this.latestVersion = latestVersion; - } - - public boolean needsUpdate() { - return needsUpdate; - } - - public void setNeedsUpdate(boolean needsUpdate) { - this.needsUpdate = needsUpdate; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/sql/SQL.java b/src/main/java/me/ztowne13/customcrates/interfaces/sql/SQL.java deleted file mode 100644 index 224d920..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/sql/SQL.java +++ /dev/null @@ -1,219 +0,0 @@ -package me.ztowne13.customcrates.interfaces.sql; - -import me.ztowne13.customcrates.SpecializedCrates; - -import java.sql.PreparedStatement; -import java.sql.ResultSet; - -public class SQL { - private final SQLConnection connection; - private final SpecializedCrates instance; - private int attempts = 0; - - public SQL(SpecializedCrates instance, String databaseIP, String database, String port, String username, String password) { - this.instance = instance; - connection = new SQLConnection(this, databaseIP, port, database, username, password); - } - - public SpecializedCrates getInstance() { - return instance; - } - - public Object get(String table, String where, String whereResult, - String sec) { - instance.getDebugUtils().log("get() - CALL : Object", getClass(), false); - if (connection.isOpen()) { - try { - attempts = 0; - PreparedStatement sql = getConnection().get().prepareStatement( - "SELECT * FROM `" + table + "` WHERE " + where + "='" - + whereResult + "';"); - ResultSet result = sql.executeQuery(); - result.next(); - return result.getObject(sec).toString(); - } catch (Exception exc) { - instance.getDebugUtils().log("get() - Exception handling request", getClass()); -// exc.printStackTrace(); -// new SQLLog("Unsuccessfuly retrieved something from database"); - return null; - } - - } else { - attempts++; - if (attempts <= 10) { - connection.open(); - return get(table, where, whereResult, sec); - } else { - instance.getDebugUtils().log("get() - Attempt limit reached"); -// new SQLLog("ERROR: SQL CONNECTION ATTEMPT LIMIT REACHED"); - } - } - return null; - } - - public ResultSet get(String table, String where, String whereResult) { - instance.getDebugUtils().log("get() - CALL : ResultSet", getClass()); - - if (connection.isOpen()) { - try { - attempts = 0; - PreparedStatement sql = getConnection().get().prepareStatement( - "SELECT * FROM `" + table + "` WHERE " + where + "='" - + whereResult + "';"); - ResultSet result = sql.executeQuery(); - result.next(); - return result; - } catch (Exception exc) { - instance.getDebugUtils().log("get() - Exception handling request", getClass()); -// exc.printStackTrace(); -// new SQLLog("Unsuccessfuly retrieved something from database"); - return null; - } - - } else { - attempts++; - if (attempts <= 10) { - connection.open(); - return get(table, where, whereResult); - } else { - instance.getDebugUtils().log("get() - Attempt limit reached"); -// new SQLLog("ERROR: SQL CONNECTION ATTEMPT LIMIT REACHED"); - } - } - return null; - } - - public void write(final String table, final String set_where, final String where_value, final String set_path, final String set_value) { - instance.getDebugUtils().log("write() - CALL", getClass(), true); - - if (connection.isOpen()) { - String pat = ""; - if (!isInt(set_value)) { - pat = "'" + set_value + "'"; - } else { - pat = set_value; - } - String query = "UPDATE `" + table + "` SET " + set_path + "=" + pat - + " WHERE " + set_where + "='" + where_value + "';"; - SQLQueryThread.addQuery(query); - } else { - attempts++; - if (attempts <= 10) { - connection.open(); - write(table, set_where, where_value, set_path, set_value); - } else { - instance.getDebugUtils().log("get() - Attempt limit reached"); -// new SQLLog("ERROR: SQL CONNECTION ATTEMPT LIMIT REACHED"); - } - } - } - - public void create(String table, String format, boolean uniqueUuid) { - instance.getDebugUtils().log("create() - CALL", getClass()); - - //format (name format(len), name int) - if (connection.isOpen()) { - try { - instance.getDebugUtils().log("create() - Creating table...", getClass()); - long curTime = System.currentTimeMillis(); - - String createQuery = "CREATE TABLE IF NOT EXISTS " + table + " (" + format + ")"; - connection.get().prepareStatement(createQuery).executeUpdate(); - - instance.getDebugUtils().log("create() - Finished creating table in " + (System.currentTimeMillis() - curTime) + "ms.", getClass()); - if (uniqueUuid) { - instance.getDebugUtils().log("create() - Updating unique uuid...", getClass()); - - try { - String uniqueQuery = "ALTER TABLE " + table + " ADD CONSTRAINT UQ_UUID UNIQUE (uuid)"; - connection.get().prepareStatement(uniqueQuery).executeUpdate(); - } catch (Exception exc) { - // IGNORED - } - - instance.getDebugUtils().log("create() - Finished updating unique id in " + (System.currentTimeMillis() - curTime) + - "ms.", getClass()); - } - } catch (Exception exc) { - exc.printStackTrace(); - instance.getDebugUtils().log("create() - FAILED TO CREATE TABLE!", getClass()); - } - } else { - instance.getDebugUtils().log("create() - ISSUE: SQLConnection is not open.", getClass()); - attempts++; - if (attempts <= 10) { - connection.open(); - create(table, format, uniqueUuid); - } else { - instance.getDebugUtils().log("get() - Attempt limit reached"); -// new SQLLog("ERROR: SQL CONNECTION ATTEMPT LIMIT REACHED"); - } - } - } - - /** - * @param table the table to insert into - * @param toSet formatted value1='val1', value2='val2' - * @param ignore whether or not to ignore duplicates - */ - public void insert(final String table, final String toSet, final boolean ignore) { - if (connection.isOpen()) { - try { - instance.getDebugUtils().log("insert() - CALL", getClass()); - - String query = "INSERT " + (ignore ? "IGNORE" : "") + " INTO " + table + " SET " + toSet; - connection.get().prepareStatement(query).executeUpdate(); - } catch (Exception exc) { - exc.printStackTrace(); - } - } else { - attempts++; - if (attempts <= 10) { - connection.open(); - insert(table, toSet, ignore); - } else { - instance.getDebugUtils().log("insert() - Attempt limit reached"); -// new SQLLog("ERROR: SQL CONNECTION ATTEMPT LIMIT REACHED"); - } - } - } - - public void replace(final String table, final String values, final String toSetValues) { - if (connection.isOpen()) { - try { - instance.getDebugUtils().log("replace() - CALL", getClass()); - - String query = "REPLACE INTO " + table + "(" + values + ") VALUES(" + toSetValues + ")"; - connection.get().prepareStatement(query).executeUpdate(); - } catch (Exception exc) { - exc.printStackTrace(); - } - } else { - attempts++; - if (attempts <= 10) { - connection.open(); - replace(table, values, toSetValues); - } else { - instance.getDebugUtils().log("replace() - Attempt limit reached"); -// new SQLLog("ERROR: SQL CONNECTION ATTEMPT LIMIT REACHED"); - } - } - } - - public boolean isInt(String s) { - try { - int i = Integer.parseInt(s); - return true; - } catch (Exception exc) { - } - return false; - } - - public SQLConnection getConnection() { - return connection; - } - - public int getAttempts() { - return attempts; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/sql/SQLConnection.java b/src/main/java/me/ztowne13/customcrates/interfaces/sql/SQLConnection.java deleted file mode 100644 index b900b84..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/sql/SQLConnection.java +++ /dev/null @@ -1,109 +0,0 @@ -package me.ztowne13.customcrates.interfaces.sql; - -import me.ztowne13.customcrates.utils.ChatUtils; - -import java.sql.Connection; -import java.sql.DriverManager; -import java.sql.SQLException; - -public class SQLConnection { - private static int queries = 0; - private final String host; - private final String database; - private final String user; - private final String pass; - private final String port; - private final SQL sql; - private Connection connection; - private boolean saidOnce = false; - - public SQLConnection(SQL sql, String host, String dbPort, String database, String user, String pass) { - this.host = host; - this.database = database; - this.user = user; - this.pass = pass; - this.sql = sql; - this.port = dbPort; - } - - public static int getQueries() { - return queries; - } - - public Connection open() { - return open(true); - } - - public Connection open(boolean log) { - try { - Connection c = connection = - DriverManager.getConnection("jdbc:mysql://" + this.host + ":" + port + "/" + this.database + "?autoReconnect=true&useSSL=false", this.user, this.pass); - if (log) - ChatUtils.log("[SpecializedCrates] Connection to the SQL database was completed successfuly."); - return c; - } catch (SQLException exc) { - if (!saidOnce) { - saidOnce = true; - if (log) - ChatUtils.log("[SpecializedCrates] Error connecting to the database, are the values in the config correct?"); - } - return null; - } - } - - public boolean isOpen() { - try { - return (connection != null) && (!connection.isClosed()); - } catch (SQLException e) { - // IGNORED - } - - return false; - } - - public Connection get() { - try { - if (queries >= 1000) { - if (connection != null) { - ChatUtils.log("[SpecializedCrates] Re-opening connection."); - connection.close(); - } - queries = 0; - open(); - } - - if (connection == null || connection.isClosed()) { - open(); - } - } catch (Exception exc) { - // IGNORED - } - - queries++; - return connection; - } - - public Connection getConnection() { - return connection; - } - - public String getHost() { - return host; - } - - public String getDatabase() { - return database; - } - - public String getUser() { - return user; - } - - public String getPass() { - return pass; - } - - public SQL getSql() { - return sql; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/interfaces/sql/SQLQueryThread.java b/src/main/java/me/ztowne13/customcrates/interfaces/sql/SQLQueryThread.java deleted file mode 100644 index 15a5159..0000000 --- a/src/main/java/me/ztowne13/customcrates/interfaces/sql/SQLQueryThread.java +++ /dev/null @@ -1,84 +0,0 @@ -package me.ztowne13.customcrates.interfaces.sql; - -import me.ztowne13.customcrates.players.data.SQLDataHandler; - -import java.util.Queue; -import java.util.concurrent.ConcurrentLinkedQueue; - -public class SQLQueryThread extends Thread { - private static final Queue sql_query = new ConcurrentLinkedQueue<>(); - private static final Queue task_query = new ConcurrentLinkedQueue<>(); - private static boolean stopped = false; - - private final SQL sql; - - public SQLQueryThread(SQL sql) { - this.sql = sql; - start(); - setName("SpecializedCrates-SQL"); - - sql.getInstance().getDebugUtils().log("SQLQueryThread() - Opening connection...", getClass()); - long curTime = System.currentTimeMillis(); - - sql.getConnection().open(); - - sql.getInstance().getDebugUtils().log("SQLQueryThread() - Completed opening connection in " + (System.currentTimeMillis() - curTime) + "ms.", getClass()); - } - - public static void addQuery(String query) { - sql_query.add(query); - } - - public static void stopRun() { - stopped = true; - } - - public static void clearQuery() { - sql_query.clear(); - task_query.clear(); - } - - public static void addQuery(Runnable runnable) { - task_query.add(runnable); - } - - @Override - public void run() { - boolean tryReconnect = false; - while (!stopped) { - try { - Thread.sleep(250); - } catch (InterruptedException exc) { - Thread.currentThread().interrupt(); - } - - if (!SQLDataHandler.isLoaded()) { - continue; - } - - while (!sql_query.isEmpty()) { - String query = sql_query.remove(); - sql.getInstance().getDebugUtils().log("run() - query: " + query, getClass()); - try { - sql.getConnection().get().prepareStatement(query).executeUpdate(); - tryReconnect = false; - } catch (Exception exc) { - if (!tryReconnect) { - tryReconnect = true; - sql.getConnection().open(); - sql.getInstance().getDebugUtils().log("Trying to reconnect to SQL servers."); - } else { - sql.getInstance().getDebugUtils().log("Failed to reconnect to SQL servers."); - exc.printStackTrace(); - } - } - } - - while (!task_query.isEmpty()) { - Runnable query = task_query.remove(); - sql.getInstance().getDebugUtils().log("run() - query: " + query.toString(), getClass()); - query.run(); - } - } - } -} diff --git a/src/main/java/me/ztowne13/customcrates/listeners/BlockBreakListener.java b/src/main/java/me/ztowne13/customcrates/listeners/BlockBreakListener.java deleted file mode 100644 index a5dfbf4..0000000 --- a/src/main/java/me/ztowne13/customcrates/listeners/BlockBreakListener.java +++ /dev/null @@ -1,83 +0,0 @@ -package me.ztowne13.customcrates.listeners; - -import me.ztowne13.customcrates.Messages; -import me.ztowne13.customcrates.SettingsValue; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.PlacedCrate; -import me.ztowne13.customcrates.crates.options.ObtainType; -import me.ztowne13.customcrates.players.PlayerManager; -import me.ztowne13.customcrates.utils.CrateUtils; -import org.bukkit.GameMode; -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.block.BlockBreakEvent; - -public class BlockBreakListener implements Listener { - SpecializedCrates cc; - - public BlockBreakListener(SpecializedCrates cc) { - this.cc = cc; - } - - @EventHandler - public void onBreakPlacedCrate(BlockBreakEvent e) { - Player p = e.getPlayer(); - Location l = e.getBlock().getLocation(); - - if (PlacedCrate.crateExistsAt(l)) { - PlacedCrate cm = PlacedCrate.get(cc, l); - Crate crates = cm.getCrate(); - - if (crates.getSettings().getObtainType().isStatic()) { - if (!p.hasPermission("customcrates.admin") && !p.hasPermission("specializedcrates.admin")) { - e.setCancelled(true); - Messages.FAILED_BREAK_CRATE.msgSpecified(cc, p, new String[]{"%crate%", "%reason%"}, - new String[]{crates.getDisplayName(), "static"}); - } - return; - } - - cm.delete(); - Messages.BROKEN_CRATE.msgSpecified(cc, p, new String[]{"%crate%"}, new String[]{crates.getDisplayName()}); - } - // LUCKY CHEST / MINE CRATES - else { - // Event isn't already cancelled - if (!e.isCancelled()) { - // Not in creative mode or creative mode is allowed - if (!p.getGameMode().equals(GameMode.CREATIVE) || (Boolean) SettingsValue.LUCKYCHEST_CREATIVE.getValue(cc)) { - // Luckychests enabled - if (PlayerManager.get(cc, p).getPlayerDataManager().isActivatedLuckyChests()) { - // Cycle through all potential crates - for (Crate crates : Crate.getLoadedCrates().values()) { - // Check if the crate is a lucky chest and if it is enabled - if (CrateUtils.isCrateUsable(crates) && crates.getSettings().luckyChestSettingsExists() && - crates.getSettings().getObtainType().equals(ObtainType.LUCKYCHEST)) { - // Check if the lucky chesty should be placed at the location - if (crates.getSettings().getLuckyChestSettings().checkRun(e.getBlock())) { - // Check if this block is a placed block or not and whether or not that's okay - if ((!e.getBlock().hasMetadata("PLACED") || - e.getBlock().getMetadata("PLACED") == null) || - (Boolean) SettingsValue.LUCKYCHEST_ALLOW_PLACED_BLOCKS.getValue(cc)) { - // Check to make sure the player has the permission or doesn't need the permission - if (!crates.getSettings().getLuckyChestSettings().isRequirePermission() || - e.getPlayer().hasPermission(crates.getSettings().getPermission())) { - PlacedCrate cm = PlacedCrate.get(cc, e.getBlock().getLocation()); - cm.setup(crates, true); - Messages.FOUND_LUCKY_CHEST.msgSpecified(cc, p); - e.setCancelled(true); - break; - } - } - } - } - } - } - } - } - } - } -} diff --git a/src/main/java/me/ztowne13/customcrates/listeners/BlockPlaceListener.java b/src/main/java/me/ztowne13/customcrates/listeners/BlockPlaceListener.java deleted file mode 100644 index 62d058b..0000000 --- a/src/main/java/me/ztowne13/customcrates/listeners/BlockPlaceListener.java +++ /dev/null @@ -1,45 +0,0 @@ -package me.ztowne13.customcrates.listeners; - -import me.ztowne13.customcrates.Messages; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.crateaction.AttemptCrateUseAction; -import me.ztowne13.customcrates.utils.CrateUtils; -import org.bukkit.Location; -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.BlockPlaceEvent; -import org.bukkit.metadata.FixedMetadataValue; - -public class BlockPlaceListener implements Listener { - SpecializedCrates cc; - - public BlockPlaceListener(SpecializedCrates cc) { - this.cc = cc; - } - - @EventHandler(priority = EventPriority.LOWEST) - public void onPlaceCrateKey(BlockPlaceEvent e) { - Player p = e.getPlayer(); - Location l = e.getBlock().getLocation(); - - if (!e.isCancelled()) { - if (CrateUtils.searchByKey(e.getItemInHand()) != null) { - Messages.DENY_PLACE_KEY.msgSpecified(cc, p); - e.setCancelled(true); - } else { - if (new AttemptCrateUseAction(cc, p, l, true).run()) { - e.setCancelled(true); - } - } - } - } - - @EventHandler - public void onPlace(BlockPlaceEvent e) { - Block b = e.getBlock(); - b.setMetadata("PLACED", new FixedMetadataValue(cc, "something")); - } -} diff --git a/src/main/java/me/ztowne13/customcrates/listeners/BlockRemoveListener.java b/src/main/java/me/ztowne13/customcrates/listeners/BlockRemoveListener.java deleted file mode 100644 index c3254b6..0000000 --- a/src/main/java/me/ztowne13/customcrates/listeners/BlockRemoveListener.java +++ /dev/null @@ -1,56 +0,0 @@ -package me.ztowne13.customcrates.listeners; - -import me.ztowne13.customcrates.SettingsValue; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.PlacedCrate; -import org.bukkit.block.Block; -import org.bukkit.block.BlockFace; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.block.BlockExplodeEvent; -import org.bukkit.event.block.BlockPistonExtendEvent; -import org.bukkit.event.entity.EntityExplodeEvent; - -import java.util.List; - -public class BlockRemoveListener implements Listener { - SpecializedCrates cc; - - public BlockRemoveListener(SpecializedCrates cc) { - this.cc = cc; - } - - @EventHandler - public void onBlockChange(BlockExplodeEvent e) { - if (cc.isAllowTick()) - if ((Boolean) SettingsValue.EXPLODE_DYNAMIC.getValue(cc)) - e.blockList().removeIf(b -> PlacedCrate.crateExistsAt(b.getLocation())); - } - - @EventHandler - public void onPistonPush(BlockPistonExtendEvent e) { - if (cc.isAllowTick() && shouldCancel(e.getBlocks(), e.getDirection())) - e.setCancelled(true); - } - - @EventHandler - public void onEntityExplode(EntityExplodeEvent e) { - if (cc.isAllowTick()) - if ((Boolean) SettingsValue.EXPLODE_DYNAMIC.getValue(cc)) - e.blockList().removeIf(b -> PlacedCrate.crateExistsAt(b.getLocation())); - } - - public boolean shouldCancel(List blocks, BlockFace bf) { - boolean shouldCancel = false; - if ((Boolean) SettingsValue.EXPLODE_DYNAMIC.getValue(cc)) { - for (Block b : blocks) { - if (PlacedCrate.crateExistsAt(b.getLocation()) || - PlacedCrate.crateExistsAt(b.getRelative(bf).getLocation())) { - shouldCancel = true; - break; - } - } - } - return shouldCancel; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/listeners/ChatListener.java b/src/main/java/me/ztowne13/customcrates/listeners/ChatListener.java deleted file mode 100644 index dda8f4c..0000000 --- a/src/main/java/me/ztowne13/customcrates/listeners/ChatListener.java +++ /dev/null @@ -1,75 +0,0 @@ -package me.ztowne13.customcrates.listeners; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.interfaces.igc.inputmenus.InputMenu; -import me.ztowne13.customcrates.players.PlayerManager; -import me.ztowne13.customcrates.utils.ChatUtils; -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.event.player.AsyncPlayerChatEvent; -import org.bukkit.event.player.PlayerCommandPreprocessEvent; - -/** - * Created by ztowne13 on 3/15/16. - */ -public class ChatListener implements Listener { - SpecializedCrates cc; - - public ChatListener(SpecializedCrates cc) { - this.cc = cc; - } - - @EventHandler(priority = EventPriority.LOWEST) - public void onChat(final AsyncPlayerChatEvent e) { - final Player p = e.getPlayer(); - if (p.hasPermission("customcrates.admin") || p.hasPermission("specializedcrates.admin")) { - PlayerManager pm = PlayerManager.get(cc, p); - if (pm.isInOpenMenu()) { - final IGCMenu menu = pm.getOpenMenu(); - if (menu.isInInputMenu()) { - final String msg = e.getMessage(); - final InputMenu im = menu.getInputMenu(); - - Bukkit.getScheduler().runTaskLater(cc, () -> { - im.runFor(menu, msg); - p.sendMessage(ChatUtils.toChatColor(" &7&l> &f" + msg)); - }, 1); - - e.getRecipients().clear(); - e.setCancelled(true); - } - } - } - } - - @EventHandler - public void onCmiReloadListener(PlayerCommandPreprocessEvent event) { - final Player player = event.getPlayer(); - - if (player.hasPermission("customcrates.admin") || player.hasPermission("specializedcrates.admin")) { - if (cc.getSettings().getInfoToLog().containsKey("Hologram Plugin") && - cc.getSettings().getInfoToLog().get("Hologram Plugin").equalsIgnoreCase("CMI")) { - String[] split = event.getMessage().split(" "); - if (split.length >= 2) { - if (split[0].equalsIgnoreCase("/cmi") || split[0].equalsIgnoreCase("/cmi:cmi")) { - if (split[1].equalsIgnoreCase("reload")) { - Bukkit.getScheduler().scheduleSyncDelayedTask(cc, () -> { - long start = System.currentTimeMillis(); - ChatUtils.msgInfo(player, - "You have executed &c/cmi reload&e. In order to keep holograms on the &6Specialized&7Crates &ecrates, &6Specialized&7Crates &eis also reloading."); - cc.reload(); - ChatUtils.msgInfo(player, - "Reloaded the Specialized Crate plugin &7(" + (System.currentTimeMillis() - start) + - "ms)&a."); - }, 10); - } - } - } - } - } - } -} diff --git a/src/main/java/me/ztowne13/customcrates/listeners/CommandPreprocessListener.java b/src/main/java/me/ztowne13/customcrates/listeners/CommandPreprocessListener.java deleted file mode 100644 index bd8b20f..0000000 --- a/src/main/java/me/ztowne13/customcrates/listeners/CommandPreprocessListener.java +++ /dev/null @@ -1,37 +0,0 @@ -package me.ztowne13.customcrates.listeners; - -import me.ztowne13.customcrates.Messages; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.players.PlayerManager; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerCommandPreprocessEvent; - -/** - * Created by ztowne13 on 3/3/16. - */ -public class CommandPreprocessListener implements Listener { - SpecializedCrates cc; - - public CommandPreprocessListener(SpecializedCrates cc) { - this.cc = cc; - } - - @EventHandler - public void onCommandPP(PlayerCommandPreprocessEvent e) { - Player p = e.getPlayer(); - PlayerManager pm = PlayerManager.get(cc, p); - - long ct = System.currentTimeMillis(); - long diff = ct - pm.getCmdCooldown(); - - if (diff < 1000 && !pm.getLastCooldown().equalsIgnoreCase("cmd")) { - e.setCancelled(true); - Messages.WAIT_ONE_SECOND.msgSpecified(cc, p); - } - - pm.setLastCooldown("cmd"); - pm.setCmdCooldown(ct); - } -} diff --git a/src/main/java/me/ztowne13/customcrates/listeners/DamageListener.java b/src/main/java/me/ztowne13/customcrates/listeners/DamageListener.java deleted file mode 100644 index 7ab359d..0000000 --- a/src/main/java/me/ztowne13/customcrates/listeners/DamageListener.java +++ /dev/null @@ -1,25 +0,0 @@ -package me.ztowne13.customcrates.listeners; - -import me.ztowne13.customcrates.SpecializedCrates; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.entity.EntityDamageByEntityEvent; - -public class DamageListener implements Listener { - SpecializedCrates sc; - - public DamageListener(SpecializedCrates sc) { - this.sc = sc; - } - - @EventHandler - public void onFireworkExplode(EntityDamageByEntityEvent event) { - if (event.getDamager().getCustomName() != null) { - if (event.getDamager().getCustomName().equalsIgnoreCase("scf")) { - if (!event.getDamager().isCustomNameVisible()) { - event.setCancelled(true); - } - } - } - } -} diff --git a/src/main/java/me/ztowne13/customcrates/listeners/InteractListener.java b/src/main/java/me/ztowne13/customcrates/listeners/InteractListener.java deleted file mode 100644 index ca30bd0..0000000 --- a/src/main/java/me/ztowne13/customcrates/listeners/InteractListener.java +++ /dev/null @@ -1,74 +0,0 @@ -package me.ztowne13.customcrates.listeners; - -import me.ztowne13.customcrates.SettingsValue; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.crateaction.AttemptKeyUseAction; -import me.ztowne13.customcrates.crates.crateaction.CrateAction; -import me.ztowne13.customcrates.crates.crateaction.LeftClickAction; -import me.ztowne13.customcrates.utils.CrateUtils; -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; - -public class InteractListener implements Listener { - SpecializedCrates cc; - - public InteractListener(SpecializedCrates cc) { - this.cc = cc; - } - - @EventHandler(priority = EventPriority.LOWEST) - public void onInteract(PlayerInteractEvent e) { - cc.getDebugUtils().log("onInteract - CALL", this.getClass()); - cc.getDebugUtils().log("onInteract - (cancelled: " + e.isCancelled() + ")", getClass()); - - Player p = e.getPlayer(); - - // Handle crate left or right click - if (e.getAction().equals(Action.RIGHT_CLICK_BLOCK) || e.getAction().equals(Action.LEFT_CLICK_BLOCK)) { - cc.getDebugUtils().log("onInteract - Click block", this.getClass()); - - CrateAction action; - if (e.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { - action = new AttemptKeyUseAction(cc, p, e.getClickedBlock().getLocation()); - cc.getDebugUtils().log("onInteract - is right click block", getClass()); - } else { - action = new LeftClickAction(cc, p, e.getClickedBlock().getLocation()); - } - - boolean result = action.run(); - if (result) { - cc.getDebugUtils().log("onInteract - Cancelling", getClass()); - e.setCancelled(true); - } - } - - // Prevent crate keys from being used for anything else (enderpearls not being throw, etc.) - if (e.getItem() != null) { - for (Crate crate : Crate.getLoadedCrates().values()) { - if (crate.getSettings().getKeyItemHandler().keyMatchesToStack(e.getItem(), false)) { - if (!((Boolean) SettingsValue.KEY_ALLOW_LEFT_CLICK_INTERACTION.getValue(cc) && e.getAction().equals(Action.LEFT_CLICK_BLOCK))) { - e.setCancelled(true); - } - } - } - } - } - - @EventHandler - public void onKeyPreviewMenu(PlayerInteractEvent event) { - Action action = event.getAction(); - if (action.equals(Action.LEFT_CLICK_BLOCK) || action.equals(Action.LEFT_CLICK_AIR)) { - if ((Boolean) SettingsValue.LEFT_CLICK_KEY_PREVIEW.getValue(cc)) { - Crate crate = CrateUtils.searchByKey(event.getItem()); - if (crate != null) { - crate.getSettings().getDisplayer().openFor(event.getPlayer()); - } - } - } - } -} diff --git a/src/main/java/me/ztowne13/customcrates/listeners/InventoryActionListener.java b/src/main/java/me/ztowne13/customcrates/listeners/InventoryActionListener.java deleted file mode 100644 index 9983eea..0000000 --- a/src/main/java/me/ztowne13/customcrates/listeners/InventoryActionListener.java +++ /dev/null @@ -1,299 +0,0 @@ -package me.ztowne13.customcrates.listeners; - -import me.ztowne13.customcrates.Messages; -import me.ztowne13.customcrates.SettingsValue; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.PlacedCrate; -import me.ztowne13.customcrates.crates.types.animations.AnimationDataHolder; -import me.ztowne13.customcrates.crates.types.animations.CrateAnimation; -import me.ztowne13.customcrates.interfaces.igc.crates.IGCMultiCrateMain; -import me.ztowne13.customcrates.interfaces.igc.crates.previeweditor.IGCCratePreviewEditor; -import me.ztowne13.customcrates.interfaces.igc.fileconfigs.rewards.IGCDragAndDrop; -import me.ztowne13.customcrates.interfaces.items.ItemBuilder; -import me.ztowne13.customcrates.players.PlayerDataManager; -import me.ztowne13.customcrates.players.PlayerManager; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.CrateUtils; -import me.ztowne13.customcrates.utils.Utils; -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.*; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; - -public class InventoryActionListener implements Listener { - SpecializedCrates cc; - - public InventoryActionListener(SpecializedCrates cc) { - this.cc = cc; - } - - @EventHandler - public void onInventoryDrag(InventoryDragEvent e) { - cc.getDebugUtils().log("onInventoryDrag - CALL", getClass()); - - Player player = (Player) e.getWhoClicked(); - PlayerManager playerManager = PlayerManager.get(cc, player); - - if (playerManager.isInCrate() || playerManager.isInRewardMenu()) { - cc.getDebugUtils().log("onInventoryDrag - CANCELLED"); - e.setCancelled(true); - } else if (playerManager.isInOpenMenu()) { - if (e.getView().getTopInventory() != null) { - if (playerManager.getOpenMenu() instanceof IGCCratePreviewEditor && - e.getRawSlots().equals(e.getInventorySlots())) { - try { - for (int slot : e.getInventorySlots()) - ((IGCCratePreviewEditor) playerManager.getOpenMenu()) - .manageClick(slot, true, e.getNewItems().values().iterator().next()); - e.setCancelled(true); - } catch (Exception exc) { - exc.printStackTrace(); - } - } - } - } - } - - @EventHandler - public void onInventoryClick(InventoryClickEvent e) { - Player p = (Player) e.getWhoClicked(); - PlayerManager pm = PlayerManager.get(cc, p); - - int slot = e.getSlot(); - - if (pm.isInCrate() || pm.isInRewardMenu()) { - e.setCancelled(true); - - if (isntPlayerInventory(e, pm)) { - - if (pm.isInRewardMenu() && pm.getLastPage() != null) { - pm.getLastPage().handleInput(p, e.getSlot()); - } - - // Handle multicrate click - if (pm.isInCrate() && pm.getOpenCrate().isMultiCrate()) { - Crate crate = pm.getOpenCrate(); - crate.getSettings().getMultiCrateSettings().checkClick(pm, slot, e.getClick()); - e.setCancelled(true); - } - // Handle discover animation click - else if (pm.isInCrate()) { - pm.getOpenCrate().getSettings().getCrateAnimation().handleClick(pm.getCurrentAnimation(), slot); - } - } - } - - /*if (pm.isWaitingForClose()) - { - e.setCancelled(true); - pm.closeCrate(); - for (Reward r : pm.getWaitingForClose()) - { - r.runCommands(p); - } - pm.setWaitingForClose(null); - p.closeInventory(); - }*/ - } - - /** - * Handles anvil crafting - mainly to prevent key/crate renaming. - * - * @param e The event passed by the server - */ - @EventHandler - public void onAnvilClick(InventoryClickEvent e) { - if (e.getInventory().getType().equals(InventoryType.ANVIL)) { - if (e.getInventory().getItem(2) != null) { - ItemBuilder builder = new ItemBuilder(e.getInventory().getItem(2)); - if (builder.hasDisplayName()) { - if (CrateUtils.searchByCrate(builder.getStack()) != null || CrateUtils.searchByKey(builder.getStack()) != null) { - e.setCancelled(true); - e.getWhoClicked().closeInventory(); - Messages.CANT_CRAFT_KEYS.msgSpecified(cc, (Player) e.getWhoClicked()); - } - } - } - } - } - - /** - * Handles inventory clicks intended in the in-game config inventory editors. - * - * @param e The event passed by the server - */ - @EventHandler - public void onIGCClick(InventoryClickEvent e) { - Player p = (Player) e.getWhoClicked(); - PlayerManager pm = PlayerManager.get(cc, p); - - if ((p.hasPermission("customcrates.admin") || p.hasPermission("specializedcrates.admin")) && pm.isInOpenMenu()) { - if (!(e.getClickedInventory() == null || e.getView().getTopInventory() == null)) { - if (e.getClickedInventory().equals(e.getView().getTopInventory()) && - !e.getView().getTitle().equalsIgnoreCase(ChatUtils.toChatColor("&c&lClose to save"))) { - if (!(pm.getOpenMenu() instanceof IGCDragAndDrop) || e.getSlot() == 52 || e.getSlot() == 53) - e.setCancelled(true); - - try { - pm.getOpenMenu().manageClick(e.getSlot()); - } catch (Exception exc) { - exc.printStackTrace(); - } - } - } - } - } - - @EventHandler - public void onCratesClaimClick(InventoryClickEvent e) { - if (e.getWhoClicked() instanceof Player) { - Player player = (Player) e.getWhoClicked(); - PlayerManager playerManager = PlayerManager.get(cc, player); - - if (playerManager.isInCratesClaimMenu()) { - if (!((boolean) SettingsValue.CRATES_CLAIM_ALLOW_DEPOSIT.getValue(cc))) { - if ((e.getClickedInventory() != player.getInventory() && (player.getItemOnCursor() != null && !player.getItemOnCursor().getType().equals(Material.AIR))) - || (!e.getClick().equals(ClickType.LEFT) && !e.getClick().equals(ClickType.RIGHT))) { - e.setCancelled(true); - Messages.CRATES_CLAIM_DENY_DEPOSIT_KEYS.msgSpecified(cc, player); - } - } - } - } - } - - @EventHandler - public void onCrateAnimationESCKey(InventoryCloseEvent e) { - Player player = (Player) e.getPlayer(); - PlayerManager pm = PlayerManager.get(cc, player); - - if (pm.isInCrateAnimation()) { - AnimationDataHolder dataHolder = pm.getCurrentAnimation(); - dataHolder.getCrateAnimation().handleKeyPress(dataHolder, CrateAnimation.KeyType.ESC); - } - } - - @EventHandler - public void onCratesClaimClose(InventoryCloseEvent e) { - if (e.getPlayer() instanceof Player) { - Player player = (Player) e.getPlayer(); - PlayerManager playerManager = PlayerManager.get(cc, player); - PlayerDataManager dataManager = playerManager.getPlayerDataManager(); - - if (playerManager.isInCratesClaimMenu()) { - preventDupeReopen(player, e.getInventory(), false); - playerManager.setInCratesClaimMenu(false); - for (ItemStack stack : e.getInventory().getContents()) { - if (stack == null || stack.getType() == Material.AIR) { - continue; - } - - Crate result = CrateUtils.searchByKey(stack); - if (result != null) { - dataManager.setVirtualCrateKeys(result, dataManager.getVCCrateData(result).getKeys() + stack.getAmount()); - } else { - Utils.addItemAndDropRest(player, stack); - } - } - } - } - } - - @EventHandler - public void onInventoryClose(InventoryCloseEvent e) { - final Player p = (Player) e.getPlayer(); - final PlayerManager pm = PlayerManager.get(cc, p); - - pm.setLastPage(null); - - if (pm.isInOpenMenu() && !pm.getOpenMenu().isInInputMenu()) { - - if (e.getView().getTitle().equalsIgnoreCase(ChatUtils.toChatColor("&7&l> &6&lClose to save"))) { - - pm.getOpenMenu().manageClick(-1); - ChatUtils.msgSuccess(p, - "Successfully saved all rewards. Please go through and update all of their commands as well as their chance values."); - Bukkit.getScheduler().scheduleSyncDelayedTask(cc, () -> pm.getOpenMenu().up(), 1); - } - // Closing a multicrate - else if (e.getView().getTitle().equalsIgnoreCase(ChatUtils.toChatColor("&c&lClose to save"))) { - ChatUtils.msgInfo(p, "There are unsaved changes, please remember to save."); - IGCMultiCrateMain openMenu = (IGCMultiCrateMain) pm.getOpenMenu(); - openMenu.getCrates().getSettings().getMultiCrateSettings().updateCrateSpots(); - Bukkit.getScheduler().scheduleSyncDelayedTask(cc, () -> pm.getOpenMenu().open(), 1); - } else if (pm.getOpenMenu() instanceof IGCCratePreviewEditor) { - ((IGCCratePreviewEditor) pm.getOpenMenu()).getCustomRewardDisplayer().saveAllPages(); - Bukkit.getScheduler().scheduleSyncDelayedTask(cc, () -> { - if (pm.getOpenMenu() instanceof IGCCratePreviewEditor) - pm.getOpenMenu().up(); - }, 1); - } else if (!(pm.getOpenMenu() instanceof IGCMultiCrateMain)) { - pm.setOpenMenu(null); - Bukkit.getScheduler().scheduleSyncDelayedTask(cc, () -> { - if (!pm.isInOpenMenu()) { - ChatUtils.msg(p, "&9&lNOTE: &bType &f'/scrates !' &bto reopen to your last config menu!"); - } - }, 1); - } - } - - // Close the multicrate - if (pm.isInCrate() && !pm.isInRewardMenu()) { - if (pm.getOpenCrate() != null && pm.getOpenCrate().isMultiCrate()) { - pm.closeCrate(); - preventDupeReopen(p, e.getInventory(), true); - } - } - - // Handle closing an inventory while the reward preview menu is open - if (pm.isInRewardMenu()) { - final Crate cachedOpenCrate = pm.getOpenCrate(); - final PlacedCrate cachedLastOpenedPlacedCrate = pm.getLastOpenedPlacedCrate(); - if (pm.getNextPageInventoryCloseGrace() <= cc.getTotalTicks()) { - // This is to reopen a multicrate if the reward preview menu was closed - if (pm.isInCrate() && pm.getOpenCrate().isMultiCrate()) { - pm.setInRewardMenu(false); - Bukkit.getScheduler().runTaskLater(cc, () -> cachedOpenCrate.getSettings().getMultiCrateSettings().openFor(p, cachedLastOpenedPlacedCrate), 1); - } - // This is to prevent duplication in the reward menu - it reopens the inventory very briefly and re-closes it. - else { - pm.setInRewardMenu(false); - preventDupeReopen(p, e.getInventory(), false); - } - } - } - } - - public void preventDupeReopen(final Player player, final Inventory inventory, final boolean checkInRewardMenu) { - Bukkit.getScheduler().runTaskLater(cc, () -> { - if (checkInRewardMenu) { - if (PlayerManager.get(cc, player).isInRewardMenu()) { - return; - } - } - - if (inventory.getType().equals(InventoryType.CRAFTING)) { - return; - } - - player.openInventory(inventory); - player.closeInventory(); - }, 1); - } - - public boolean isntPlayerInventory(InventoryClickEvent e, PlayerManager pm) { - cc.getDebugUtils().log("onInventoryClick - In crate or reward menu (" + pm.isInCrate() + " : " + pm.isInRewardMenu() + - ")", getClass()); - if (!(e.getClickedInventory() == null || e.getWhoClicked().getInventory() == null)) { - cc.getDebugUtils().log("onInventoryClick - Clicked inventory and clicker aren't null."); - return !e.getClickedInventory().equals(e.getWhoClicked().getInventory()); - } - return false; - } -} - diff --git a/src/main/java/me/ztowne13/customcrates/listeners/NPCEventListener.java b/src/main/java/me/ztowne13/customcrates/listeners/NPCEventListener.java deleted file mode 100644 index 773dcca..0000000 --- a/src/main/java/me/ztowne13/customcrates/listeners/NPCEventListener.java +++ /dev/null @@ -1,34 +0,0 @@ -package me.ztowne13.customcrates.listeners; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.crateaction.AttemptKeyUseAction; -import me.ztowne13.customcrates.crates.crateaction.LeftClickAction; -import net.citizensnpcs.api.event.NPCLeftClickEvent; -import net.citizensnpcs.api.event.NPCRightClickEvent; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; - -/** - * Created by ztowne13 on 2/26/16. - */ -public class NPCEventListener implements Listener { - SpecializedCrates cc; - - public NPCEventListener(SpecializedCrates cc) { - this.cc = cc; - } - - @EventHandler - public void onNPCClickRight(NPCRightClickEvent e) { - if (new AttemptKeyUseAction(cc, e.getClicker(), e.getNPC().getStoredLocation()).run()) { - e.setCancelled(true); - } - } - - @EventHandler() - public void onNPCClickLeft(NPCLeftClickEvent e) { - Player p = e.getClicker(); - new LeftClickAction(cc, p, e.getNPC().getStoredLocation()).run(); - } -} diff --git a/src/main/java/me/ztowne13/customcrates/listeners/PlayerConnectionListener.java b/src/main/java/me/ztowne13/customcrates/listeners/PlayerConnectionListener.java deleted file mode 100644 index 4fc490a..0000000 --- a/src/main/java/me/ztowne13/customcrates/listeners/PlayerConnectionListener.java +++ /dev/null @@ -1,43 +0,0 @@ -package me.ztowne13.customcrates.listeners; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.players.PlayerManager; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerQuitEvent; - -public class PlayerConnectionListener implements Listener { - SpecializedCrates cc; - - public PlayerConnectionListener(SpecializedCrates cc) { - this.cc = cc; - } - -// @EventHandler -// public void adminJoin(PlayerJoinEvent e) -// { -// final Player p = e.getPlayer(); -// PlayerManager.get(cc, p); -// if (p.hasPermission("customcrates.admin") && cc.getUpdateChecker().needsUpdate()) -// { -// Bukkit.getScheduler().scheduleSyncDelayedTask(cc, new Runnable() -// { -// @Override -// public void run() -// { -// Messages.NEEDS_UPDATE.msgSpecified(cc, p, new String[]{"%version%"}, -// new String[]{cc.getUpdateChecker().getLatestVersion()}); -// } -// }, 1); -// } -// } - - @EventHandler - public void onQuit(PlayerQuitEvent e) { - cc.getDebugUtils().log("onQuit() - CALL (" + e.getPlayer().getName() + ")", getClass()); - Player p = e.getPlayer(); - PlayerManager.get(cc, p).remove(20); - } - -} diff --git a/src/main/java/me/ztowne13/customcrates/listeners/PluginEnableListener.java b/src/main/java/me/ztowne13/customcrates/listeners/PluginEnableListener.java deleted file mode 100644 index 0eb1a85..0000000 --- a/src/main/java/me/ztowne13/customcrates/listeners/PluginEnableListener.java +++ /dev/null @@ -1,37 +0,0 @@ -package me.ztowne13.customcrates.listeners; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.PlacedCrate; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.server.PluginEnableEvent; - -public class PluginEnableListener implements Listener { - SpecializedCrates sc; - - String[] toListenHolograms = new String[]{ - "CMI", - "Holographic Displays", - "Holograms" - }; - - public PluginEnableListener(SpecializedCrates sc) { - this.sc = sc; - } - - @EventHandler - public void onPluginEnable(PluginEnableEvent pluginEnableEvent) { - for (String hologramName : toListenHolograms) { - if (hologramName.equalsIgnoreCase(pluginEnableEvent.getPlugin().getName())) { - for (PlacedCrate crate : PlacedCrate.getPlacedCrates().values()) { - crate.setupHolo(crate.getCrate(), false); - } - } - } - - if (pluginEnableEvent.getPlugin().getName().equalsIgnoreCase("Multiverse-Core")) { - for (String s : sc.getSettings().getFailedPlacedCrate()) - sc.getSettings().loadCrateFromFile(s); - } - } -} diff --git a/src/main/java/me/ztowne13/customcrates/listeners/TabCompleteListener.java b/src/main/java/me/ztowne13/customcrates/listeners/TabCompleteListener.java deleted file mode 100644 index 20fd27c..0000000 --- a/src/main/java/me/ztowne13/customcrates/listeners/TabCompleteListener.java +++ /dev/null @@ -1,166 +0,0 @@ -package me.ztowne13.customcrates.listeners; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.commands.sub.SubCommand; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.CrateSettings; -import me.ztowne13.customcrates.utils.Utils; -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.command.TabCompleter; -import org.bukkit.entity.Player; - -import java.util.ArrayList; -import java.util.List; - -/** - * Created by ztowne13 on 2/19/16. - */ -public class TabCompleteListener implements TabCompleter { - SpecializedCrates cc; - - public TabCompleteListener(SpecializedCrates cc) { - this.cc = cc; - } - - @Override - public List onTabComplete(CommandSender sender, Command cmd, String alias, String[] args) { - List list = new ArrayList(); - if (sender instanceof Player) { - Player player = (Player) sender; - String cN = cmd.getName(); - if (cN.equalsIgnoreCase("crates") || - cN.equalsIgnoreCase("specializedcrates") || - cN.equalsIgnoreCase("sc") || - cN.equalsIgnoreCase("scrates") || - cN.equalsIgnoreCase("ccrates")) { - if (args.length == 1) { - if (player.hasPermission("customcrates.admin") || player.hasPermission("specializedcratest.admin")) { - list.add("config"); - list.add("virtualcrates"); - list.add("givecrate"); - list.add("givekey"); - list.add("edit"); - list.add("errors"); - list.add("deletecrate"); - list.add("listcrates"); - list.add("listhistory"); - list.add("delallcratetype"); - list.add("reload"); - list.add("info"); - list.add("!"); - list.add("luckychest"); - list.add("forceopen"); - list.add("toggleparticles"); - list.add("spawncrate"); - list.add("claim"); - } else { - list.add("luckychest"); - list.add("claim"); - } - list = Utils.onlyLeaveEntriesWithPref(list, args[0]); - } else { - if (SubCommand.getMappedAliases().containsKey(args[0])) { - args[0] = SubCommand.getMappedAliases().get(args[0]); - } - - if (args[0].equalsIgnoreCase("givekey") || args[0].equalsIgnoreCase("givecrate") || - args[0].equalsIgnoreCase("delallcratetype")) { - if (args.length == 2) { - for (Crate crates : Crate.getLoadedCrates().values()) { - list.add(crates.getName()); - } - list = Utils.onlyLeaveEntriesWithPref(list, args[1]); - } - if (!args[0].equalsIgnoreCase("delallcratetype")) { - if (args.length == 3) { - list.add("all"); - for (Player p : Bukkit.getOnlinePlayers()) { - list.add(p.getName()); - } - list = Utils.onlyLeaveEntriesWithPref(list, args[2]); - } else if (args.length == 4) { - list.add("1"); - list = Utils.onlyLeaveEntriesWithPref(list, ""); - } else if (args.length == 5) { - list.add("-v"); - } - } - } else if (args[0].equalsIgnoreCase("edit")) { - for (Crate crates : Crate.getLoadedCrates().values()) { - list.add(crates.getName()); - } - list = Utils.onlyLeaveEntriesWithPref(list, args[1]); - } else if (args[0].equalsIgnoreCase("forceopen")) { - if (args.length == 2) { - for (Crate crates : Crate.getLoadedCrates().values()) { - list.add(crates.getName()); - } - list = Utils.onlyLeaveEntriesWithPref(list, args[1]); - } - if (args.length == 3) { - list.add("all"); - for (Player p : Bukkit.getOnlinePlayers()) { - list.add(p.getName()); - } - - list = Utils.onlyLeaveEntriesWithPref(list, args[2]); - } - } else if (args[0].equalsIgnoreCase(("listhistory"))) { - if (args.length == 2) { - for (Player p : Bukkit.getOnlinePlayers()) { - list.add(p.getName()); - } - - list = Utils.onlyLeaveEntriesWithPref(list, args[1]); - } else if (args.length == 3) { - list.add("10"); - list = Utils.onlyLeaveEntriesWithPref(list, ""); - } - } else if (args[0].equalsIgnoreCase("errors")) { - for (Crate crates : Crate.getLoadedCrates().values()) { - list.add(crates.getName()); - } - list = Utils.onlyLeaveEntriesWithPref(list, args[1]); - } else if (args[0].equalsIgnoreCase("spawncrate")) { - if (args.length == 2) { - for (Crate crates : Crate.getLoadedCrates().values()) { - list.add(crates.getName()); - } - list = Utils.onlyLeaveEntriesWithPref(list, args[1]); - } else if (args.length == 3) { - for (World world : Bukkit.getWorlds()) { - list.add(world.getName()); - } - list = Utils.onlyLeaveEntriesWithPref(list, args[2]); - } else if (args.length == 4) { - list.add("x"); - } else if (args.length == 5) { - list.add("y"); - } else if (args.length == 6) { - list.add("z"); - } - } - } - - } else if (cN.equalsIgnoreCase("rewards")) { - if (args.length >= 1) { - for (Crate crates : Crate.getLoadedCrates().values()) { - CrateSettings cs = crates.getSettings(); - - if (player.hasPermission(cs.getPermission()) || cs.getPermission().equalsIgnoreCase("no permission")) - if (!crates.isMultiCrate()) - list.add(crates.getName()); - } - - list = Utils.onlyLeaveEntriesWithPref(list, args[0]); - } - } - } - - - return list; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/players/PlayerDataManager.java b/src/main/java/me/ztowne13/customcrates/players/PlayerDataManager.java deleted file mode 100644 index 78897d3..0000000 --- a/src/main/java/me/ztowne13/customcrates/players/PlayerDataManager.java +++ /dev/null @@ -1,327 +0,0 @@ -package me.ztowne13.customcrates.players; - -import me.ztowne13.customcrates.SettingsValue; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import me.ztowne13.customcrates.interfaces.sql.SQLQueryThread; -import me.ztowne13.customcrates.players.data.DataHandler; -import me.ztowne13.customcrates.players.data.SQLDataHandler; -import me.ztowne13.customcrates.players.data.VirtualCrateData; -import me.ztowne13.customcrates.players.data.events.CrateCooldownEvent; -import me.ztowne13.customcrates.players.data.events.HistoryEvent; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.CrateUtils; -import me.ztowne13.customcrates.utils.DebugUtils; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Created by ztowne13 on 8/5/15. - */ -public class PlayerDataManager { - private final PlayerManager playerManager; - private final List historyEvents = new ArrayList<>(); - private final List crateCooldownEvents = new ArrayList<>(); - private boolean activatedLuckyChests = true; - private DataHandler dataHandler; - private boolean loaded = false; - private String history = ""; - private String crateCooldowns = ""; - private String virtualCrates = ""; - private Map virtualCrateData = new HashMap<>(); - - public PlayerDataManager(PlayerManager playerManager) { - this.playerManager = playerManager; - this.dataHandler = playerManager.getDataHandler(); - } - - public void loadAllInformation() { - playerManager.getInstance().getDebugUtils().log("loadAllInformation() - CALL", getClass()); - if (isSQL()) { - playerManager.getInstance().getDebugUtils().log("loadAllInformation() - isSQL", getClass()); - Runnable runnable = () -> { - String toSetUUID = "uuid='" + playerManager.getPlayer().getUniqueId() + "'"; - SQLDataHandler.getSql().insert(SQLDataHandler.TABLE, - toSetUUID + ", history='', crateCooldowns='', virtualCrates='', rewardLimits=''", true); - - try { - loadAllInformationHelper(); - } catch (Exception exc) { - ChatUtils.log("&4ERROR: &cFailed to load the SQL Database Handler"); - return; - } - - loaded = true; - }; - - SQLQueryThread.addQuery(runnable); - } else { - loadAllInformationHelper(); - loaded = true; - } - } - - public void loadAllInformationHelper() { - long curTime = System.currentTimeMillis(); - playerManager.getInstance().getDebugUtils().log("loadAllInformationHelper() - CALL (" + playerManager.getPlayer().getName() + ")", getClass()); - if (getDataHandler().hasDataValue("history")) { - setHistory(getDataHandler().get("history").toString(), false); - } - if (getDataHandler().hasDataValue("crate-cooldowns")) { - setCrateCooldowns(getDataHandler().get("crate-cooldowns").toString(), false); - } - if (getDataHandler().hasDataValue("virtual-crates")) { - playerManager.getInstance().getDebugUtils().log("loadAllInformationHelper() - contains virtual-crates value: (" + getDataHandler().get("virtual-crates").toString() + ")", getClass()); - setVirtualCrates(getDataHandler().get("virtual-crates").toString()); - } - - getPlayerManager().getInstance().getDataHandler().playAllQueuedGiveCommands(getPlayerManager().getPlayer().getUniqueId()); - - parseAll(); - - loaded = true; - if (DebugUtils.OUTPUT_PLAYER_DATA_LOAD_TIME) { - ChatUtils.log("Loaded " + getPlayerManager().getPlayer().getName() + "'s data in " + (System.currentTimeMillis() - curTime) + "ms"); - } - } - - public void parseAll() { - int historyLimit = (int) SettingsValue.PLAYER_HISTORY_LIMIT.getValue(getPlayerManager().getInstance()); - int count = 0; - String recreatedHistory = ""; - for (String unParsed : getHistory().split(",")) { - recreatedHistory = (recreatedHistory.equalsIgnoreCase("") ? unParsed : recreatedHistory + "," + unParsed); - count++; - if (count > historyLimit && historyLimit >= 0) { - setHistory(recreatedHistory, false); - break; - } - - if (!unParsed.equalsIgnoreCase("")) { - String[] split = unParsed.split(";"); - - if (Crate.exists(split[1])) { - Crate crates = Crate.getCrate(playerManager.getInstance(), split[1]); - if (CrateUtils.isCrateUsable(crates)) { - ArrayList rewards = new ArrayList<>(); - for (String s : split[2].replace("[", "").replace("]", "").split("%newReward% ")) { - Reward r = crates.getSettings().getReward().getByName(s); - - rewards.add(r); - } - - boolean success = Boolean.parseBoolean(split[3].toUpperCase()); - - getHistoryEvents().add(0, new HistoryEvent(split[0], crates, rewards, success)); - } - } - } - } - - for (String unParsed : getCrateCooldowns().split(",")) { - if (!unParsed.equalsIgnoreCase("")) { - String[] split = unParsed.split(";"); - - if (Crate.exists(split[0])) { - Crate crates = Crate.getCrate(getPlayerManager().getInstance(), split[0]); - long startTime = Long.parseLong(split[1]); - - getCrateCooldownEvents().add(new CrateCooldownEvent(crates, startTime, false)); - } - } - } - - for (String unParsed : getVirtualCrates().split(",")) { - if (!unParsed.equalsIgnoreCase("")) { - String[] split = unParsed.split(";"); - if (Crate.exists(split[0])) { - Crate crate = Crate.getCrate(getPlayerManager().getInstance(), split[0]); - try { - int crates = Integer.parseInt(split[1]); - int keys = Integer.parseInt(split[2]); - getVirtualCrateData().put(crate, new VirtualCrateData(crate, crates, keys)); - } catch (Exception exc) { - exc.printStackTrace(); - } - } - } - } - } - - public String removeStringFromList(String toRemove, String list) { - String newList = ""; - - for (String parsed : list.replace(" ", "").split(",")) { - if (!parsed.equals(toRemove)) { - newList = newList.equals("") ? parsed : newList + "," + parsed; - } - } - - return newList; - } - - public String addStringToList(String toAdd, String list) { - if (!list.equalsIgnoreCase("")) { - return toAdd + "," + list; - } - - return toAdd; - } - - public void addHistory(HistoryEvent he, String history) { - setHistory(history); - getHistoryEvents().add(he); - he.getCrate().setLastOpenedName(getPlayerManager().getPlayer().getName()); - - String rewards = he.getRewards().toString(); - - he.getCrate().setLastOpenedReward(rewards.substring(1, rewards.length() - 1)); - } - - public void setVirtualCrateCrates(Crate crate, int crates) { - playerManager.getInstance().getDebugUtils().log("setVirtualCrateCrates() - CALL (" + playerManager.getPlayer().getName() + ", " + crates + ")", getClass()); - VirtualCrateData vCD = getVCCrateData(crate); - String temp = removeStringFromList(vCD.toString(), getVirtualCrates()); - vCD.setCrates(crates); - setVirtualCrates(addStringToList(vCD.toString(), temp)); - getDataHandler().write("virtual-crates", getVirtualCrates()); - } - - public void setVirtualCrateKeys(Crate crate, int keys) { - playerManager.getInstance().getDebugUtils().log("setVirtualCrateKeys() - CALL (" + playerManager.getPlayer().getName() + ", " + crate.getName() + ", " + keys + ")", getClass()); - VirtualCrateData vCD = getVCCrateData(crate); - playerManager.getInstance().getDebugUtils().log("setVirtualCrateKeys() - Before: " + vCD.toString(), getClass()); - String temp = removeStringFromList(vCD.toString(), getVirtualCrates()); - vCD.setKeys(keys); - playerManager.getInstance().getDebugUtils().log("setVirtualCrateKeys() - After: " + vCD.toString(), getClass()); - playerManager.getInstance().getDebugUtils().log("setVirtualCrateKeys() - Result: " + addStringToList(vCD.toString(), temp), getClass()); - setVirtualCrates(addStringToList(vCD.toString(), temp)); - getDataHandler().write("virtual-crates", getVirtualCrates()); - } - - public VirtualCrateData getVCCrateData(Crate crate) { - playerManager.getInstance().getDebugUtils().log("getVCCrateData() - CALL (" + playerManager.getPlayer().getName() + ", " + crate.getName() + ")", getClass()); - if (getVirtualCrateData().containsKey(crate)) { - playerManager.getInstance().getDebugUtils().log("getVCCrateData() - already contains", getClass()); - return getVirtualCrateData().get(crate); - } else { - playerManager.getInstance().getDebugUtils().log("getVCCrateData() - doesn't contain", getClass()); - getVirtualCrateData().put(crate, new VirtualCrateData(crate, 0, 0)); - return getVCCrateData(crate); - } - } - - public void addCrateCooldowns(CrateCooldownEvent cce, String crateCooldownsToSet) { - setCrateCooldowns(crateCooldownsToSet); - getCrateCooldownEvents().add(cce); - } - - public void removeCrateCooldowns(CrateCooldownEvent cce, String crateCooldownsToSet) { - setCrateCooldowns(crateCooldownsToSet); - for (CrateCooldownEvent cce2 : getCrateCooldownEvents()) { - if (cce.matches(cce2)) { - getCrateCooldownEvents().remove(cce2); - getDataHandler().write("crate-cooldowns", crateCooldownsToSet); - break; - } - } - } - - public CrateCooldownEvent getCrateCooldownEventByCrates(Crate crates) { - for (CrateCooldownEvent cce : getCrateCooldownEvents()) { - if (cce.getCrate().getName().equalsIgnoreCase(crates.getName())) { - return cce; - } - } - return null; - } - - public boolean isSQL() { - return getDataHandler() instanceof SQLDataHandler; - } - - public void setCrateCooldowns(String crateCooldowns, boolean write) { - this.crateCooldowns = crateCooldowns; - if (write) - getDataHandler().write("crate-cooldowns", crateCooldowns); - } - - public void setHistory(String history, boolean write) { - this.history = history; - if (write) - getDataHandler().write("history", getHistory()); - } - - public String getHistory() { - return history; - } - - public void setHistory(String history) { - setHistory(history, true); - } - - public String getCrateCooldowns() { - return crateCooldowns; - } - - public void setCrateCooldowns(String crateCooldowns) { - setCrateCooldowns(crateCooldowns, true); - } - - public DataHandler getDataHandler() { - return dataHandler; - } - - public void setDataHandler(DataHandler dataHandler) { - this.dataHandler = dataHandler; - } - - public List getHistoryEvents() { - return historyEvents; - } - - public List getCrateCooldownEvents() { - return crateCooldownEvents; - } - - public PlayerManager getPlayerManager() { - return playerManager; - } - - public boolean isActivatedLuckyChests() { - return activatedLuckyChests; - } - - public void setActivatedLuckyChests(boolean activatedLuckyChests) { - this.activatedLuckyChests = activatedLuckyChests; - } - - public String getVirtualCrates() { - playerManager.getInstance().getDebugUtils().log("getVirtualCrates() - CALL (" + playerManager.getPlayer().getName() + ")", getClass()); - return virtualCrates; - } - - public void setVirtualCrates(String virtualCrates) { - playerManager.getInstance().getDebugUtils().log("setVirtualCrates() - CALL (" + playerManager.getPlayer().getName() + ")", getClass()); - this.virtualCrates = virtualCrates; - } - - public Map getVirtualCrateData() { - return virtualCrateData; - } - - public void setVirtualCrateData(Map virtualCrateData) { - this.virtualCrateData = virtualCrateData; - } - - public boolean isLoaded() { - return loaded; - } - - public void setLoaded(boolean loaded) { - this.loaded = loaded; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/players/PlayerManager.java b/src/main/java/me/ztowne13/customcrates/players/PlayerManager.java deleted file mode 100644 index 44229b0..0000000 --- a/src/main/java/me/ztowne13/customcrates/players/PlayerManager.java +++ /dev/null @@ -1,287 +0,0 @@ -package me.ztowne13.customcrates.players; - -import me.ztowne13.customcrates.SettingsValue; -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.PlacedCrate; -import me.ztowne13.customcrates.crates.options.rewards.displaymenu.custom.DisplayPage; -import me.ztowne13.customcrates.crates.types.animations.AnimationDataHolder; -import me.ztowne13.customcrates.interfaces.igc.IGCMenu; -import me.ztowne13.customcrates.players.data.*; -import me.ztowne13.customcrates.utils.ChatUtils; -import me.ztowne13.customcrates.utils.ReflectionUtilities; -import me.ztowne13.customcrates.utils.Utils; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.entity.Player; -import org.bukkit.scheduler.BukkitTask; - -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -public class PlayerManager { - private static final Map playerManagerMap = new HashMap<>(); - private final SpecializedCrates instance; - private final Player player; - private final DataHandler dataHandler; - private final PlayerDataManager playerDataManager; - - private long lastClickedCrateTime = 0; - - private PlacedCrate lastOpenedPlacedCrate = null; - private Crate openCrate = null; - private Location lastOpenCrate = null; - private AnimationDataHolder currentAnimation; - private boolean isInCratesClaimMenu = false; - private boolean inRewardMenu = false; - private DisplayPage lastPage; - // This is to allow the anti-dupe inventory reopen/close feature but prevent it when opening the next page of an inv - private long nextPageInventoryCloseGrace = 0; - private boolean deleteCrate = false; - private boolean useVirtualCrate = false; - private boolean confirming = false; - private BukkitTask confirmingTask = null; - private long cmdCooldown = 0; - private String lastCooldown = "NONE"; - private IGCMenu openMenu = null; - private IGCMenu lastOpenMenu = null; - - public PlayerManager(SpecializedCrates instance, Player player) { - this.instance = instance; - this.player = player; - this.dataHandler = getSpecifiedDataHandler(); - this.playerDataManager = new PlayerDataManager(this); - - getPlayerDataManager().setDataHandler(getDataHandler()); - getPlayerDataManager().loadAllInformation(); - getPlayerManagerMap().put(player.getUniqueId(), this); - } - - public static PlayerManager get(SpecializedCrates instance, Player player) { - instance.getDebugUtils().log("PlayerManager.get() - CALL (contains: " + getPlayerManagerMap().containsKey(player.getUniqueId()) + ")", PlayerManager.class); - return getPlayerManagerMap().containsKey(player.getUniqueId()) ? getPlayerManagerMap().get(player.getUniqueId()) : new PlayerManager(instance, player); - } - - public static void clearLoaded() { - playerManagerMap.clear(); - } - - public static Map getPlayerManagerMap() { - return playerManagerMap; - } - - public void remove(int delay) { - instance.getDebugUtils().log("PlayerManager.remove() - CALL", getClass()); - - if (isInCrateAnimation()) { - getCurrentAnimation().setFastTrack(true, true); - } - - Bukkit.getScheduler().scheduleSyncDelayedTask(getInstance(), new Runnable() { - @Override - public void run() { - getPlayerManagerMap().remove(getPlayer().getUniqueId()); - instance.getDebugUtils().log("PlayerManager.remove() - Removed", getClass()); - } - }, delay); - - ReflectionUtilities.getCachedHandles().remove(getPlayer()); - } - - public DataHandler getSpecifiedDataHandler() { - try { - StorageType st = StorageType.valueOf( - ChatUtils.stripFromWhitespace(SettingsValue.STORE_DATA.getValue(getInstance()).toString().toUpperCase())); - switch (st) { - case MYSQL: - Utils.addToInfoLog(instance, "Storage Type", "MYSQL"); - return new SQLDataHandler(this); - case FLATFILE: - Utils.addToInfoLog(instance, "Storage Type", "FLATFILE"); - return new FlatFileDataHandler(this); - case PLAYERFILES: - Utils.addToInfoLog(instance, "Storage Type", "PLAYERFILES"); - return new IndividualFileDataHandler(this); - default: - ChatUtils.log(new String[]{"store-data value in the config.YML is not a valid storage type.", - " It must be: MYSQL, FLATFILE, PLAYERFILES"}); - Utils.addToInfoLog(instance, "StorageType", "FLATFILE"); - return new FlatFileDataHandler(this); - } - } catch (Exception exc) { - exc.printStackTrace(); - ChatUtils.log(new String[]{"store-data value in the config.YML is not a valid storage type.", - " It must be: MYSQL, FLATFILE, PLAYERFILES"}); - } - return null; - } - - public boolean isConfirming() { - return confirming; - } - - public void setConfirming(final boolean confirming) { - this.confirming = confirming; - if (confirming) { - confirmingTask = Bukkit.getScheduler().runTaskLater(instance, () -> setConfirming(false), 20L * (int) SettingsValue.CONFIRM_TIMEOUT.getValue(instance)); - } else { - if (confirmingTask != null) { - confirmingTask.cancel(); - confirmingTask = null; - } - } - } - - public boolean isInCrate() { - return openCrate != null; - } - - public boolean isDeleteCrate() { - return deleteCrate; - } - - public void setDeleteCrate(boolean b) { - this.deleteCrate = b; - } - - public void openCrate(Crate crate) { - openCrate = crate; - } - - public void closeCrate() { - openCrate = null; - useVirtualCrate = false; - } - - public Crate getOpenCrate() { - return openCrate; - } - - public boolean isInRewardMenu() { - return inRewardMenu; - } - - public void setInRewardMenu(boolean inRewardMenu) { - this.inRewardMenu = inRewardMenu; - } - - public Player getPlayer() { - return player; - } - - public SpecializedCrates getInstance() { - return instance; - } - - public DataHandler getDataHandler() { - return dataHandler; - } - - public PlayerDataManager getPlayerDataManager() { - return playerDataManager; - } - - public long getCmdCooldown() { - return cmdCooldown; - } - - public void setCmdCooldown(long cmdCooldown) { - this.cmdCooldown = cmdCooldown; - } - - public String getLastCooldown() { - return lastCooldown; - } - - public void setLastCooldown(String lastCooldown) { - this.lastCooldown = lastCooldown; - } - - public IGCMenu getOpenMenu() { - return openMenu; - } - - public void setOpenMenu(IGCMenu openMenu) { - this.openMenu = openMenu; - if (openMenu != null) { - this.lastOpenMenu = openMenu; - } - } - - public boolean isInOpenMenu() { - return this.openMenu != null; - } - - public IGCMenu getLastOpenMenu() { - return lastOpenMenu; - } - - public Location getLastOpenCrate() { - return lastOpenCrate; - } - - public void setLastOpenCrate(Location lastOpenCrate) { - this.lastOpenCrate = lastOpenCrate; - } - - public boolean isUseVirtualCrate() { - return useVirtualCrate; - } - - public void setUseVirtualCrate(boolean useVirtualCrate) { - this.useVirtualCrate = useVirtualCrate; - } - - public PlacedCrate getLastOpenedPlacedCrate() { - return lastOpenedPlacedCrate; - } - - public void setLastOpenedPlacedCrate(PlacedCrate lastOpenedPlacedCrate) { - this.lastOpenedPlacedCrate = lastOpenedPlacedCrate; - } - - public DisplayPage getLastPage() { - return lastPage; - } - - public void setLastPage(DisplayPage lastPage) { - this.lastPage = lastPage; - } - - public AnimationDataHolder getCurrentAnimation() { - return currentAnimation; - } - - public void setCurrentAnimation(AnimationDataHolder currentAnimation) { - this.currentAnimation = currentAnimation; - } - - public boolean isInCrateAnimation() { - return currentAnimation != null; - } - - public long getLastClickedCrateTime() { - return lastClickedCrateTime; - } - - public void setLastClickedCrateTime(long lastClickedCrateTime) { - this.lastClickedCrateTime = lastClickedCrateTime; - } - - public long getNextPageInventoryCloseGrace() { - return nextPageInventoryCloseGrace; - } - - public void setNextPageInventoryCloseGrace(long nextPageInventoryCloseGrace) { - this.nextPageInventoryCloseGrace = nextPageInventoryCloseGrace; - } - - public boolean isInCratesClaimMenu() { - return isInCratesClaimMenu; - } - - public void setInCratesClaimMenu(boolean inCratesClaimMenu) { - isInCratesClaimMenu = inCratesClaimMenu; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/players/data/DataHandler.java b/src/main/java/me/ztowne13/customcrates/players/data/DataHandler.java deleted file mode 100644 index fe4ed98..0000000 --- a/src/main/java/me/ztowne13/customcrates/players/data/DataHandler.java +++ /dev/null @@ -1,35 +0,0 @@ -package me.ztowne13.customcrates.players.data; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.players.PlayerManager; - -public abstract class DataHandler { - protected final SpecializedCrates instance; - - protected final PlayerManager playerManager; - protected final String uuid; - - public DataHandler(PlayerManager playerManager) { - this.instance = playerManager.getInstance(); - this.playerManager = playerManager; - this.uuid = playerManager.getPlayer().getUniqueId().toString(); - } - - public abstract boolean load(); - - public abstract Object get(String value); - - public abstract void write(String value, String toWrite); - - public abstract boolean hasDataPath(); - - public abstract boolean hasDataValue(String value); - - public PlayerManager getPlayerManager() { - return playerManager; - } - - public String getUuid() { - return uuid; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/players/data/FlatFileDataHandler.java b/src/main/java/me/ztowne13/customcrates/players/data/FlatFileDataHandler.java deleted file mode 100644 index 3fb2b89..0000000 --- a/src/main/java/me/ztowne13/customcrates/players/data/FlatFileDataHandler.java +++ /dev/null @@ -1,69 +0,0 @@ -package me.ztowne13.customcrates.players.data; - -import me.ztowne13.customcrates.interfaces.files.FileHandler; -import me.ztowne13.customcrates.players.PlayerManager; -import org.bukkit.configuration.file.FileConfiguration; - -public class FlatFileDataHandler extends DataHandler { - private static FileHandler fileHandler; - private static FileConfiguration fileConfiguration; - private static boolean toSave = false; - - public FlatFileDataHandler(PlayerManager playerManager) { - super(playerManager); - instance.getDebugUtils().log("Loading flat file data handler for " + playerManager.getPlayer().getName()); - if (fileHandler == null) { - fileHandler = new FileHandler(instance, "PlayerData.db", false, false); - fileConfiguration = getFileHandler().get(); - } - } - - public static FileHandler getFileHandler() { - return fileHandler; - } - - public static FileConfiguration getFileConfiguration() { - return fileConfiguration; - } - - public static boolean isToSave() { - return toSave; - } - - public static void resetToSave() { - toSave = false; - } - - @Override - public boolean load() { - return false; - } - - @Override - public Object get(String value) { - instance.getDebugUtils().log("FlatFileDataHandler.get() - CALL", getClass()); - return getFileConfiguration().get(toPath(value)); - } - - @Override - public void write(String value, String toWrite) { - instance.getDebugUtils().log("FlatFileDataHandler.write() - CALL", getClass()); - getFileConfiguration().set(toPath(value), toWrite); - - toSave = true; - } - - @Override - public boolean hasDataPath() { - return getFileConfiguration().contains(getUuid()); - } - - @Override - public boolean hasDataValue(String value) { - return getFileConfiguration().contains(toPath(value)); - } - - public String toPath(String value) { - return getUuid() + "." + value; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/players/data/IndividualFileDataHandler.java b/src/main/java/me/ztowne13/customcrates/players/data/IndividualFileDataHandler.java deleted file mode 100644 index 3bbaae3..0000000 --- a/src/main/java/me/ztowne13/customcrates/players/data/IndividualFileDataHandler.java +++ /dev/null @@ -1,64 +0,0 @@ -package me.ztowne13.customcrates.players.data; - -import me.ztowne13.customcrates.interfaces.files.FileHandler; -import me.ztowne13.customcrates.players.PlayerManager; -import org.bukkit.configuration.file.FileConfiguration; - -import java.util.ArrayList; -import java.util.List; - -public class IndividualFileDataHandler extends DataHandler { - private static final List toSave = new ArrayList<>(); - - private final FileHandler fileHandler; - private final FileConfiguration fileConfiguration; - - public IndividualFileDataHandler(PlayerManager playerManager) { - super(playerManager); - instance.getDebugUtils().log("Loading individual file data handler for " + playerManager.getPlayer().getName()); - this.fileHandler = new FileHandler(playerManager.getInstance(), playerManager.getPlayer().getUniqueId().toString() + ".stats", "/PlayerStats/", false, false, - false); - this.fileConfiguration = getFileHandler().get(); - instance.getDebugUtils().log(fileHandler.getDataFile().getAbsolutePath()); - } - - public static List getToSave() { - return toSave; - } - - @Override - public boolean load() { - return false; - } - - @Override - public Object get(String value) { - return getFileConfiguration().get(value); - } - - @Override - public void write(String value, String toWrite) { - getFileConfiguration().set(value, toWrite); - - if (!toSave.contains(this)) - toSave.add(this); - } - - @Override - public boolean hasDataValue(String value) { - return getFileConfiguration().contains(value); - } - - @Override - public boolean hasDataPath() { - return true; - } - - public FileHandler getFileHandler() { - return fileHandler; - } - - public FileConfiguration getFileConfiguration() { - return fileConfiguration; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/players/data/SQLDataHandler.java b/src/main/java/me/ztowne13/customcrates/players/data/SQLDataHandler.java deleted file mode 100644 index 35a9c7a..0000000 --- a/src/main/java/me/ztowne13/customcrates/players/data/SQLDataHandler.java +++ /dev/null @@ -1,102 +0,0 @@ -package me.ztowne13.customcrates.players.data; - -import me.ztowne13.customcrates.interfaces.files.FileHandler; -import me.ztowne13.customcrates.interfaces.sql.SQL; -import me.ztowne13.customcrates.interfaces.sql.SQLQueryThread; -import me.ztowne13.customcrates.players.PlayerManager; -import org.bukkit.Bukkit; -import org.bukkit.configuration.file.FileConfiguration; - -public class SQLDataHandler extends DataHandler { - public static final String TABLE = "scPlayerStats"; - private static SQL sql; - private static boolean loaded = false; - - public SQLDataHandler(PlayerManager playerManager) { - super(playerManager); - instance.getDebugUtils().log("SQLDataHandler() - CALL", getClass()); - load(); - } - - public static SQL getSql() { - return sql; - } - - public static boolean isLoaded() { - return loaded; - } - - @Override - public boolean load() { - if (!loaded) { - Bukkit.getScheduler().runTaskLaterAsynchronously(instance, new Runnable() { - @Override - public void run() { - instance.getDebugUtils().log("load() - CALL (Note: This is run synchronous not asynchronous)", getClass()); - long curTime = System.currentTimeMillis(); - - FileHandler sqlYml = instance.getSqlFile(); - FileConfiguration fc = sqlYml.get(); - - String dbName = fc.getString("database.name"); - String dbIp = fc.getString("database.ip"); - String dbPort = fc.getString("database.port"); - String dbUsername = fc.getString("database.username"); - String dbPassword = fc.getString("database.password"); - - instance.getDebugUtils().log("load() - Opening connection and creating query thread.", getClass()); - sql = new SQL(instance, dbIp, dbName, dbPort, dbUsername, dbPassword); - new SQLQueryThread(sql); - - instance.getDebugUtils().log("load() - Completed creating thread and opening connection in " + - (System.currentTimeMillis() - curTime) + "ms.", getClass()); - - instance.getDebugUtils().log("load() - Creating table & setting unique if it doesn't exist...", getClass()); - long createTime = System.currentTimeMillis(); - - sql.create(TABLE, - "uuid varchar(36), history longtext, crateCooldowns mediumtext, virtualCrates mediumtext, rewardLimits mediumtext", - true); - - instance.getDebugUtils().log("load() - Completed creating table & setting unique in " + - (System.currentTimeMillis() - createTime) + "ms.", - getClass()); - instance.getDebugUtils().log("load() - Completed in " + (System.currentTimeMillis() - curTime) + "ms.", getClass()); - loaded = true; - } - }, 0); - } - return false; - } - - @Override - public Object get(String value) { - value = formatValue(value); - return sql.get(TABLE, "uuid", playerManager.getPlayer().getUniqueId().toString(), value); - } - - @Override - public void write(String value, String toWrite) { - value = formatValue(value); - sql.write(TABLE, "uuid", playerManager.getPlayer().getUniqueId().toString(), value, toWrite); - } - - public String formatValue(String value) { - if (value.equalsIgnoreCase("crate-cooldowns")) - return "crateCooldowns"; - else if (value.equalsIgnoreCase("virtual-crates")) - return "virtualCrates"; - return value; - } - - @Override - public boolean hasDataValue(String value) { - return true; - } - - @Override - public boolean hasDataPath() { - return true; - } - -} diff --git a/src/main/java/me/ztowne13/customcrates/players/data/StorageType.java b/src/main/java/me/ztowne13/customcrates/players/data/StorageType.java deleted file mode 100644 index 9c6698f..0000000 --- a/src/main/java/me/ztowne13/customcrates/players/data/StorageType.java +++ /dev/null @@ -1,19 +0,0 @@ -package me.ztowne13.customcrates.players.data; - -public enum StorageType { - MYSQL(true), - - FLATFILE(true), - - PLAYERFILES(true); - - private final boolean enabled; - - StorageType(boolean enabled) { - this.enabled = enabled; - } - - public boolean isEnabled() { - return enabled; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/players/data/VirtualCrateData.java b/src/main/java/me/ztowne13/customcrates/players/data/VirtualCrateData.java deleted file mode 100644 index 7714809..0000000 --- a/src/main/java/me/ztowne13/customcrates/players/data/VirtualCrateData.java +++ /dev/null @@ -1,42 +0,0 @@ -package me.ztowne13.customcrates.players.data; - -import me.ztowne13.customcrates.crates.Crate; - -/** - * Created by ztowne13 on 7/24/16. - */ -public class VirtualCrateData { - private final Crate crate; - private int crates; - private int keys; - - public VirtualCrateData(Crate crate, int crates, int keys) { - this.crate = crate; - this.crates = crates; - this.keys = keys; - } - - public String toString() { - return crate.getName() + ";" + crates + ";" + keys; - } - - public Crate getCrate() { - return crate; - } - - public int getCrates() { - return crates; - } - - public void setCrates(int crates) { - this.crates = crates; - } - - public int getKeys() { - return keys; - } - - public void setKeys(int keys) { - this.keys = keys; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/players/data/events/CrateCooldownEvent.java b/src/main/java/me/ztowne13/customcrates/players/data/events/CrateCooldownEvent.java deleted file mode 100644 index ee4f1bf..0000000 --- a/src/main/java/me/ztowne13/customcrates/players/data/events/CrateCooldownEvent.java +++ /dev/null @@ -1,105 +0,0 @@ -package me.ztowne13.customcrates.players.data.events; - -import me.ztowne13.customcrates.Messages; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.players.PlayerDataManager; -import me.ztowne13.customcrates.utils.Utils; - -/** - * Created by ztowne13 on 8/5/15. - */ -public class CrateCooldownEvent extends DataEvent { - private final Crate crate; - private final long cooldownTime; - private final boolean start; - private long startTime; - - public CrateCooldownEvent(Crate crate, long startTime, boolean start) { - super(crate.getInstance()); - - this.crate = crate; - this.startTime = startTime; - this.cooldownTime = crate.getSettings().getCooldown() * 1000L; - this.start = start; - } - - @Override - public String getFormatted() { - return getCrate().getName() + ";" + getStartTime(); - } - - @Override - public void addTo(PlayerDataManager playerDataManager) { - if (getCooldownTime() > 0) { - if (isStart()) { - long seconds = getCooldownTime() / 1000; - String[] values = Utils.convertSecondToHHMMString(seconds); - - Messages.COOLDOWN_START.msgSpecified(instance, playerDataManager.getDataHandler().getPlayerManager().getPlayer(), - new String[]{"%crate%", "%days%", "%hours%", "%minutes%", "%seconds%"}, - new String[]{getCrate().getDisplayName(), values[0], values[1], values[2], values[3]}); - } - - playerDataManager.addCrateCooldowns(this, playerDataManager.addStringToList(getFormatted(), playerDataManager.getCrateCooldowns())); - } - } - - public void tickSecond(PlayerDataManager playerDataManager) { - if (isCooldownOverAsBoolean()) { - end(playerDataManager); - } - } - - public boolean isCooldownOverAsBoolean() { - return isCooldownOver() == -1; - } - - public long isCooldownOver() { - return getStartTime() + getCooldownTime() < System.currentTimeMillis() ? -1 : - (getStartTime() + getCooldownTime() - System.currentTimeMillis()) / 1000L; - } - - public void end(PlayerDataManager playerDataManager) { - long seconds = getCooldownTime() / 1000; - String[] values = Utils.convertSecondToHHMMString(seconds); - Messages.COOLDOWN_END.msgSpecified(getInstance(), playerDataManager.getDataHandler().getPlayerManager().getPlayer(), - new String[]{"%crate%", "%days%", "%hours%", "%minutes%", "%seconds%"}, - new String[]{getCrate().getDisplayName(), values[0], values[1], values[2], values[3]}); - playerDataManager.removeCrateCooldowns(this, playerDataManager.removeStringFromList(getFormatted(), playerDataManager.getCrateCooldowns())); - } - - public boolean matches(CrateCooldownEvent crateCooldownEvent) { - return getCrate().getName().equalsIgnoreCase(crateCooldownEvent.getCrate().getName()) && getStartTime() == crateCooldownEvent.getStartTime() && - getCooldownTime() == crateCooldownEvent.getCooldownTime(); - } - - public void playFailure(PlayerDataManager playerDataManager) { - crate.getSettings().getCrateAnimation().playFailToOpen(playerDataManager.getPlayerManager().getPlayer(), false, true); - long seconds = isCooldownOver(); - String[] values = Utils.convertSecondToHHMMString(seconds); - playerDataManager.getPlayerManager().getPlayer().sendMessage(Messages.CRATE_ON_COOLDOWN.getFromConf(instance).replace("%crate%", crate.getDisplayName()) - .replace("%days%", values[0]).replace("%hours%", values[1]).replace("%minutes%", values[2]) - .replace("%seconds%", values[3])); - - } - - public Crate getCrate() { - return crate; - } - - public long getStartTime() { - return startTime; - } - - public void setStartTime(long startTime) { - this.startTime = startTime; - } - - public long getCooldownTime() { - return cooldownTime; - } - - public boolean isStart() { - return start; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/players/data/events/DataEvent.java b/src/main/java/me/ztowne13/customcrates/players/data/events/DataEvent.java deleted file mode 100644 index d2b81e9..0000000 --- a/src/main/java/me/ztowne13/customcrates/players/data/events/DataEvent.java +++ /dev/null @@ -1,23 +0,0 @@ -package me.ztowne13.customcrates.players.data.events; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.players.PlayerDataManager; - -/** - * Created by ztowne13 on 8/5/15. - */ -public abstract class DataEvent { - protected final SpecializedCrates instance; - - public DataEvent(SpecializedCrates instance) { - this.instance = instance; - } - - public abstract void addTo(PlayerDataManager playerDataManager); - - public abstract String getFormatted(); - - public SpecializedCrates getInstance() { - return instance; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/players/data/events/HistoryEvent.java b/src/main/java/me/ztowne13/customcrates/players/data/events/HistoryEvent.java deleted file mode 100644 index 239301e..0000000 --- a/src/main/java/me/ztowne13/customcrates/players/data/events/HistoryEvent.java +++ /dev/null @@ -1,103 +0,0 @@ -package me.ztowne13.customcrates.players.data.events; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.options.rewards.Reward; -import me.ztowne13.customcrates.players.PlayerDataManager; -import me.ztowne13.customcrates.players.PlayerManager; -import me.ztowne13.customcrates.utils.ChatUtils; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** - * Created by ztowne13 on 8/5/15. - */ -public class HistoryEvent extends DataEvent { - private final Crate crate; - private final List rewards; - private boolean success; - private String currentTime; - - public HistoryEvent(String currentTime, Crate crate, List rewards, boolean success) { - super(crate.getInstance()); - this.crate = crate; - this.rewards = rewards; - this.success = success; - this.currentTime = currentTime; - } - - public static void listFor(SpecializedCrates instance, CommandSender sender, Player toDisplay, int amount) { - ChatUtils.msg(sender, "&6TIME &7- &9CRATE &7- &cREWARD\n\n" + - "&aOldest Entries\n" + - " to\n" + - "&aNewest Entries\n\n"); - - ArrayList hevents = new ArrayList<>(PlayerManager.get(instance, toDisplay).getPlayerDataManager().getHistoryEvents()); - - Collections.reverse(hevents); - - amount = Math.min(amount, hevents.size()); - ChatUtils.msg(sender, "&eHistory for " + toDisplay.getName() + " &7(Showing " + amount + "/" + hevents.size() + ")"); - - for (int i = amount - 1; i >= 0; i--) { - HistoryEvent he = hevents.get(i); - String[] split = he.getFormatted().split(";"); - String rewardName = split[2].replace("%newReward%", ","); - ChatUtils - .msg(sender, "&6" + he.getCurrentTime() + " &7- &9" + he.getCrate().getName() + " &7- &c" + rewardName); - } - } - - @Override - public void addTo(PlayerDataManager playerDataManager) { - playerDataManager.addHistory(this, playerDataManager.addStringToList(getFormatted(), playerDataManager.getHistory())); - } - - @Override - public String getFormatted() { - String rewardName = getRewards() == null || getRewards().isEmpty() ? "none" : - getRewards().toString().replace(",", "%newReward%"); - return getCurrentTime() + ";" + getCrate().getName() + ";" + rewardName + ";" + isSuccess(); - } - - public boolean matches(HistoryEvent historyEvent) { - boolean matches = - getCrate().getName().equalsIgnoreCase(historyEvent.getCrate().getName()) && isSuccess() == historyEvent.isSuccess() && - getCurrentTime().equals(historyEvent.getCurrentTime()); - for (int i = 0; i < getRewards().size(); i++) { - if (!getRewards().get(i).getDisplayName(false).equalsIgnoreCase(historyEvent.getRewards().get(i).getDisplayName(false))) { - matches = false; - break; - } - } - return matches; - } - - public Crate getCrate() { - return crate; - } - - public List getRewards() { - return rewards; - } - - public boolean isSuccess() { - return success; - } - - public void setSuccess(boolean success) { - this.success = success; - } - - public String getCurrentTime() { - return currentTime; - } - - public void setCurrentTime(String currentTime) { - this.currentTime = currentTime; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/utils/ChatUtils.java b/src/main/java/me/ztowne13/customcrates/utils/ChatUtils.java deleted file mode 100644 index d9a6d12..0000000 --- a/src/main/java/me/ztowne13/customcrates/utils/ChatUtils.java +++ /dev/null @@ -1,131 +0,0 @@ -package me.ztowne13.customcrates.utils; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.interfaces.externalhooks.PlaceHolderAPIHandler; -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.List; - -/** - * Created by ztowne13 on 3/3/16. - */ -public class ChatUtils { - - private ChatUtils() { - // EMPTY - } - - public static void log(String[] args) { - Bukkit.getLogger().info("-----------------------------------"); - for (String arg : args) { - Bukkit.getServer().getConsoleSender().sendMessage(ChatUtils.toChatColor(arg)); - } - Bukkit.getLogger().info("-----------------------------------"); - } - - public static void log(String s) { - Bukkit.getServer().getConsoleSender().sendMessage(ChatUtils.toChatColor("&7" + s)); - } - - public static void logFailLoad(String crate, String failLoad, String failLoadValue) { - log(new String[]{"Failed to load " + failLoad + " for crate " + crate + ": " + failLoadValue}); - } - - public static String formatAndColor(SpecializedCrates specializedCrates, Player player, String str) { - if (specializedCrates.isUsingPlaceholderAPI()) { - str = PlaceHolderAPIHandler.setPlaceHolders(player, str); - } - - return toChatColor(str); - } - - public static void msg(Player p, String s) { - p.sendMessage(toChatColor(s)); - } - - public static void msg(CommandSender sender, String s) { - sender.sendMessage(toChatColor(s)); - } - - public static void msgError(Player p, String s) { - msg(p, "&4&lERROR! &c" + s); - } - - public static void msgSuccess(Player p, String s) { - msg(p, "&2&lSUCCESS! &a" + s); - } - - public static void msgInfo(Player p, String s) { - msg(p, "&6&lInfo &e" + s); - } - - public static void msgHey(Player p, String s) { - msg(p, "&6&lHey! &e" + s); - } - - public static String toChatColor(String s) { - s = s.replace("", "§"); - return ChatColor.translateAlternateColorCodes('&', s); - } - - public static String fromChatColor(String s) { - return s.replace("§", "&"); - } - - public static String stripQuotes(String s) { - while (s.startsWith("'") || s.startsWith("\"")) - s = s.substring(1); - - while (s.endsWith("'") || s.endsWith("\"")) - s = s.substring(0, s.length() - 1); - - return s; - } - - public static String removeColor(String s) { - s = ChatColor.stripColor(s); - StringBuilder newString = new StringBuilder(); - int i = 0; - while (i < s.length()) { - if (s.charAt(i) != '&') { - newString.append(s.charAt(i)); - } - i++; - } - return newString.toString(); - } - - public static String stripFromWhitespace(String s) { - return s.replaceAll("\\s+", ""); - } - - public static List removeColorFrom(List list) { - ArrayList newList = new ArrayList<>(); - for (Object s : list) { - newList.add(ChatColor.stripColor(s.toString())); - } - return newList; - } - - public static List fromColor(List list) { - ArrayList newList = new ArrayList<>(); - for (Object s : list) { - newList.add(s.toString().replace("§", "&")); - } - return newList; - } - - public static String lastChatColor(String s) { - String original = fromChatColor(s); - int index = original.lastIndexOf('&'); - if (index < 0 || index == original.length() - 1) { - return toChatColor("&f"); - } else { - return toChatColor(original.substring(index, index + 2)); - } - } -} diff --git a/src/main/java/me/ztowne13/customcrates/utils/CrateUtils.java b/src/main/java/me/ztowne13/customcrates/utils/CrateUtils.java deleted file mode 100644 index f98604d..0000000 --- a/src/main/java/me/ztowne13/customcrates/utils/CrateUtils.java +++ /dev/null @@ -1,41 +0,0 @@ -package me.ztowne13.customcrates.utils; - -import me.ztowne13.customcrates.crates.Crate; -import me.ztowne13.customcrates.crates.PlacedCrate; -import org.bukkit.inventory.ItemStack; - -public class CrateUtils { - private CrateUtils() { - // EMPTY - } - - public static Crate searchByKey(ItemStack stack) { - for (Crate crate : Crate.getLoadedCrates().values()) { - if (isCrateUsable(crate) && crate.getSettings().getKeyItemHandler().keyMatchesToStack(stack, false)) { - return crate; - } - } - return null; - } - - public static Crate searchByCrate(ItemStack stack) { - return searchByCrate(stack, false); - } - - public static Crate searchByCrate(ItemStack stack, boolean includeDisabled) { - for (Crate crate : Crate.getLoadedCrates().values()) { - if ((isCrateUsable(crate) || includeDisabled) && crate.getSettings().getCrateItemHandler().crateMatchesToStack(stack)) { - return crate; - } - } - return null; - } - - public static boolean isCrateUsable(Crate crate) { - return crate != null && crate.isEnabled() && !crate.isDisabledByError(); - } - - public static boolean isCrateUsable(PlacedCrate placedCrate) { - return placedCrate.isCratesEnabled() && placedCrate.getCrate() != null && placedCrate.getCrate().isEnabled() && !placedCrate.getCrate().isDisabledByError(); - } -} \ No newline at end of file diff --git a/src/main/java/me/ztowne13/customcrates/utils/DebugUtils.java b/src/main/java/me/ztowne13/customcrates/utils/DebugUtils.java deleted file mode 100644 index 13c1f92..0000000 --- a/src/main/java/me/ztowne13/customcrates/utils/DebugUtils.java +++ /dev/null @@ -1,78 +0,0 @@ -package me.ztowne13.customcrates.utils; - -import me.ztowne13.customcrates.SpecializedCrates; -import org.bukkit.Bukkit; - -public class DebugUtils { - public static final boolean ENABLE_CACHING = true; - public static final boolean LOG_CACHED_INFO = false; - public static final boolean OUTPUT_AVERAGE_TICK = false; - - public static final boolean OUTPUT_FILE_SAVE_TIME = false; - public static final boolean OUTPUT_PLAYER_DATA_LOAD_TIME = false; - - public static final boolean OUTPUT_AVERAGE_ANIMATION_TICK = false; - private static final boolean FORCE_DEBUG = false; - - private final SpecializedCrates instance; - - private final String[] sort = new String[] - { - "" - }; - - public DebugUtils(SpecializedCrates instance) { - this.instance = instance; - } - - public void log(String s) { - boolean debug = FORCE_DEBUG || Boolean.parseBoolean(instance.getSettings().getConfigValues().get("debug").toString()); - if (debug) { - Bukkit.getLogger().info(() -> "[DEBUG] " + s); - } - } - - public void log(String s, Class clazz) { - log(s, clazz, false); - } - - public void log(String s, Class clazz, boolean dumpStack) { - log(s, clazz, dumpStack, false); - } - - public void log(String s, Class clazz, boolean dumpStack, boolean toChat) { - try { - boolean debug = FORCE_DEBUG || Boolean.parseBoolean(instance.getSettings().getConfigValues().get("debug").toString()); - - String msg = clazz.getName() + "." + s; - - boolean found = sort.length == 0; - for (String toSort : sort) { - if (msg.startsWith(toSort)) { - found = true; - break; - } - } - - if (found) { - if (debug) { - if (toChat) - Bukkit.broadcastMessage("[DEBUG] " + msg); - else - Bukkit.getLogger().info(() -> "[DEBUG] " + msg); - } - if (dumpStack) { - dumpStack(); - } - } - } catch (Exception exc) { - // IGNORED - } - } - - public void dumpStack() { - boolean debug = FORCE_DEBUG || Boolean.parseBoolean(instance.getSettings().getConfigValues().get("debug").toString()); - if (debug) - Thread.dumpStack(); - } -} diff --git a/src/main/java/me/ztowne13/customcrates/utils/LocationUtils.java b/src/main/java/me/ztowne13/customcrates/utils/LocationUtils.java deleted file mode 100644 index 6a87501..0000000 --- a/src/main/java/me/ztowne13/customcrates/utils/LocationUtils.java +++ /dev/null @@ -1,35 +0,0 @@ -package me.ztowne13.customcrates.utils; - -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; - -public class LocationUtils { - private LocationUtils() { - // EMPTY - } - - public static String locToString(Location l) { - return l.getWorld().getName() + ";" + l.getBlockX() + ";" + l.getBlockY() + ";" + l.getBlockZ(); - } - - public static Location stringToLoc(String s) { - String[] split = s.split(";"); - return new Location(Bukkit.getWorld(split[0]), Integer.parseInt(split[1]), Integer.parseInt(split[2]), - Integer.parseInt(split[3])); - } - - public static Location getLocationCentered(Location l) { - return new Location(l.getWorld(), l.getX() + .5, l.getY() + 1.5, l.getZ() + .5); - } - - public static void removeDubBlocks(Location l) { - if (l.getBlock() != null) - l.getBlock().setType(Material.AIR); - Location l2 = l.clone(); - l2.setY(l2.getY() + 1); - - if (l2.getBlock() != null) - l2.getBlock().setType(Material.AIR); - } -} diff --git a/src/main/java/me/ztowne13/customcrates/utils/NPCUtils.java b/src/main/java/me/ztowne13/customcrates/utils/NPCUtils.java deleted file mode 100644 index df50096..0000000 --- a/src/main/java/me/ztowne13/customcrates/utils/NPCUtils.java +++ /dev/null @@ -1,122 +0,0 @@ -package me.ztowne13.customcrates.utils; - -import me.ztowne13.customcrates.SpecializedCrates; -import me.ztowne13.customcrates.crates.PlacedCrate; -import me.ztowne13.customcrates.crates.types.display.npcs.Citizens2NPCPlaceHolder; -import me.ztowne13.customcrates.crates.types.display.npcs.IdentifierTrait; -import me.ztowne13.customcrates.crates.types.display.npcs.MobPlaceholder; -import net.citizensnpcs.api.CitizensAPI; -import net.citizensnpcs.api.npc.NPC; -import net.citizensnpcs.api.npc.NPCRegistry; -import net.citizensnpcs.api.trait.TraitInfo; -import net.citizensnpcs.trait.LookClose; -import org.bukkit.Bukkit; -import org.bukkit.Location; - -import java.util.Iterator; - -/** - * Created by ztowne13 on 2/26/16. - */ -public class NPCUtils { - private static final boolean DISABLED_MOB_RELOAD = true; - private static boolean failedLoad = false; - - private NPCUtils() { - // EMPTY - } - - public static void checkUncheckMobs(boolean b) { - if (DISABLED_MOB_RELOAD || !isCitizensInstalled()) - return; - - for (NPCRegistry npcRegistry : CitizensAPI.getNPCRegistries()) { - Iterator npcIterator = npcRegistry.iterator(); - - for (NPC npc : Utils.iteratorToList(npcIterator)) { - if (npc.hasTrait(IdentifierTrait.class) && npc.getTrait(IdentifierTrait.class).isCrate()) { - if (!b) { - b = true; - for (NPC npck : MobPlaceholder.getNpcMap().values()) { - if (npck.getUniqueId().equals(npc.getUniqueId())) { - b = false; - } - } - - for (NPC npck : Citizens2NPCPlaceHolder.getNpcMap().values()) { - if (npck.getUniqueId().equals(npc.getUniqueId())) { - b = false; - } - } - } - - if (b) { - npc.destroy(); - } - } - } - } - } - - public static void checkUncheckMobs(SpecializedCrates instance, final boolean bVal, long l) { - Bukkit.getScheduler().scheduleSyncDelayedTask(instance, () -> NPCUtils.checkUncheckMobs(bVal), l); - } - - public static NPC getNpcForCrate(PlacedCrate placedCrate) { - if (!isCitizensInstalled()) { - return null; - } - - for (NPCRegistry npcRegistry : CitizensAPI.getNPCRegistries()) { - Iterator npcIterator = npcRegistry.iterator(); - - for (NPC npc : Utils.iteratorToList(npcIterator)) { - if (!npc.isSpawned() || !npc.getName().equalsIgnoreCase("Specialized Crate - Crate")) - continue; - - //if (npc.hasTrait(IdentifierTrait.class) && npc.getTrait(IdentifierTrait.class).isCrate()) - { - Location storedLoc = npc.getStoredLocation(); - Location crateLoc = LocationUtils.getLocationCentered(placedCrate.getLocation()); - if (Math.abs(storedLoc.getX() - crateLoc.getX()) < .3 && - Math.abs(storedLoc.getY() - crateLoc.getY()) < 2 && - Math.abs(storedLoc.getZ() - crateLoc.getZ()) < .3 && - storedLoc.getWorld() == crateLoc.getWorld()) { - return npc; - } - } - - } - } - return null; - } - - public static boolean npcExists(PlacedCrate placedCrate) { - return getNpcForCrate(placedCrate) != null; - } - - public static void applyDefaultInfo(NPC npc) { - npc.getTrait(LookClose.class).toggle(); - - npc.data().remove(NPC.AMBIENT_SOUND_METADATA); - npc.data().set(NPC.SILENT_METADATA, true); - npc.data().set(NPC.DEFAULT_PROTECTED_METADATA, true); - - npc.data().setPersistent(NPC.NAMEPLATE_VISIBLE_METADATA, false); - } - - public static boolean isCitizensInstalled() { - return Utils.isPLInstalled("Citizens") && !failedLoad; - } - - public static void load(boolean firstEnable) { - try { - if (firstEnable && isCitizensInstalled()) { - CitizensAPI.getTraitFactory().registerTrait(TraitInfo.create(IdentifierTrait.class).withName("isCrate")); - } - } catch (Exception exc) { - failedLoad = true; - ChatUtils.log("ERROR: FAILED TO ESTABLISH LINK WITH CITIZENS, DISABLING CITIZENS FEATURES"); - } - } -} diff --git a/src/main/java/me/ztowne13/customcrates/utils/ReflectionUtilities.java b/src/main/java/me/ztowne13/customcrates/utils/ReflectionUtilities.java deleted file mode 100644 index 8957060..0000000 --- a/src/main/java/me/ztowne13/customcrates/utils/ReflectionUtilities.java +++ /dev/null @@ -1,155 +0,0 @@ -package me.ztowne13.customcrates.utils; - -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.HashMap; -import java.util.Map; - -public class ReflectionUtilities { - - private static final Map cachedHandles = new HashMap<>(); - private static final HashMap, HashMap> cachedFields = new HashMap<>(); - private static final HashMap> cachedOBCClass = new HashMap<>(); - private static final HashMap> cachedNMSClass = new HashMap<>(); - - private ReflectionUtilities() { - // EMPTY - } - - public static Map getCachedHandles() { - return cachedHandles; - } - - public static void setValue(Object instance, String fieldName, Object value) throws Exception { - Field field = instance.getClass().getDeclaredField(fieldName); - field.setAccessible(true); - field.set(instance, value); - } - - public static Object getValue(Object instance, String fieldName) - throws Exception { - Field field = instance.getClass().getDeclaredField(fieldName); - field.setAccessible(true); - return field.get(instance); - } - - public static Class getNMSClass(String className) { - if (DebugUtils.LOG_CACHED_INFO) { - ChatUtils.log("Cached NMS classes: " + cachedNMSClass.size()); - } - - Class val = cachedNMSClass.get(className); - if (val != null) { - return val; - } - - String fullName = "net.minecraft.server." + VersionUtils.getVersionRaw() + "." + className; - Class clazz = null; - try { - clazz = Class.forName(fullName); - } catch (Exception e) { - e.printStackTrace(); - } - - cachedNMSClass.put(className, clazz); - - return clazz; - } - - public static Class getOBCClass(String className) { - if (DebugUtils.LOG_CACHED_INFO) { - ChatUtils.log("Cached OBC classes: " + cachedOBCClass.size()); - } - - Class val = cachedOBCClass.get(className); - if (val != null) { - return val; - } - - String fullName = "org.bukkit.craftbukkit." + VersionUtils.getVersionRaw() + "." + className; - Class clazz = null; - try { - clazz = Class.forName(fullName); - } catch (Exception e) { - e.printStackTrace(); - } - - cachedOBCClass.put(className, clazz); - - return clazz; - } - - public static Object getHandle(Object obj) { - if (DebugUtils.LOG_CACHED_INFO) { - ChatUtils.log("Cached handles: " + cachedHandles.size()); - } - - Object val = cachedHandles.get(obj); - if (val != null) { - return val; - } - - try { - Object returnObj = getMethod(obj.getClass(), "getHandle").invoke(obj); - cachedHandles.put(obj, returnObj); - return returnObj; - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - public static Field getField(Class clazz, String name) { - if (DebugUtils.LOG_CACHED_INFO) { - ChatUtils.log("Cached fields: " + cachedFields.size()); - } - - if (!DebugUtils.ENABLE_CACHING) { - return getFieldOriginal(clazz, name); - } - - HashMap val = cachedFields.computeIfAbsent(clazz, c -> { - HashMap blank = new HashMap<>(); - cachedFields.put(clazz, blank); - return blank; - }); - - Field val2 = val.get(name); - if (val2 != null) { - return val2; - } else { - Field field = getFieldOriginal(clazz, name); - cachedFields.get(clazz).put(name, field); - return field; - } - } - - public static Field getFieldOriginal(Class clazz, String name) { - try { - Field field = clazz.getDeclaredField(name); - field.setAccessible(true); - return field; - } catch (Exception e) { - e.printStackTrace(); - return null; - } - } - - public static Method getMethod(Class clazz, String name, Class... args) { - try { - Method method = clazz.getDeclaredMethod(name, args); - method.setAccessible(true); - return method; - } catch (NoSuchMethodException e) { - e.printStackTrace(); - return null; - } - } - - public static void clearLoaded() { - cachedHandles.clear(); - cachedNMSClass.clear(); - cachedOBCClass.clear(); - cachedFields.clear(); - } -} diff --git a/src/main/java/me/ztowne13/customcrates/utils/Utils.java b/src/main/java/me/ztowne13/customcrates/utils/Utils.java deleted file mode 100644 index 8b95164..0000000 --- a/src/main/java/me/ztowne13/customcrates/utils/Utils.java +++ /dev/null @@ -1,268 +0,0 @@ -package me.ztowne13.customcrates.utils; - -import com.cryptomorin.xseries.XMaterial; -import me.ztowne13.customcrates.SettingsValue; -import me.ztowne13.customcrates.SpecializedCrates; -import org.bukkit.Bukkit; -import org.bukkit.Color; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - -import java.text.SimpleDateFormat; -import java.util.*; - -public class Utils { - - private static final Random RANDOM = new Random(); - private static int cachedParticleDistance = -1; - - private Utils() { - // EMPTY - } - - public static void setCachedParticleDistance(int cachedParticleDistance) { - Utils.cachedParticleDistance = cachedParticleDistance; - } - - public static boolean hasItemInHand(Player player) { - return player.getItemInHand() != null && !player.getItemInHand().getType().equals(Material.AIR); - } - - public static boolean itemHasName(ItemStack stack) { - return stack.hasItemMeta() && stack.getItemMeta().hasDisplayName(); - } - - public static String getStringFromColor(Color color) { - if (color.asRGB() == Color.AQUA.asRGB()) { - return "AQUA"; - } else if (color.asRGB() == Color.BLACK.asRGB()) { - return "BLACK"; - } else if (color.asRGB() == Color.BLUE.asRGB()) { - return "BLUE"; - } else if (color.asRGB() == Color.FUCHSIA.asRGB()) { - return "FUCHSIA"; - } else if (color.asRGB() == Color.GRAY.asRGB()) { - return "GRAY"; - } else if (color.asRGB() == Color.GREEN.asRGB()) { - return "GREEN"; - } else if (color.asRGB() == Color.LIME.asRGB()) { - return "LIME"; - } else if (color.asRGB() == Color.MAROON.asRGB()) { - return "MAROON"; - } else if (color.asRGB() == Color.NAVY.asRGB()) { - return "NAVY"; - } else if (color.asRGB() == Color.OLIVE.asRGB()) { - return "OLIVE"; - } else if (color.asRGB() == Color.ORANGE.asRGB()) { - return "ORANGE"; - } else if (color.asRGB() == Color.PURPLE.asRGB()) { - return "PURPLE"; - } else if (color.asRGB() == Color.RED.asRGB()) { - return "RED"; - } else if (color.asRGB() == Color.SILVER.asRGB()) { - return "SILVER"; - } else if (color.asRGB() == Color.TEAL.asRGB()) { - return "TEAL"; - } else if (color.asRGB() == Color.WHITE.asRGB()) { - return "WHITE"; - } else if (color.asBGR() == Color.YELLOW.asBGR()) { - return "YELLOW"; - } - return null; - } - - public static Color getColorFromString(String s) { - if (s.equalsIgnoreCase("AQUA")) { - return Color.AQUA; - } else if (s.equalsIgnoreCase("BLACK")) { - return Color.BLACK; - } else if (s.equalsIgnoreCase("BLUE")) { - return Color.BLUE; - } else if (s.equalsIgnoreCase("FUCHSIA")) { - return Color.FUCHSIA; - } else if (s.equalsIgnoreCase("GRAY")) { - return Color.GRAY; - } else if (s.equalsIgnoreCase("GREEN")) { - return Color.GREEN; - } else if (s.equalsIgnoreCase("LIME")) { - return Color.LIME; - } else if (s.equalsIgnoreCase("MAROON")) { - return Color.MAROON; - } else if (s.equalsIgnoreCase("NAVY")) { - return Color.NAVY; - } else if (s.equalsIgnoreCase("OLIVE")) { - return Color.OLIVE; - } else if (s.equalsIgnoreCase("ORANGE")) { - return Color.ORANGE; - } else if (s.equalsIgnoreCase("PURPLE")) { - return Color.PURPLE; - } else if (s.equalsIgnoreCase("RED")) { - return Color.RED; - } else if (s.equalsIgnoreCase("SILVER")) { - return Color.SILVER; - } else if (s.equalsIgnoreCase("TEAL")) { - return Color.TEAL; - } else if (s.equalsIgnoreCase("WHITE")) { - return Color.WHITE; - } else if (s.equalsIgnoreCase("YELLOW")) { - return Color.YELLOW; - } - return null; - } - - public static int getOpenInventorySlots(Player player) { - int slots = 0; - for (int i = 0; i < 36; i++) { - ItemStack itemStack = player.getInventory().getItem(i); - if (itemStack == null || XMaterial.AIR.isSimilar(itemStack)) { - slots++; - } - } - - return slots; - } - - public static String currentTimeParsed() { - long millis = System.currentTimeMillis(); - Date d = new Date(millis); - return d.toString(); - } - - public static List onlyLeaveEntriesWithPref(List list, String pref) { - List newList = new ArrayList<>(); - for (String s : list) { - if (s.toLowerCase().startsWith(pref.toLowerCase())) { - newList.add(s); - } - } - return newList; - } - - public static List iteratorToList(Iterator i) { - List l = new ArrayList<>(); - while (i.hasNext()) { - l.add(i.next()); - } - return l; - } - - public static List wrapArrays(List ar1, List ar2) { - ar1.addAll(ar2); - return ar1; - } - - public static boolean isPLInstalled(String name) { - if (Bukkit.getPluginManager().getPlugin(name) != null) { - return Bukkit.getPluginManager().isPluginEnabled(name); - } - return false; - } - - public static boolean isInt(String s) { - try { - Integer.parseInt(s); - return true; - } catch (Exception exc) { - return false; - } - } - - public static boolean isDouble(String s) { - try { - Double.valueOf(s); - return true; - } catch (Exception exc) { - return false; - } - } - - public static boolean isLong(String s) { - try { - Long.valueOf(s); - return true; - } catch (Exception exc) { - return false; - } - } - - public static boolean isBoolean(String s) { - try { - return s.equalsIgnoreCase("true") || s.equalsIgnoreCase("false"); - } catch (Exception exc) { - return false; - } - } - - public static void giveAllItem(ItemStack stack) { - for (Player p : Bukkit.getOnlinePlayers()) { - p.getInventory().addItem(stack); - } - } - - public static void addToInfoLog(SpecializedCrates cc, String s, String s2) { - cc.getSettings().getInfoToLog().remove(s); - - cc.getSettings().getInfoToLog().put(s, s2); - } - - public static int getRandomNumberExcluding(int limit, List exclude) { - int generated = RANDOM.nextInt(limit); - return exclude.contains(generated) ? getRandomNumberExcluding(limit, exclude) : generated; - } - - public static void addItemAndDropRest(final Player player, ItemStack stack) { - addItemAndDropRest(player, stack, true); - } - - public static int addItemAndDropRest(final Player player, ItemStack stack, boolean doDrop) { - HashMap list = player.getInventory().addItem(stack); - int count = 0; - - for (ItemStack toDrop : list.values()) { - if (doDrop) - player.getWorld().dropItemNaturally(player.getLocation(), toDrop); - - count += toDrop.getAmount(); - } - - return count; - } - - public static String[] convertSecondToHHMMString(long secondTime) { - TimeZone tz = TimeZone.getTimeZone("UTC"); - SimpleDateFormat df = new SimpleDateFormat("dd:HH:mm:ss"); - df.setTimeZone(tz); - String time = df.format(new Date(secondTime * 1000L)); - - String[] args = time.split(":"); - String seconds = args[3]; - String minutes = args[2]; - String hours = args[1]; - String days = (Integer.parseInt(args[0]) - 1) + ""; - - return new String[]{days, hours, minutes, seconds}; - } - - public static boolean isPlayerInRange(SpecializedCrates sc, Player p, Location center) { - if (!sc.isParticlesEnabled()) { - return false; - } - - if (cachedParticleDistance == -1) { - cachedParticleDistance = (int) SettingsValue.PARTICLE_VIEW_DISTANCE.getValue(sc); - } - - double distance; - if (Objects.equals(center.getWorld(), p.getWorld())) { - distance = center.distance(p.getLocation()); - if (distance > 1.7976931348623157E+308D) - return false; - else { - return distance < cachedParticleDistance; - } - } - return false; - } -} diff --git a/src/main/java/me/ztowne13/customcrates/utils/VersionUtils.java b/src/main/java/me/ztowne13/customcrates/utils/VersionUtils.java deleted file mode 100644 index 0bb1a91..0000000 --- a/src/main/java/me/ztowne13/customcrates/utils/VersionUtils.java +++ /dev/null @@ -1,63 +0,0 @@ -package me.ztowne13.customcrates.utils; - -import org.bukkit.Bukkit; - -public class VersionUtils { - private static String cachedVersionRaw = ""; - private static String cachedServerVersion = ""; - - public static String getVersionRaw() { - if (cachedVersionRaw.equals("")) { - cachedVersionRaw = Bukkit.getServer().getClass().getPackage().getName().split("\\.")[3]; - } - return cachedVersionRaw; - } - - public static String getServerVersion() { - if (cachedServerVersion.equals("")) { - cachedServerVersion = Bukkit.getServer().getClass().getPackage().getName().substring(23); - } - return cachedServerVersion; - } - - public enum Version { - v1_7, - v1_8, - v1_8_R3, - v1_9, - v1_10, - v1_11, - v1_12, - v1_13, - v1_14, - v1_15, - v1_16, - v1_17, - v1_18; - - public boolean isServerVersionOrEarlier() { - for (Version version : Version.values()) { - if (VersionUtils.getServerVersion().contains(version.name())) - return true; - if (this == version) - break; - } - return false; - } - - public boolean isServerVersionOrLater() { - boolean found = false; - - for (Version version : Version.values()) { - if (this == version && !found) - found = true; - - if (found && VersionUtils.getServerVersion().contains(version.name())) - return true; - } - return false; - } - - } - -} diff --git a/src/main/kotlin/me/ztowne13/customcrates/SpecialisedCrates.kt b/src/main/kotlin/me/ztowne13/customcrates/SpecialisedCrates.kt new file mode 100644 index 0000000..759bcf9 --- /dev/null +++ b/src/main/kotlin/me/ztowne13/customcrates/SpecialisedCrates.kt @@ -0,0 +1,418 @@ +package me.ztowne13.customcrates + +import ch.jalu.configme.SettingsManager +import com.google.gson.Gson +import com.google.gson.GsonBuilder +import com.okkero.skedule.CoroutineTask +import com.okkero.skedule.SynchronizationContext +import com.okkero.skedule.schedule +import me.ztowne13.customcrates.api.SpecialisedCratesAPI +import me.ztowne13.customcrates.crates.Crate +import me.ztowne13.customcrates.handlers.CrateHandler +import me.ztowne13.customcrates.handlers.EconomyHandler +import me.ztowne13.customcrates.holograms.HologramHandler +import me.ztowne13.customcrates.listeners.* +import me.ztowne13.customcrates.logic.Loop +import me.ztowne13.customcrates.particles.ParticleHandler +import me.ztowne13.customcrates.storage.StorageProvider +import me.ztowne13.customcrates.utils.* +import me.ztowne13.oldcustomcrates.interfaces.externalhooks.EconomyHandler +import me.ztowne13.oldcustomcrates.interfaces.externalhooks.holograms.HologramManager +import org.bukkit.Bukkit +import org.bukkit.entity.Player +import org.bukkit.event.Listener +import org.bukkit.plugin.Plugin +import org.bukkit.plugin.java.JavaPlugin +import org.bukkit.scheduler.BukkitScheduler +import org.jetbrains.annotations.Async +import java.lang.Exception +import java.util.ArrayList + +class SpecialisedCrates : JavaPlugin() { + + //TODO + // Rework command system to be cleaner (ACF) + // Rework config system + // Rework saving system + // Reorganise everything to work - IN PROGRESS + // Use Coroutines everywhere because they are cool + + companion object { + private var api = SpecialisedCratesAPI() + private val gson = GsonBuilder().setPrettyPrinting().create() + + fun getApi(): SpecialisedCratesAPI { return api } + fun getGson(): Gson { return gson } + } + + private lateinit var settingsManager: SettingsManager + + private lateinit var hologramHandler: HologramHandler + private lateinit var crateHandler: CrateHandler + private lateinit var economyHandler: EconomyHandler + private lateinit var particleHandler: ParticleHandler + + private lateinit var storageProvider: StorageProvider + + + fun getSchedule(): BukkitScheduler { + return Bukkit.getScheduler() + } + fun getInstance(): SpecialisedCrates { return this } + + override fun onEnable() { + onEnable(true) + } + + private fun onEnable(register: Boolean) { + if (!Bukkit.getPluginManager().isPluginEnabled("Vault")) { + Logging.warn("It appears that you don't have Vault! Stopping the plugin..") + Bukkit.getPluginManager().disablePlugin(this) + return + } + + if (!Bukkit.getPluginManager()) + } + +// scheduler.scheduleSyncRepeatingTask(this, schedule) +// +// if (metricsLite == null) { +// metricsLite = metricsLite(this, 5642) +// } +// +// if (debugUtils == null) { +// debugUtils = DebugUtils(this) +// } +// +// if (Bukkit.getPluginManager().getPlugin("PlaceholderAPI") != null && !isUsingPlaceholderAPI()) { +// placeHolderAPIHandler = PlaceHolderAPIHandler(this) +// placeHolderAPIHandler!!.register() +// } +// +// reloadConfig() +// saveDefaultConfig() +// loadFiles() +// +// dataHandler = me.ztowne13.oldcustomcrates.DataHandler(this, dataFile) +// +// setSettings(Settings(this)) +// hologramManager = when { +// Utils.isPLInstalled("HolographicDisplays") -> { +// Utils.addToInfoLog(this, "Hologram Plugin", "HolographicDisplays") +// HDHologramManager(this) +// } +// Utils.isPLInstalled("Holograms") -> { +// Utils.addToInfoLog(this, "Hologram Plugin", "Holograms") +// SainttXHologramManager(this) +// } +// Utils.isPLInstalled("CMI") -> { +// Utils.addToInfoLog(this, "Hologram Plugin", "CMI") +// ZripsHologramManager(this) +// } +// else -> { +// Utils.addToInfoLog(this, "Hologram Plugin", "None") +// NoHologramManager(this) +// } +// } +// +// getSettings()!!.load() +// registerCommands() +// +// if (register) { +// registerAll() +// } +// +// for (p: Player in Bukkit.getOnlinePlayers()) { +// PlayerManager[this, p] +// } +// +// NPCUtils.load(register) +// NPCUtils.checkUncheckMobs(this, false, 20) +// loadRewards() +// run() +// dataHandler!!.loadFromFile() +// allowTick = true +// getSettings()!!.getInfoToLog().put("Metrics", if (metricsLite == null) "&cdisabled" else "&aenabled") +// +// // Check to see if the plugin needs a reload to find the hologram plugin +// if (!hasAttemptedReload) { +// Bukkit.getScheduler().runTaskLater(this, Runnable { +// if (getSettings()!!.getInfoToLog().containsKey("Hologram Plugin") && +// getSettings()!!.getInfoToLog()["Hologram Plugin"].equals("None", ignoreCase = true) +// ) { +// hasAttemptedReload = true +// ChatUtils.log( +// ("&e[SpecialisedCrates] No hologram plugin was found. In the off-chance that this is because the hologram plugin" + +// " opted to ignore the softdepend and loaded after SpecialisedCrates, the plugin is reloading once to " + +// "try again.") +// ) +// reload() +// } +// }, 1) +// } +// if (Bukkit.getServer().getSpawnRadius() != 0) { +// ChatUtils.log( +// ("&4WARNING: &cThe value 'spawn-protection' is set to " + Bukkit.getServer().getSpawnRadius() + +// " in the server.properties file. This WILL cause issues with SpecialisedCrates - any crates near spawn will " + +// "only be openable for OP players. Please go to your server.properties file in the main directory of your server" + +// " and change spawn-protection: 0.") +// ) +// } +// } +// override fun onDisable() { +// allowTick = false +// try { +// finishUpPlayers() +// } catch (exc: Exception) { +// // IGNORED +// } +// dataHandler!!.saveToFile() +// CHologram.Companion.deleteAll() +// NPCUtils.checkUncheckMobs(true) +// OpenChestAnimation.Companion.removeAllItems() +// Messages.Companion.clearCache() +// SQLQueryThread.Companion.stopRun() +// SQLQueryThread.Companion.clearQuery() +// saveFilesTick(false) +// } +// +// fun saveEverything() { +// messageFile!!.save() +// rewardsFile!!.save() +// crateConfigFile!!.save() +// settings!!.writeSettingsValues() +// for (crate: Crate in Crate.Companion.getLoadedCrates().values) { +// try { +// crate.getSettings().saveAll() +// } catch (exc: Exception) { +// exc.printStackTrace() +// } +// } +// } +// +// fun reload() { +// ChatUtils.log("Disabling...") +// onDisable() +// setMessageFile(null) +// setRewardsFile(null) +// setActiveCratesFile(null) +// setCrateConfigFile(null) +// setSettings(null) +// setDataFile(null) +// setSqlFile(null) +// getCommand("scrates").setExecutor(null) +// getCommand("scrates").setTabCompleter(null) +// getCommand("keys").setExecutor(null) +// try { +// getCommand("rewards").setExecutor(null) +// getCommand("rewards").setTabCompleter(null) +// } catch (exc: Exception) { +// // IGNORED +// } +// setTick(0) +// FileHandler.Companion.clearLoaded() +// PlacedCrate.Companion.clearLoaded() +// PlayerManager.Companion.clearLoaded() +// Crate.Companion.clearLoaded() +// ReflectionUtilities.clearLoaded() +// Utils.setCachedParticleDistance(-1) +// stopRun() +// setBukkitTask(null) +// CReward.Companion.getAllRewards().clear() +// SettingsValue.Companion.clearCache() +// ChatUtils.log("Enabling SpecialisedCrates") +// onEnable(false) +// } +// +// fun registerCommands() { +// val tabCompleteListener: TabCompleteListener = TabCompleteListener(this) +// commandCrate = CommandCrate(this) +// getCommand("scrates").setExecutor(commandCrate) +// getCommand("scrates").setTabCompleter(tabCompleteListener) +// getCommand("keys").setExecutor(CommandKey(this)) +// getCommand("rewards").setExecutor(CommandRewards(this)) +// getCommand("rewards").setTabCompleter(tabCompleteListener) +// } +// +// fun registerAll() { +// registerListener(InteractListener(this)) +// registerListener(BlockBreakListener(this)) +// registerListener(BlockPlaceListener(this)) +// registerListener(BlockRemoveListener(this)) +// registerListener(InventoryActionListener(this)) +// registerListener(PlayerConnectionListener(this)) +// registerListener(CommandPreprocessListener(this)) +// registerListener(ChatListener(this)) +// registerListener(PluginEnableListener(this)) +// registerListener(DamageListener(this)) +// if (NPCUtils.isCitizensInstalled()) { +// registerListener(NPCEventListener(this)) +// } +// } +// +// fun loadRewards() { +// var newValues: Boolean = false +// for (rName: String? in getRewardsFile()!!.get()!!.getKeys(false)) { +// if (!CReward.Companion.getAllRewards().containsKey(rName)) { +// if (!newValues) { +// newValues = true +// } +// val reward: Reward = Reward(this, rName) +// reward.loadFromConfig() +// reward.loadChance() +// CReward.Companion.getAllRewards().put(rName, reward) +// } +// } +// } +// +// fun registerListener(listener: Listener?) { +// Bukkit.getPluginManager().registerEvents(listener, this) +// } +// +// fun loadFiles() { +// setRewardsFile(FileHandler(this, "Rewards.yml", true, false)) +// setActiveCratesFile(FileHandler(this, "ActiveCrates.db", false, false)) +// setCrateConfigFile(FileHandler(this, "CrateConfig.yml", true, false)) +// setMessageFile(FileHandler(this, "Messages.yml", true, false)) +// setDataFile(FileHandler(this, "PluginData.db", false, false)) +// setSqlFile(FileHandler(this, "SQL.yml", true, false)) +// getMessageFile()!!.saveDefaults() +// getRewardsFile()!!.saveDefaults() +// getActiveCratesFile()!!.saveDefaults() +// getCrateConfigFile()!!.saveDefaults() +// getDataFile()!!.saveDefaults() +// getSqlFile()!!.saveDefaults() +// } +// +// fun firstLoadFiles() { +// val firstFiles: Array = +// arrayOf("BasicCrate", "BeginnerCrate", "MiddleCrate", "MasterCrate", "MineChestExample", "ExpertCrate") +// for (newFile: String in firstFiles) { +// FileHandler(this, newFile + ".crate", "Crates/", true, true, false).saveDefaults() +// } +// FileHandler(this, "AllCrates.multicrate", "Crates/", true, true, false).saveDefaults() +// } +// +// fun tick() { +// if (!allowTick) { +// return +// } +// for (placedCrate: PlacedCrate in ArrayList(PlacedCrate.Companion.getPlacedCrates().values)) { +// if (placedCrate.isCratesEnabled()) { +// try { +// placedCrate.tick(CrateState.PLAY) +// } catch (exc: Exception) { +// exc.printStackTrace() +// } +// } +// } +// getAlreadyUpdated().clear() +// setTotalTicks(getTotalTicks() + 1) +// setTick(getTick() + 1) +// if (getTick() == 10) { +// setTick(0) +// saveFilesTick(true) +// for (p: Player? in Bukkit.getOnlinePlayers()) { +// val pdm: PlayerDataManager = PlayerManager.Companion.get(this, p)!! +// .getPlayerDataManager() +// val list: ArrayList = ArrayList(pdm.getCrateCooldownEvents()) +// for (cce: CrateCooldownEvent? in list) { +// cce!!.tickSecond(pdm) +// } +// } +// } +// } +// +// fun saveFilesTick(isInterval: Boolean) { +// saveFilesTick++ +// val dataSaveType: String = SettingsValue.DATA_SAVE_METHOD.getValue(this).toString() +// val saveInterVal: Int = SettingsValue.DATA_SAVE_INTERVAL.getValue(this) as Int +// if (isInterval && (dataSaveType.equals("DISABLE", ignoreCase = true) || saveFilesTick % saveInterVal != 0)) { +// return +// } +// if (FlatFileDataHandler.Companion.isToSave()) { +// getDebugUtils()!!.log("saveFilesTick() - Saving playerdata.db flat file") +// FlatFileDataHandler.Companion.getFileHandler()!!.save() +// FlatFileDataHandler.Companion.resetToSave() +// } +// for (file: IndividualFileDataHandler in IndividualFileDataHandler.Companion.getToSave()) { +// file.getFileHandler().save() +// } +// IndividualFileDataHandler.Companion.getToSave().clear() +// } +// +// fun run() { +// setBukkitTask(Bukkit.getScheduler().runTaskTimer(this, Runnable({ +// if (DebugUtils.Companion.OUTPUT_AVERAGE_TICK) { +// val curTimeMillis: Long = System.currentTimeMillis() +// tick() +// val dif: Long = (System.currentTimeMillis() - curTimeMillis) +// total += dif +// count++ +// val solved: Long = total / count +// ChatUtils.log("Average: " + solved) +// } else { +// tick() +// } +// }), 0, 2)) +// } +// +// fun finishUpPlayers() { +// for (p: Player in Bukkit.getOnlinePlayers()) { +// val pm: PlayerManager? = PlayerManager.Companion.get(this, p) +// if (pm!!.isInCrateAnimation()) { +// pm.getCurrentAnimation()!!.setFastTrack(true, true) +// } +// if (pm.isInCratesClaimMenu()) { +// p.closeInventory() +// } +// } +// } + + fun particleCoroutine() { + getSchedule().schedule(this) { + repeating(2) + + + } + } + + fun saveCoroutine() { + getSchedule().schedule(this) { + repeating(600) + + + + } + } + + + + fun getSettingsManager(): SettingsManager { + return settingsManager + } + + fun getHologramHandler(): Any { + return hologramHandler + } + + fun getCrateHandler(): CrateHandler { + return crateHandler + } + + fun getEconomyHandler(): EconomyHandler { + return economyHandler + } + + fun getParticleHandler(): ParticleHandler { + return particleHandler + } + + fun getLoop(): Loop { + return loop + } + + fun getStorageProvider(): StorageProvider { + return storageProvider + } +} \ No newline at end of file diff --git a/src/main/kotlin/me/ztowne13/customcrates/api/SpecialisedCratesAPI.kt b/src/main/kotlin/me/ztowne13/customcrates/api/SpecialisedCratesAPI.kt new file mode 100644 index 0000000..3ec7f8e --- /dev/null +++ b/src/main/kotlin/me/ztowne13/customcrates/api/SpecialisedCratesAPI.kt @@ -0,0 +1,4 @@ +package me.ztowne13.customcrates.api + +class SpecialisedCratesAPI { +} \ No newline at end of file diff --git a/src/main/kotlin/me/ztowne13/customcrates/api/events/CrateOpenEvent.kt b/src/main/kotlin/me/ztowne13/customcrates/api/events/CrateOpenEvent.kt new file mode 100644 index 0000000..1cfd161 --- /dev/null +++ b/src/main/kotlin/me/ztowne13/customcrates/api/events/CrateOpenEvent.kt @@ -0,0 +1,18 @@ +package me.ztowne13.customcrates.api.events + +import org.bukkit.entity.Player +import org.bukkit.event.HandlerList +import me.ztowne13.customcrates.crates.Crate +import me.ztowne13.customcrates.crates.options.rewards.Reward +import org.bukkit.event.Event + +class CrateOpenEvent(val player: Player, val rewards: List?, val crate: Crate?, val openedCratesCount: Int) : + Event() { + override fun getHandlers(): HandlerList { + return handlerList + } + + companion object { + val handlerList = HandlerList() + } +} \ No newline at end of file diff --git a/src/main/kotlin/me/ztowne13/customcrates/commands/ACFHandler.kt b/src/main/kotlin/me/ztowne13/customcrates/commands/ACFHandler.kt new file mode 100644 index 0000000..80a2db0 --- /dev/null +++ b/src/main/kotlin/me/ztowne13/customcrates/commands/ACFHandler.kt @@ -0,0 +1,177 @@ +package me.ztowne13.customcrates.commands + +import ch.jalu.configme.SettingsManager +import me.ztowne13.customcrates.SpecialisedCrates +import net.milkbowl.vault.economy.Economy +import net.milkbowl.vault.permission.Permission +import org.bukkit.Bukkit +import org.bukkit.entity.Player +import java.util.* + +class ACFHandler(private val plugin: SpecialisedCrates, private val commandManager: PaperCommandManager) { + val languages = mutableListOf() + + fun load() { + commandManager.usePerIssuerLocale(true, false) + commandManager.enableUnstableAPI("help") + + loadLang() + loadContexts(plugin.guildHandler, plugin.arenaHandler) + loadCompletions(plugin.guildHandler, plugin.arenaHandler) + loadConditions(plugin.guildHandler) + loadDI() + + commandManager.commandReplacements.addReplacement("guilds", plugin.settingsHandler.mainConf.getProperty(PluginSettings.PLUGIN_ALIASES)) + commandManager.commandReplacements.addReplacement("syntax", plugin.settingsHandler.mainConf.getProperty(PluginSettings.SYNTAX_NAME)) + + loadCommands() + loadCompletionCache() + } + + fun loadLang() { + languages.clear() + plugin.dataFolder.resolve("languages").listFiles()?.filter { + it.extension.equals("yml", true) + }?.forEach { + val locale = Locale.forLanguageTag(it.nameWithoutExtension) + + commandManager.addSupportedLanguage(locale) + commandManager.locales.loadYamlLanguageFile(it, locale) + languages.add(it.nameWithoutExtension) + } + commandManager.locales.defaultLocale = Locale.forLanguageTag(plugin.settingsHandler.mainConf.getProperty(PluginSettings.MESSAGES_LANGUAGE)) + } + + private fun loadContexts(guildHandler: GuildHandler, arenaHandler: ArenaHandler) { + commandManager.commandContexts.registerIssuerAwareContext(Guild::class.java) { c -> + val guild: Guild = (if (c.hasFlag("other")) { + guildHandler.getGuild(c.popFirstArg()) + } else { + guildHandler.getGuild(c.player) + }) + ?: throw InvalidCommandArgument(Messages.ERROR__NO_GUILD) + guild + } + commandManager.commandContexts.registerContext(Arena::class.java) { c -> arenaHandler.getArena(c.popFirstArg()).get() } + } + + private fun loadConditions(guildHandler: GuildHandler) { + commandManager.commandConditions.addCondition(Guild::class.java, "perm") { c, exec, value -> + if (value == null) { + return@addCondition + } + val player = exec.player + val guild = guildHandler.getGuild(player) + if (!guild.memberHasPermission(player, c.getConfigValue("perm", "SERVER_OWNER"))) { + throw InvalidPermissionException() + } + } + commandManager.commandConditions.addCondition(Guild::class.java, "NotMaxedAllies") { c, exec, value -> + if (value == null) { + return@addCondition + } + val player = exec.player + val guild = guildHandler.getGuild(player) + if (guild.allies.size >= guild.tier.maxAllies) { + throw ExpectationNotMet(Messages.ALLY__MAX_ALLIES) + } + } + commandManager.commandConditions.addCondition(Player::class.java, "NoGuild") { c, exec, value -> + if (value == null) { + return@addCondition + } + val player = exec.player + if (guildHandler.getGuild(player) != null) { + throw ExpectationNotMet(Messages.ERROR__ALREADY_IN_GUILD) + } + } + commandManager.commandConditions.addCondition("NotMigrating") { + if (guildHandler.isMigrating) { + throw ExpectationNotMet(Messages.ERROR__MIGRATING) + } + } + } + + private fun loadCompletions(guildHandler: GuildHandler, arenaHandler: ArenaHandler) { + commandManager.commandCompletions.registerCompletion("online") { Bukkit.getOnlinePlayers().map { it.name } } + commandManager.commandCompletions.registerCompletion("invitedTo") { c -> guildHandler.getInvitedGuilds(c.player) } + commandManager.commandCompletions.registerCompletion("joinableGuilds") { c -> guildHandler.getJoinableGuild(c.player) } + commandManager.commandCompletions.registerCompletion("guilds") { guildHandler.guildNames } + commandManager.commandCompletions.registerCompletion("arenas") { arenaHandler.getArenas().map { it.name } } + commandManager.commandCompletions.registerStaticCompletion("locations") { listOf("challenger", "defender") } + commandManager.commandCompletions.registerCompletion("languages") { languages.sorted() } + commandManager.commandCompletions.registerStaticCompletion("sources") { listOf("JSON", "MYSQL", "SQLITE", "MARIADB") } + + commandManager.commandCompletions.registerAsyncCompletion("members") { c -> + val guild = guildHandler.getGuild(c.player) ?: return@registerAsyncCompletion emptyList() + guild.members.mapNotNull { guildHandler.lookupCache[it.uuid] ?: it.name } + } + + commandManager.commandCompletions.registerCompletion("claimed") { c -> + val guild = guildHandler.getGuild(c.player) ?: return@registerCompletion emptyList() + return@registerCompletion mutableListOf("this", "all") + } + + commandManager.commandCompletions.registerCompletion("members-admin") { c -> + val guild = c.getContextValue(Guild::class.java, 1) ?: return@registerCompletion emptyList() + guild.members.mapNotNull { guildHandler.lookupCache[it.uuid] ?: it.name } + } + commandManager.commandCompletions.registerCompletion("allyInvites") { c -> + val guild = guildHandler.getGuild(c.player) ?: return@registerCompletion null + if (!guild.hasPendingAllies()) { + return@registerCompletion null + } + guild.pendingAllies.mapNotNull { guildHandler.getNameById(it) } + } + commandManager.commandCompletions.registerCompletion("allies") { c -> + val guild = guildHandler.getGuild(c.player) ?: return@registerCompletion null + if (!guild.hasAllies()) { + return@registerCompletion null + } + guild.allies.mapNotNull { guildHandler.getNameById(it) } + } + commandManager.commandCompletions.registerCompletion("activeCodes") { c -> + val guild = guildHandler.getGuild(c.player) ?: return@registerCompletion null + if (guild.codes == null) { + return@registerCompletion null + } + guild.codes.map { it.id } + } + commandManager.commandCompletions.registerCompletion("vaultAmount") { c -> + val guild = guildHandler.getGuild(c.player) ?: return@registerCompletion null + if (guild.vaults == null) { + return@registerCompletion null + } + val list = guildHandler.vaults[guild] ?: return@registerCompletion null + (1 until list.size).map(Any::toString) + } + } + + private fun loadCommands() { + ZISScanner().getClasses(Guilds::class.java, "me.glaremasters.guilds.commands").asSequence() + .filter { BaseCommand::class.java.isAssignableFrom(it) } + .forEach { commandManager.registerCommand(it.newInstance() as BaseCommand) } + } + + private fun loadCompletionCache() { + val handler = plugin.guildHandler + + handler.guilds.forEach { guild -> + guild.members.filterNotNull().forEach { member -> + handler.lookupCache.putIfAbsent(member.uuid, member.name) + } + } + } + + private fun loadDI() { + commandManager.registerDependency(GuildHandler::class.java, plugin.guildHandler) + commandManager.registerDependency(SettingsManager::class.java, plugin.settingsHandler.mainConf) + commandManager.registerDependency(ActionHandler::class.java, plugin.actionHandler) + commandManager.registerDependency(Economy::class.java, plugin.economy) + commandManager.registerDependency(Permission::class.java, plugin.permissions) + commandManager.registerDependency(CooldownHandler::class.java, plugin.cooldownHandler) + commandManager.registerDependency(ArenaHandler::class.java, plugin.arenaHandler) + commandManager.registerDependency(ChallengeHandler::class.java, plugin.challengeHandler) + commandManager.registerDependency(DatabaseAdapter::class.java, plugin.database) + } +} \ No newline at end of file diff --git a/src/main/kotlin/me/ztowne13/customcrates/crates/Crate.kt b/src/main/kotlin/me/ztowne13/customcrates/crates/Crate.kt new file mode 100644 index 0000000..a720cc6 --- /dev/null +++ b/src/main/kotlin/me/ztowne13/customcrates/crates/Crate.kt @@ -0,0 +1,57 @@ +package me.ztowne13.customcrates.crates + +class Crate(var name: String, var isEnabled: Boolean, var loaded: Boolean, var multiCrate: Boolean, var configuration: CrateConfiguration, var instances: CrateInstances ) { + + override fun toString(): String { + return "Crate(name=$name, isEnabled=$isEnabled, loaded=$loaded, multiCrate=$multiCrate, configuration=$configuration, instances=$instances)" + } + + class CrateBuilder internal constructor() { + private lateinit var name: String + private var isEnabled: Boolean = false + private var loaded: Boolean = false + private var multiCrate: Boolean = false + private lateinit var configuration: CrateConfiguration + private lateinit var instances: CrateInstances + + fun name(name: String): CrateBuilder { + this.name = name + return this + } + + fun isEnabled(isEnabled: Boolean): CrateBuilder { + this.isEnabled = isEnabled + return this + } + + fun loaded(loaded: Boolean): CrateBuilder { + this.loaded = loaded + return this + } + + fun multiCrate(multiCrate: Boolean): CrateBuilder { + this.multiCrate = multiCrate + return this + } + + fun configuration(configuration: CrateConfiguration): CrateBuilder { + this.configuration = configuration + return this + } + + fun instances(instances: CrateInstances): CrateBuilder { + this.instances = instances + return this + } + + override fun toString(): String { + return "Crate(name=$name, isEnabled=$isEnabled, loaded=$loaded, multiCrate=$multiCrate, configuration=$configuration, instances=$instances)" + } + } + + companion object { + fun builder(): CrateBuilder { + return CrateBuilder() + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/me/ztowne13/customcrates/crates/CrateConfiguration.kt b/src/main/kotlin/me/ztowne13/customcrates/crates/CrateConfiguration.kt new file mode 100644 index 0000000..22bd493 --- /dev/null +++ b/src/main/kotlin/me/ztowne13/customcrates/crates/CrateConfiguration.kt @@ -0,0 +1,4 @@ +package me.ztowne13.customcrates.crates + +class CrateConfiguration { +} \ No newline at end of file diff --git a/src/main/kotlin/me/ztowne13/customcrates/crates/CrateInstances.kt b/src/main/kotlin/me/ztowne13/customcrates/crates/CrateInstances.kt new file mode 100644 index 0000000..da2a782 --- /dev/null +++ b/src/main/kotlin/me/ztowne13/customcrates/crates/CrateInstances.kt @@ -0,0 +1,4 @@ +package me.ztowne13.customcrates.crates + +class CrateInstances { +} \ No newline at end of file diff --git a/src/main/kotlin/me/ztowne13/customcrates/data/DataHandler.kt b/src/main/kotlin/me/ztowne13/customcrates/data/DataHandler.kt new file mode 100644 index 0000000..698af6e --- /dev/null +++ b/src/main/kotlin/me/ztowne13/customcrates/data/DataHandler.kt @@ -0,0 +1,4 @@ +package me.ztowne13.customcrates.data + +class DataHandler { +} \ No newline at end of file diff --git a/src/main/kotlin/me/ztowne13/customcrates/data/json/Read.kt b/src/main/kotlin/me/ztowne13/customcrates/data/json/Read.kt new file mode 100644 index 0000000..5a2a0d7 --- /dev/null +++ b/src/main/kotlin/me/ztowne13/customcrates/data/json/Read.kt @@ -0,0 +1,4 @@ +package me.ztowne13.customcrates.data.json + +class Read { +} \ No newline at end of file diff --git a/src/main/kotlin/me/ztowne13/customcrates/data/json/Save.kt b/src/main/kotlin/me/ztowne13/customcrates/data/json/Save.kt new file mode 100644 index 0000000..f29b2eb --- /dev/null +++ b/src/main/kotlin/me/ztowne13/customcrates/data/json/Save.kt @@ -0,0 +1,4 @@ +package me.ztowne13.customcrates.data.json + +class Save { +} \ No newline at end of file diff --git a/src/main/kotlin/me/ztowne13/customcrates/data/sql/Read.kt b/src/main/kotlin/me/ztowne13/customcrates/data/sql/Read.kt new file mode 100644 index 0000000..91f94b3 --- /dev/null +++ b/src/main/kotlin/me/ztowne13/customcrates/data/sql/Read.kt @@ -0,0 +1,4 @@ +package me.ztowne13.customcrates.data.sql + +class Read { +} \ No newline at end of file diff --git a/src/main/kotlin/me/ztowne13/customcrates/data/sql/Save.kt b/src/main/kotlin/me/ztowne13/customcrates/data/sql/Save.kt new file mode 100644 index 0000000..557789f --- /dev/null +++ b/src/main/kotlin/me/ztowne13/customcrates/data/sql/Save.kt @@ -0,0 +1,4 @@ +package me.ztowne13.customcrates.data.sql + +class Save { +} \ No newline at end of file diff --git a/src/main/kotlin/me/ztowne13/customcrates/handlers/CrateHandler.kt b/src/main/kotlin/me/ztowne13/customcrates/handlers/CrateHandler.kt new file mode 100644 index 0000000..dae5721 --- /dev/null +++ b/src/main/kotlin/me/ztowne13/customcrates/handlers/CrateHandler.kt @@ -0,0 +1,4 @@ +package me.ztowne13.customcrates.handlers + +class CrateHandler { +} \ No newline at end of file diff --git a/src/main/kotlin/me/ztowne13/customcrates/handlers/EconomyHandler.kt b/src/main/kotlin/me/ztowne13/customcrates/handlers/EconomyHandler.kt new file mode 100644 index 0000000..ddc0552 --- /dev/null +++ b/src/main/kotlin/me/ztowne13/customcrates/handlers/EconomyHandler.kt @@ -0,0 +1,4 @@ +package me.ztowne13.customcrates.handlers + +class EconomyHandler { +} \ No newline at end of file diff --git a/src/main/kotlin/me/ztowne13/customcrates/holograms/HologramHandler.kt b/src/main/kotlin/me/ztowne13/customcrates/holograms/HologramHandler.kt new file mode 100644 index 0000000..de05c24 --- /dev/null +++ b/src/main/kotlin/me/ztowne13/customcrates/holograms/HologramHandler.kt @@ -0,0 +1,4 @@ +package me.ztowne13.customcrates.holograms + +class HologramHandler { +} \ No newline at end of file diff --git a/src/main/kotlin/me/ztowne13/customcrates/holograms/types/HolographicDisplays.kt b/src/main/kotlin/me/ztowne13/customcrates/holograms/types/HolographicDisplays.kt new file mode 100644 index 0000000..f491e13 --- /dev/null +++ b/src/main/kotlin/me/ztowne13/customcrates/holograms/types/HolographicDisplays.kt @@ -0,0 +1,4 @@ +package me.ztowne13.customcrates.holograms.types + +class HolographicDisplays { +} \ No newline at end of file diff --git a/src/main/kotlin/me/ztowne13/customcrates/listeners/BlockBreakListener.kt b/src/main/kotlin/me/ztowne13/customcrates/listeners/BlockBreakListener.kt new file mode 100644 index 0000000..19091bb --- /dev/null +++ b/src/main/kotlin/me/ztowne13/customcrates/listeners/BlockBreakListener.kt @@ -0,0 +1,77 @@ +package me.ztowne13.customcrates.listeners + +import org.bukkit.GameMode +import org.bukkit.event.block.BlockBreakEvent +import me.ztowne13.customcrates.SpecialisedCrates +import me.ztowne13.customcrates.crates.Crate +import me.ztowne13.customcrates.crates.PlacedCrate +import me.ztowne13.customcrates.crates.options.ObtainType +import me.ztowne13.customcrates.players.PlayerManager +import org.bukkit.event.EventHandler +import org.bukkit.event.Listener + +class BlockBreakListener(var cc: SpecialisedCrates) : Listener { + @EventHandler + fun onBreakPlacedCrate(e: BlockBreakEvent) { + val p = e.player + val l = e.block.location + if (PlacedCrate.Companion.crateExistsAt(l)) { + val cm: PlacedCrate = PlacedCrate.Companion.get(cc, l) + val crates = cm.crate + if (crates!!.settings.obtainType!!.isStatic) { + if (!p.hasPermission("me.ztowne13.customcrates.admin") && !p.hasPermission("specializedcrates.admin")) { + e.isCancelled = true + Messages.FAILED_BREAK_CRATE.msgSpecified( + cc, p, arrayOf("%crate%", "%reason%"), arrayOf( + crates.displayName, "static" + ) + ) + } + return + } + cm.delete() + Messages.BROKEN_CRATE.msgSpecified( + cc, p, arrayOf("%crate%"), arrayOf( + crates.displayName + ) + ) + } else { + // Event isn't already cancelled + if (!e.isCancelled) { + // Not in creative mode or creative mode is allowed + if (p.gameMode != GameMode.CREATIVE || (SettingsValue.LUCKYCHEST_CREATIVE.getValue(cc) as Boolean)) { + // Luckychests enabled + if (PlayerManager.Companion.get(cc, p)!!.getPlayerDataManager().isActivatedLuckyChests()) { + // Cycle through all potential crates + for (crates in Crate.Companion.getLoadedCrates().values) { + // Check if the crate is a lucky chest and if it is enabled + if (CrateUtils.isCrateUsable(crates) && crates.settings.luckyChestSettingsExists() && crates.settings.obtainType == ObtainType.LUCKYCHEST) { + // Check if the lucky chesty should be placed at the location + if (crates.settings.luckyChestSettings!!.checkRun(e.block)) { + // Check if this block is a placed block or not and whether or not that's okay + if (!e.block.hasMetadata("PLACED") || + e.block.getMetadata("PLACED") == null || + (SettingsValue.LUCKYCHEST_ALLOW_PLACED_BLOCKS.getValue(cc) as Boolean) + ) { + // Check to make sure the player has the permission or doesn't need the permission + if (!crates.settings.luckyChestSettings!!.isRequirePermission || + e.player.hasPermission(crates.settings.permission!!) + ) { + val cm: PlacedCrate = PlacedCrate.Companion.get( + cc, e.block.location + ) + cm.setup(crates, true) + Messages.FOUND_LUCKY_CHEST.msgSpecified(cc, p) + e.isCancelled = true + break + } + } + } + } + } + } + } + } + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/me/ztowne13/customcrates/listeners/BlockPlaceListener.kt b/src/main/kotlin/me/ztowne13/customcrates/listeners/BlockPlaceListener.kt new file mode 100644 index 0000000..1a6cea9 --- /dev/null +++ b/src/main/kotlin/me/ztowne13/customcrates/listeners/BlockPlaceListener.kt @@ -0,0 +1,33 @@ +package me.ztowne13.customcrates.listeners + +import org.bukkit.event.EventPriority +import org.bukkit.event.block.BlockPlaceEvent +import org.bukkit.metadata.FixedMetadataValue +import me.ztowne13.customcrates.SpecialisedCrates +import me.ztowne13.customcrates.crates.crateaction.AttemptCrateUseAction +import org.bukkit.event.EventHandler +import org.bukkit.event.Listener + +class BlockPlaceListener(var cc: SpecialisedCrates) : Listener { + @EventHandler(priority = EventPriority.LOWEST) + fun onPlaceCrateKey(e: BlockPlaceEvent) { + val p = e.player + val l = e.block.location + if (!e.isCancelled) { + if (CrateUtils.searchByKey(e.itemInHand) != null) { + Messages.DENY_PLACE_KEY.msgSpecified(cc, p) + e.isCancelled = true + } else { + if (AttemptCrateUseAction(cc, p, l, true).run()) { + e.isCancelled = true + } + } + } + } + + @EventHandler + fun onPlace(e: BlockPlaceEvent) { + val b = e.block + b.setMetadata("PLACED", FixedMetadataValue(cc, "something")) + } +} \ No newline at end of file diff --git a/src/main/kotlin/me/ztowne13/customcrates/listeners/BlockRemoveListener.kt b/src/main/kotlin/me/ztowne13/customcrates/listeners/BlockRemoveListener.kt new file mode 100644 index 0000000..fedb376 --- /dev/null +++ b/src/main/kotlin/me/ztowne13/customcrates/listeners/BlockRemoveListener.kt @@ -0,0 +1,45 @@ +package me.ztowne13.customcrates.listeners + +import org.bukkit.block.BlockFace +import org.bukkit.event.block.BlockExplodeEvent +import org.bukkit.event.block.BlockPistonExtendEvent +import org.bukkit.event.entity.EntityExplodeEvent +import me.ztowne13.customcrates.SpecialisedCrates +import me.ztowne13.customcrates.crates.PlacedCrate +import org.bukkit.block.Block +import org.bukkit.event.EventHandler +import org.bukkit.event.Listener + +class BlockRemoveListener(var cc: SpecialisedCrates) : Listener { + @EventHandler + fun onBlockChange(e: BlockExplodeEvent) { + if (cc.isAllowTick) if ((SettingsValue.EXPLODE_DYNAMIC.getValue(cc) as Boolean)) e.blockList() + .removeIf { b: Block -> PlacedCrate.Companion.crateExistsAt(b.location) } + } + + @EventHandler + fun onPistonPush(e: BlockPistonExtendEvent) { + if (cc.isAllowTick && shouldCancel(e.blocks, e.direction)) e.isCancelled = true + } + + @EventHandler + fun onEntityExplode(e: EntityExplodeEvent) { + if (cc.isAllowTick) if ((SettingsValue.EXPLODE_DYNAMIC.getValue(cc) as Boolean)) e.blockList() + .removeIf { b: Block -> PlacedCrate.Companion.crateExistsAt(b.location) } + } + + fun shouldCancel(blocks: List, bf: BlockFace?): Boolean { + var shouldCancel = false + if ((SettingsValue.EXPLODE_DYNAMIC.getValue(cc) as Boolean)) { + for (b in blocks) { + if (PlacedCrate.Companion.crateExistsAt(b.location) || + PlacedCrate.Companion.crateExistsAt(b.getRelative(bf!!).location) + ) { + shouldCancel = true + break + } + } + } + return shouldCancel + } +} \ No newline at end of file diff --git a/src/main/kotlin/me/ztowne13/customcrates/listeners/ChatListener.kt b/src/main/kotlin/me/ztowne13/customcrates/listeners/ChatListener.kt new file mode 100644 index 0000000..1e38483 --- /dev/null +++ b/src/main/kotlin/me/ztowne13/customcrates/listeners/ChatListener.kt @@ -0,0 +1,68 @@ +package me.ztowne13.customcrates.listeners + +import org.bukkit.Bukkit +import java.lang.Runnable +import org.bukkit.event.EventPriority +import org.bukkit.event.player.AsyncPlayerChatEvent +import org.bukkit.event.player.PlayerCommandPreprocessEvent +import me.ztowne13.customcrates.SpecialisedCrates +import me.ztowne13.customcrates.players.PlayerManager +import org.bukkit.event.EventHandler +import org.bukkit.event.Listener + +/** + * Created by ztowne13 on 3/15/16. + */ +class ChatListener(var cc: SpecialisedCrates) : Listener { + @EventHandler(priority = EventPriority.LOWEST) + fun onChat(e: AsyncPlayerChatEvent) { + val p = e.player + if (p.hasPermission("me.ztowne13.customcrates.admin") || p.hasPermission("specializedcrates.admin")) { + val pm: PlayerManager = PlayerManager.Companion.get(cc, p) + if (pm.isInOpenMenu) { + val menu = pm.openMenu + if (menu!!.isInInputMenu) { + val msg = e.message + val im = menu.inputMenu + Bukkit.getScheduler().runTaskLater(cc, Runnable { + im!!.runFor(menu, msg) + p.sendMessage(ChatUtils.toChatColor(" &7&l> &f$msg")) + }, 1) + e.recipients.clear() + e.isCancelled = true + } + } + } + } + + @EventHandler + fun onCmiReloadListener(event: PlayerCommandPreprocessEvent) { + val player = event.player + if (player.hasPermission("me.ztowne13.customcrates.admin") || player.hasPermission("specializedcrates.admin")) { + if (cc.settings!!.infoToLog.containsKey("Hologram Plugin") && + cc.settings!!.infoToLog["Hologram Plugin"].equals("CMI", ignoreCase = true) + ) { + val split = event.message.split(" ").toTypedArray() + if (split.size >= 2) { + if (split[0].equals("/cmi", ignoreCase = true) || split[0].equals("/cmi:cmi", ignoreCase = true)) { + if (split[1].equals("reload", ignoreCase = true)) { + Bukkit.getScheduler().scheduleSyncDelayedTask(cc, { + val start = System.currentTimeMillis() + ChatUtils.msgInfo( + player, + "You have executed &c/cmi reload&e. In order to keep holograms on the &6Specialized&7Crates &ecrates, &6Specialized&7Crates &eis also reloading." + ) + cc.reload() + ChatUtils.msgInfo( + player, + "Reloaded the Specialized Crate plugin &7(" + (System.currentTimeMillis() - start) + + "ms)&a." + ) + }, 10) + } + } + } + } + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/me/ztowne13/customcrates/listeners/CommandPreprocessListener.kt b/src/main/kotlin/me/ztowne13/customcrates/listeners/CommandPreprocessListener.kt new file mode 100644 index 0000000..520e00a --- /dev/null +++ b/src/main/kotlin/me/ztowne13/customcrates/listeners/CommandPreprocessListener.kt @@ -0,0 +1,26 @@ +package me.ztowne13.customcrates.listeners + +import org.bukkit.event.player.PlayerCommandPreprocessEvent +import me.ztowne13.customcrates.SpecialisedCrates +import me.ztowne13.customcrates.players.PlayerManager +import org.bukkit.event.EventHandler +import org.bukkit.event.Listener + +/** + * Created by ztowne13 on 3/3/16. + */ +class CommandPreprocessListener(var cc: SpecialisedCrates) : Listener { + @EventHandler + fun onCommandPP(e: PlayerCommandPreprocessEvent) { + val p = e.player + val pm: PlayerManager = PlayerManager.Companion.get(cc, p) + val ct = System.currentTimeMillis() + val diff = ct - pm.cmdCooldown + if (diff < 1000 && !pm.lastCooldown.equals("cmd", ignoreCase = true)) { + e.isCancelled = true + Messages.WAIT_ONE_SECOND.msgSpecified(cc, p) + } + pm.lastCooldown = "cmd" + pm.cmdCooldown = ct + } +} \ No newline at end of file diff --git a/src/main/kotlin/me/ztowne13/customcrates/listeners/DamageListener.kt b/src/main/kotlin/me/ztowne13/customcrates/listeners/DamageListener.kt new file mode 100644 index 0000000..856f517 --- /dev/null +++ b/src/main/kotlin/me/ztowne13/customcrates/listeners/DamageListener.kt @@ -0,0 +1,19 @@ +package me.ztowne13.customcrates.listeners + +import org.bukkit.event.entity.EntityDamageByEntityEvent +import me.ztowne13.customcrates.SpecialisedCrates +import org.bukkit.event.EventHandler +import org.bukkit.event.Listener + +class DamageListener(var sc: SpecialisedCrates) : Listener { + @EventHandler + fun onFireworkExplode(event: EntityDamageByEntityEvent) { + if (event.damager.customName != null) { + if (event.damager.customName.equals("scf", ignoreCase = true)) { + if (!event.damager.isCustomNameVisible) { + event.isCancelled = true + } + } + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/me/ztowne13/customcrates/listeners/InteractListener.kt b/src/main/kotlin/me/ztowne13/customcrates/listeners/InteractListener.kt new file mode 100644 index 0000000..52a7f31 --- /dev/null +++ b/src/main/kotlin/me/ztowne13/customcrates/listeners/InteractListener.kt @@ -0,0 +1,62 @@ +package me.ztowne13.customcrates.listeners + +import org.bukkit.event.EventPriority +import org.bukkit.event.player.PlayerInteractEvent +import me.ztowne13.customcrates.SpecialisedCrates +import me.ztowne13.customcrates.crates.Crate +import me.ztowne13.customcrates.crates.crateaction.AttemptKeyUseAction +import me.ztowne13.customcrates.crates.crateaction.CrateAction +import me.ztowne13.customcrates.crates.crateaction.LeftClickAction +import org.bukkit.event.EventHandler +import org.bukkit.event.Listener +import org.bukkit.event.block.* + +class InteractListener(var cc: SpecialisedCrates) : Listener { + @EventHandler(priority = EventPriority.LOWEST) + fun onInteract(e: PlayerInteractEvent) { + cc.debugUtils!!.log("onInteract - CALL", this.javaClass) + cc.debugUtils!!.log("onInteract - (cancelled: " + e.isCancelled + ")", javaClass) + val p = e.player + + // Handle crate left or right click + if (e.action == Action.RIGHT_CLICK_BLOCK || e.action == Action.LEFT_CLICK_BLOCK) { + cc.debugUtils!!.log("onInteract - Click block", this.javaClass) + val action: CrateAction + if (e.action == Action.RIGHT_CLICK_BLOCK) { + action = AttemptKeyUseAction(cc, p, e.clickedBlock!!.location) + cc.debugUtils!!.log("onInteract - is right click block", javaClass) + } else { + action = LeftClickAction(cc, p, e.clickedBlock!!.location) + } + val result = action.run() + if (result) { + cc.debugUtils!!.log("onInteract - Cancelling", javaClass) + e.isCancelled = true + } + } + + // Prevent crate keys from being used for anything else (enderpearls not being throw, etc.) + if (e.item != null) { + for (crate in Crate.Companion.getLoadedCrates().values) { + if (crate.settings.keyItemHandler!!.keyMatchesToStack(e.item, false)) { + if (!((SettingsValue.KEY_ALLOW_LEFT_CLICK_INTERACTION.getValue(cc) as Boolean) && e.action == Action.LEFT_CLICK_BLOCK)) { + e.isCancelled = true + } + } + } + } + } + + @EventHandler + fun onKeyPreviewMenu(event: PlayerInteractEvent) { + val action = event.action + if (action == Action.LEFT_CLICK_BLOCK || action == Action.LEFT_CLICK_AIR) { + if ((SettingsValue.LEFT_CLICK_KEY_PREVIEW.getValue(cc) as Boolean)) { + val crate = CrateUtils.searchByKey(event.item) + if (crate != null) { + crate.settings.displayer!!.openFor(event.player) + } + } + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/me/ztowne13/customcrates/listeners/InventoryActionListener.kt b/src/main/kotlin/me/ztowne13/customcrates/listeners/InventoryActionListener.kt new file mode 100644 index 0000000..7a54d00 --- /dev/null +++ b/src/main/kotlin/me/ztowne13/customcrates/listeners/InventoryActionListener.kt @@ -0,0 +1,276 @@ +package me.ztowne13.customcrates.listeners + +import org.bukkit.entity.Player +import org.bukkit.Material +import org.bukkit.Bukkit +import java.lang.Runnable +import org.bukkit.event.inventory.InventoryType +import org.bukkit.event.inventory.ClickType +import org.bukkit.event.inventory.InventoryDragEvent +import org.bukkit.event.inventory.InventoryClickEvent +import org.bukkit.event.inventory.InventoryCloseEvent +import me.ztowne13.customcrates.SpecialisedCrates +import me.ztowne13.customcrates.crates.types.animations.CrateAnimation +import me.ztowne13.customcrates.interfaces.igc.crates.IGCMultiCrateMain +import me.ztowne13.customcrates.interfaces.igc.crates.previeweditor.IGCCratePreviewEditor +import me.ztowne13.customcrates.interfaces.igc.fileconfigs.rewards.IGCDragAndDrop +import me.ztowne13.customcrates.interfaces.items.ItemBuilder +import me.ztowne13.customcrates.players.PlayerManager +import org.bukkit.event.EventHandler +import org.bukkit.event.Listener +import org.bukkit.inventory.Inventory +import java.lang.Exception + +class InventoryActionListener(var cc: SpecialisedCrates) : Listener { + @EventHandler + fun onInventoryDrag(e: InventoryDragEvent) { + cc.debugUtils!!.log("onInventoryDrag - CALL", javaClass) + val player = e.whoClicked as Player + val playerManager: PlayerManager = PlayerManager.Companion.get(cc, player) + if (playerManager.isInCrate || playerManager.isInRewardMenu) { + cc.debugUtils!!.log("onInventoryDrag - CANCELLED") + e.isCancelled = true + } else if (playerManager.isInOpenMenu) { + if (e.view.topInventory != null) { + if (playerManager.openMenu is IGCCratePreviewEditor && e.rawSlots == e.inventorySlots) { + try { + for (slot in e.inventorySlots) (playerManager.openMenu as IGCCratePreviewEditor) + .manageClick(slot, true, e.newItems.values.iterator().next()) + e.isCancelled = true + } catch (exc: Exception) { + exc.printStackTrace() + } + } + } + } + } + + @EventHandler + fun onInventoryClick(e: InventoryClickEvent) { + val p = e.whoClicked as Player + val pm: PlayerManager = PlayerManager.Companion.get(cc, p) + val slot = e.slot + if (pm.isInCrate || pm.isInRewardMenu) { + e.isCancelled = true + if (isntPlayerInventory(e, pm)) { + if (pm.isInRewardMenu && pm.lastPage != null) { + pm.lastPage!!.handleInput(p, e.slot) + } + + // Handle multicrate click + if (pm.isInCrate && pm.openCrate!!.isMultiCrate) { + val crate = pm.openCrate + crate!!.settings.multiCrateSettings!!.checkClick(pm, slot, e.click) + e.isCancelled = true + } else if (pm.isInCrate) { + pm.openCrate!!.settings.crateAnimation!! + .handleClick(pm.currentAnimation, slot) + } + } + } + + /*if (pm.isWaitingForClose()) + { + e.setCancelled(true); + pm.closeCrate(); + for (Reward r : pm.getWaitingForClose()) + { + r.runCommands(p); + } + pm.setWaitingForClose(null); + p.closeInventory(); + }*/ + } + + /** + * Handles anvil crafting - mainly to prevent key/crate renaming. + * + * @param e The event passed by the server + */ + @EventHandler + fun onAnvilClick(e: InventoryClickEvent) { + if (e.inventory.type == InventoryType.ANVIL) { + if (e.inventory.getItem(2) != null) { + val builder = ItemBuilder(e.inventory.getItem(2)) + if (builder.hasDisplayName()) { + if (searchByCrate(builder.stack) != null || CrateUtils.searchByKey(builder.stack) != null) { + e.isCancelled = true + e.whoClicked.closeInventory() + Messages.CANT_CRAFT_KEYS.msgSpecified(cc, e.whoClicked as Player) + } + } + } + } + } + + /** + * Handles inventory clicks intended in the in-game config inventory editors. + * + * @param e The event passed by the server + */ + @EventHandler + fun onIGCClick(e: InventoryClickEvent) { + val p = e.whoClicked as Player + val pm: PlayerManager = PlayerManager.Companion.get(cc, p) + if ((p.hasPermission("me.ztowne13.customcrates.admin") || p.hasPermission("specializedcrates.admin")) && pm.isInOpenMenu) { + if (!(e.clickedInventory == null || e.view.topInventory == null)) { + if (e.clickedInventory == e.view.topInventory && + !e.view.title.equals(ChatUtils.toChatColor("&c&lClose to save"), ignoreCase = true) + ) { + if (pm.openMenu !is IGCDragAndDrop || e.slot == 52 || e.slot == 53) e.isCancelled = true + try { + pm.openMenu!!.manageClick(e.slot) + } catch (exc: Exception) { + exc.printStackTrace() + } + } + } + } + } + + @EventHandler + fun onCratesClaimClick(e: InventoryClickEvent) { + if (e.whoClicked is Player) { + val player = e.whoClicked as Player + val playerManager: PlayerManager = PlayerManager.Companion.get( + cc, player + ) + if (playerManager.isInCratesClaimMenu) { + if (!(SettingsValue.CRATES_CLAIM_ALLOW_DEPOSIT.getValue(cc) as Boolean)) { + if (e.clickedInventory !== player.inventory && player.itemOnCursor != null && player.itemOnCursor.type != Material.AIR + || e.click != ClickType.LEFT && e.click != ClickType.RIGHT + ) { + e.isCancelled = true + Messages.CRATES_CLAIM_DENY_DEPOSIT_KEYS.msgSpecified(cc, player) + } + } + } + } + } + + @EventHandler + fun onCrateAnimationESCKey(e: InventoryCloseEvent) { + val player = e.player as Player + val pm: PlayerManager = PlayerManager.Companion.get(cc, player) + if (pm.isInCrateAnimation) { + val dataHolder = pm.currentAnimation + dataHolder.crateAnimation.handleKeyPress(dataHolder, CrateAnimation.KeyType.ESC) + } + } + + @EventHandler + fun onCratesClaimClose(e: InventoryCloseEvent) { + if (e.player is Player) { + val player = e.player as Player + val playerManager: PlayerManager = PlayerManager.Companion.get( + cc, player + ) + val dataManager = playerManager.playerDataManager + if (playerManager.isInCratesClaimMenu) { + preventDupeReopen(player, e.inventory, false) + playerManager.isInCratesClaimMenu = false + for (stack in e.inventory.contents) { + if (stack == null || stack.type == Material.AIR) { + continue + } + val result = CrateUtils.searchByKey(stack) + if (result != null) { + dataManager!!.setVirtualCrateKeys( + result, + dataManager.getVCCrateData(result)!!.keys + stack.amount + ) + } else { + Utils.addItemAndDropRest(player, stack) + } + } + } + } + } + + @EventHandler + fun onInventoryClose(e: InventoryCloseEvent) { + val p = e.player as Player + val pm: PlayerManager = PlayerManager.Companion.get(cc, p) + pm.lastPage = null + if (pm.isInOpenMenu && !pm.openMenu!!.isInInputMenu) { + if (e.view.title.equals(ChatUtils.toChatColor("&7&l> &6&lClose to save"), ignoreCase = true)) { + pm.openMenu!!.manageClick(-1) + ChatUtils.msgSuccess( + p, + "Successfully saved all rewards. Please go through and update all of their commands as well as their chance values." + ) + Bukkit.getScheduler().scheduleSyncDelayedTask(cc, { pm.openMenu!!.up() }, 1) + } else if (e.view.title.equals(ChatUtils.toChatColor("&c&lClose to save"), ignoreCase = true)) { + ChatUtils.msgInfo(p, "There are unsaved changes, please remember to save.") + val openMenu = pm.openMenu as IGCMultiCrateMain + openMenu.crates!!.settings.multiCrateSettings!!.updateCrateSpots() + Bukkit.getScheduler().scheduleSyncDelayedTask(cc, { pm.openMenu!!.open() }, 1) + } else if (pm.openMenu is IGCCratePreviewEditor) { + (pm.openMenu as IGCCratePreviewEditor).customRewardDisplayer!! + .saveAllPages() + Bukkit.getScheduler() + .scheduleSyncDelayedTask(cc, { if (pm.openMenu is IGCCratePreviewEditor) pm.openMenu.up() }, 1) + } else if (pm.openMenu !is IGCMultiCrateMain) { + pm.openMenu = null + Bukkit.getScheduler().scheduleSyncDelayedTask(cc, { + if (!pm.isInOpenMenu) { + ChatUtils.msg(p, "&9&lNOTE: &bType &f'/scrates !' &bto reopen to your last config menu!") + } + }, 1) + } + } + + // Close the multicrate + if (pm.isInCrate && !pm.isInRewardMenu) { + if (pm.openCrate != null && pm.openCrate!!.isMultiCrate) { + pm.closeCrate() + preventDupeReopen(p, e.inventory, true) + } + } + + // Handle closing an inventory while the reward preview menu is open + if (pm.isInRewardMenu) { + val cachedOpenCrate = pm.openCrate + val cachedLastOpenedPlacedCrate = pm.lastOpenedPlacedCrate + if (pm.nextPageInventoryCloseGrace <= cc.totalTicks) { + // This is to reopen a multicrate if the reward preview menu was closed + if (pm.isInCrate && pm.openCrate!!.isMultiCrate) { + pm.isInRewardMenu = false + Bukkit.getScheduler().runTaskLater(cc, Runnable { + cachedOpenCrate!!.settings.multiCrateSettings!!.openFor(p, cachedLastOpenedPlacedCrate) + }, 1) + } else { + pm.isInRewardMenu = false + preventDupeReopen(p, e.inventory, false) + } + } + } + } + + fun preventDupeReopen(player: Player, inventory: Inventory, checkInRewardMenu: Boolean) { + Bukkit.getScheduler().runTaskLater(cc, Runnable { + if (checkInRewardMenu) { + if (PlayerManager.Companion.get(cc, player)!!.isInRewardMenu()) { + return@runTaskLater + } + } + if (inventory.type == InventoryType.CRAFTING) { + return@runTaskLater + } + player.openInventory(inventory) + player.closeInventory() + }, 1) + } + + fun isntPlayerInventory(e: InventoryClickEvent, pm: PlayerManager?): Boolean { + cc.debugUtils!!.log( + "onInventoryClick - In crate or reward menu (" + pm!!.isInCrate + " : " + pm.isInRewardMenu + + ")", javaClass + ) + if (!(e.clickedInventory == null || e.whoClicked.inventory == null)) { + cc.debugUtils!!.log("onInventoryClick - Clicked inventory and clicker aren't null.") + return e.clickedInventory != e.whoClicked.inventory + } + return false + } +} \ No newline at end of file diff --git a/src/main/kotlin/me/ztowne13/customcrates/listeners/NPCEventListener.kt b/src/main/kotlin/me/ztowne13/customcrates/listeners/NPCEventListener.kt new file mode 100644 index 0000000..908a7e4 --- /dev/null +++ b/src/main/kotlin/me/ztowne13/customcrates/listeners/NPCEventListener.kt @@ -0,0 +1,27 @@ +package me.ztowne13.customcrates.listeners + +import me.ztowne13.customcrates.SpecialisedCrates +import me.ztowne13.customcrates.crates.crateaction.AttemptKeyUseAction +import me.ztowne13.customcrates.crates.crateaction.LeftClickAction +import net.citizensnpcs.api.event.NPCLeftClickEvent +import net.citizensnpcs.api.event.NPCRightClickEvent +import org.bukkit.event.EventHandler +import org.bukkit.event.Listener + +/** + * Created by ztowne13 on 2/26/16. + */ +class NPCEventListener(var cc: SpecialisedCrates) : Listener { + @EventHandler + fun onNPCClickRight(e: NPCRightClickEvent) { + if (AttemptKeyUseAction(cc, e.clicker, e.npc.storedLocation).run()) { + e.isCancelled = true + } + } + + @EventHandler + fun onNPCClickLeft(e: NPCLeftClickEvent) { + val p = e.clicker + LeftClickAction(cc, p, e.npc.storedLocation).run() + } +} \ No newline at end of file diff --git a/src/main/kotlin/me/ztowne13/customcrates/listeners/PlayerConnectionListener.kt b/src/main/kotlin/me/ztowne13/customcrates/listeners/PlayerConnectionListener.kt new file mode 100644 index 0000000..c72a3c1 --- /dev/null +++ b/src/main/kotlin/me/ztowne13/customcrates/listeners/PlayerConnectionListener.kt @@ -0,0 +1,34 @@ +package me.ztowne13.customcrates.listeners + +import org.bukkit.event.player.PlayerQuitEvent +import me.ztowne13.customcrates.SpecialisedCrates +import me.ztowne13.customcrates.players.PlayerManager +import org.bukkit.event.EventHandler +import org.bukkit.event.Listener + +class PlayerConnectionListener(var cc: SpecialisedCrates) : Listener { + // @EventHandler + // public void adminJoin(PlayerJoinEvent e) + // { + // final Player p = e.getPlayer(); + // PlayerManager.get(cc, p); + // if (p.hasPermission("me.ztowne13.customcrates.admin") && cc.getUpdateChecker().needsUpdate()) + // { + // Bukkit.getScheduler().scheduleSyncDelayedTask(cc, new Runnable() + // { + // @Override + // public void run() + // { + // Messages.NEEDS_UPDATE.msgSpecified(cc, p, new String[]{"%version%"}, + // new String[]{cc.getUpdateChecker().getLatestVersion()}); + // } + // }, 1); + // } + // } + @EventHandler + fun onQuit(e: PlayerQuitEvent) { + cc.debugUtils!!.log("onQuit() - CALL (" + e.player.name + ")", javaClass) + val p = e.player + PlayerManager.Companion.get(cc, p)!!.remove(20) + } +} \ No newline at end of file diff --git a/src/main/kotlin/me/ztowne13/customcrates/listeners/PluginEnableListener.kt b/src/main/kotlin/me/ztowne13/customcrates/listeners/PluginEnableListener.kt new file mode 100644 index 0000000..b42f79e --- /dev/null +++ b/src/main/kotlin/me/ztowne13/customcrates/listeners/PluginEnableListener.kt @@ -0,0 +1,29 @@ +package me.ztowne13.customcrates.listeners + +import org.bukkit.event.server.PluginEnableEvent +import me.ztowne13.customcrates.SpecialisedCrates +import me.ztowne13.customcrates.crates.PlacedCrate +import org.bukkit.event.EventHandler +import org.bukkit.event.Listener + +class PluginEnableListener(var sc: SpecialisedCrates) : Listener { + var toListenHolograms = arrayOf( + "CMI", + "Holographic Displays", + "Holograms" + ) + + @EventHandler + fun onPluginEnable(pluginEnableEvent: PluginEnableEvent) { + for (hologramName in toListenHolograms) { + if (hologramName.equals(pluginEnableEvent.plugin.name, ignoreCase = true)) { + for (crate in PlacedCrate.Companion.getPlacedCrates().values) { + crate.setupHolo(crate.crate, false) + } + } + } + if (pluginEnableEvent.plugin.name.equals("Multiverse-Core", ignoreCase = true)) { + for (s in sc.settings!!.failedPlacedCrate) sc.settings!!.loadCrateFromFile(s) + } + } +} \ No newline at end of file diff --git a/src/main/kotlin/me/ztowne13/customcrates/listeners/TabCompleteListener.kt b/src/main/kotlin/me/ztowne13/customcrates/listeners/TabCompleteListener.kt new file mode 100644 index 0000000..1b2f4c4 --- /dev/null +++ b/src/main/kotlin/me/ztowne13/customcrates/listeners/TabCompleteListener.kt @@ -0,0 +1,153 @@ +package me.ztowne13.customcrates.listeners + +import org.bukkit.entity.Player +import org.bukkit.Bukkit +import me.ztowne13.customcrates.SpecialisedCrates +import me.ztowne13.customcrates.commands.sub.SubCommand +import me.ztowne13.customcrates.crates.Crate +import org.bukkit.command.* +import java.util.ArrayList + +/** + * Created by ztowne13 on 2/19/16. + */ +class TabCompleteListener(var cc: SpecialisedCrates) : TabCompleter { + override fun onTabComplete(sender: CommandSender, cmd: Command, alias: String, args: Array): List? { + var list: MutableList? = ArrayList() + if (sender is Player) { + val player = sender + val cN = cmd.name + if (cN.equals("crates", ignoreCase = true) || + cN.equals("specializedcrates", ignoreCase = true) || + cN.equals("sc", ignoreCase = true) || + cN.equals("scrates", ignoreCase = true) || + cN.equals("ccrates", ignoreCase = true) + ) { + if (args.size == 1) { + if (player.hasPermission("me.ztowne13.customcrates.admin") || player.hasPermission("specializedcratest.admin")) { + list!!.add("config") + list.add("virtualcrates") + list.add("givecrate") + list.add("givekey") + list.add("edit") + list.add("errors") + list.add("deletecrate") + list.add("listcrates") + list.add("listhistory") + list.add("delallcratetype") + list.add("reload") + list.add("info") + list.add("!") + list.add("luckychest") + list.add("forceopen") + list.add("toggleparticles") + list.add("spawncrate") + list.add("claim") + } else { + list!!.add("luckychest") + list.add("claim") + } + list = Utils.onlyLeaveEntriesWithPref(list, args[0]) + } else { + if (SubCommand.Companion.getMappedAliases().containsKey(args[0])) { + args[0] = SubCommand.Companion.getMappedAliases().get(args[0])!! + } + if (args[0].equals("givekey", ignoreCase = true) || args[0].equals( + "givecrate", + ignoreCase = true + ) || + args[0].equals("delallcratetype", ignoreCase = true) + ) { + if (args.size == 2) { + for (crates in Crate.Companion.getLoadedCrates().values) { + list!!.add(crates.name!!) + } + list = Utils.onlyLeaveEntriesWithPref(list, args[1]) + } + if (!args[0].equals("delallcratetype", ignoreCase = true)) { + if (args.size == 3) { + list!!.add("all") + for (p in Bukkit.getOnlinePlayers()) { + list.add(p.name) + } + list = Utils.onlyLeaveEntriesWithPref(list, args[2]) + } else if (args.size == 4) { + list!!.add("1") + list = Utils.onlyLeaveEntriesWithPref(list, "") + } else if (args.size == 5) { + list!!.add("-v") + } + } + } else if (args[0].equals("edit", ignoreCase = true)) { + for (crates in Crate.Companion.getLoadedCrates().values) { + list!!.add(crates.name!!) + } + list = Utils.onlyLeaveEntriesWithPref(list, args[1]) + } else if (args[0].equals("forceopen", ignoreCase = true)) { + if (args.size == 2) { + for (crates in Crate.Companion.getLoadedCrates().values) { + list!!.add(crates.name!!) + } + list = Utils.onlyLeaveEntriesWithPref(list, args[1]) + } + if (args.size == 3) { + list!!.add("all") + for (p in Bukkit.getOnlinePlayers()) { + list.add(p.name) + } + list = Utils.onlyLeaveEntriesWithPref(list, args[2]) + } + } else if (args[0].equals("listhistory", ignoreCase = true)) { + if (args.size == 2) { + for (p in Bukkit.getOnlinePlayers()) { + list!!.add(p.name) + } + list = Utils.onlyLeaveEntriesWithPref(list, args[1]) + } else if (args.size == 3) { + list!!.add("10") + list = Utils.onlyLeaveEntriesWithPref(list, "") + } + } else if (args[0].equals("errors", ignoreCase = true)) { + for (crates in Crate.Companion.getLoadedCrates().values) { + list!!.add(crates.name!!) + } + list = Utils.onlyLeaveEntriesWithPref(list, args[1]) + } else if (args[0].equals("spawncrate", ignoreCase = true)) { + if (args.size == 2) { + for (crates in Crate.Companion.getLoadedCrates().values) { + list!!.add(crates.name!!) + } + list = Utils.onlyLeaveEntriesWithPref(list, args[1]) + } else if (args.size == 3) { + for (world in Bukkit.getWorlds()) { + list!!.add(world.name) + } + list = Utils.onlyLeaveEntriesWithPref(list, args[2]) + } else if (args.size == 4) { + list!!.add("x") + } else if (args.size == 5) { + list!!.add("y") + } else if (args.size == 6) { + list!!.add("z") + } + } + } + } else if (cN.equals("rewards", ignoreCase = true)) { + if (args.size >= 1) { + for (crates in Crate.Companion.getLoadedCrates().values) { + val cs = crates.settings + if (player.hasPermission(cs!!.permission!!) || cs!!.permission.equals( + "no permission", + ignoreCase = true + ) + ) if (!crates.isMultiCrate) list!!.add( + crates.name!! + ) + } + list = Utils.onlyLeaveEntriesWithPref(list, args[0]) + } + } + } + return list + } +} \ No newline at end of file diff --git a/src/main/kotlin/me/ztowne13/customcrates/particles/ParticleHandler.kt b/src/main/kotlin/me/ztowne13/customcrates/particles/ParticleHandler.kt new file mode 100644 index 0000000..af40c40 --- /dev/null +++ b/src/main/kotlin/me/ztowne13/customcrates/particles/ParticleHandler.kt @@ -0,0 +1,4 @@ +package me.ztowne13.customcrates.particles + +class ParticleHandler { +} \ No newline at end of file diff --git a/src/main/kotlin/me/ztowne13/customcrates/players/CratesPlayer.kt b/src/main/kotlin/me/ztowne13/customcrates/players/CratesPlayer.kt new file mode 100644 index 0000000..0f0ed45 --- /dev/null +++ b/src/main/kotlin/me/ztowne13/customcrates/players/CratesPlayer.kt @@ -0,0 +1,4 @@ +package me.ztowne13.customcrates.players + +class CratesPlayer { +} \ No newline at end of file diff --git a/src/main/kotlin/me/ztowne13/customcrates/rewards/Reward.kt b/src/main/kotlin/me/ztowne13/customcrates/rewards/Reward.kt new file mode 100644 index 0000000..ae309b8 --- /dev/null +++ b/src/main/kotlin/me/ztowne13/customcrates/rewards/Reward.kt @@ -0,0 +1,4 @@ +package me.ztowne13.customcrates.rewards + +class Reward { +} \ No newline at end of file diff --git a/src/main/kotlin/me/ztowne13/customcrates/storage/StorageProvider.kt b/src/main/kotlin/me/ztowne13/customcrates/storage/StorageProvider.kt new file mode 100644 index 0000000..685f575 --- /dev/null +++ b/src/main/kotlin/me/ztowne13/customcrates/storage/StorageProvider.kt @@ -0,0 +1,4 @@ +package me.ztowne13.customcrates.storage + +class StorageProvider { +} \ No newline at end of file diff --git a/src/main/kotlin/me/ztowne13/customcrates/utils/Logging.kt b/src/main/kotlin/me/ztowne13/customcrates/utils/Logging.kt new file mode 100644 index 0000000..41973f3 --- /dev/null +++ b/src/main/kotlin/me/ztowne13/customcrates/utils/Logging.kt @@ -0,0 +1,23 @@ +package me.ztowne13.customcrates.utils + +import java.util.logging.Level + +class Logging { + companion object { + fun log(level: Level, msg: String) { + java.util.logging.Logger.getLogger("SpecialisedCrates").log(level, msg) + } + + fun info(msg: String) { + log(Level.INFO, msg) + } + + fun warn(msg: String) { + log(Level.WARNING, msg) + } + + fun severe(msg: String) { + log(Level.SEVERE, msg) + } + } +} \ No newline at end of file diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml index 67454a5..cca9767 100644 --- a/src/main/resources/plugin.yml +++ b/src/main/resources/plugin.yml @@ -1,10 +1,10 @@ -name: ${project.name} -author: ${project.author} -version: ${project.version} -main: ${project.mainClass} +name: SpecialisedCrates +author: [ztowne13, VQ9] +version: @version@ +main: me.ztowne13.customcrates.SpecialisedCrates api-version: 1.13 description: A 100% customizable crate plugin for your server. -softdepend: [HolographicDisplays,IndividualHolograms,Holograms,Citizens,CMI,PlaceholderAPI,Multiverse-Core,Vault] +softdepend: [HolographicDisplays,IndividualHolograms,Holograms,Citizens,PlaceholderAPI,Multiverse-Core,Vault] commands: scrates: description: All commands for the specialized crates plugin.