From af7e1e435f577bbf9742bb526ac00a71a21c219c Mon Sep 17 00:00:00 2001 From: LMBishop <13875753+LMBishop@users.noreply.github.com> Date: Thu, 17 Jun 2021 13:32:02 +0100 Subject: Convert to multi module project - Common module to provide an abstract Quests plugin - Api is still todo --- .../java/com/leonardobishop/quests/Quests.java | 493 ---------------- .../com/leonardobishop/quests/api/QuestsAPI.java | 35 -- .../quests/api/QuestsPlaceholders.java | 334 ----------- .../quests/api/enums/QuestStartResult.java | 13 - .../quests/api/events/PlayerCancelQuestEvent.java | 51 -- .../quests/api/events/PlayerFinishQuestEvent.java | 51 -- .../quests/api/events/PlayerQuestEvent.java | 19 - .../quests/api/events/PlayerStartQuestEvent.java | 51 -- .../api/events/PlayerStartTrackQuestEvent.java | 34 -- .../api/events/PlayerStopTrackQuestEvent.java | 29 - .../quests/api/events/PreStartQuestEvent.java | 57 -- .../com/leonardobishop/quests/blocktype/Block.java | 35 -- .../quests/blocktype/SimilarBlocks.java | 93 --- .../quests/command/QuestsCommand.java | 636 --------------------- .../quests/hook/coreprotect/CoreProtectHook.java | 29 - .../quests/hook/coreprotect/CoreProtectNoHook.java | 10 - .../quests/hook/coreprotect/ICoreProtectHook.java | 16 - .../quests/hook/itemgetter/ItemGetter.java | 48 -- .../quests/hook/itemgetter/ItemGetterLatest.java | 244 -------- .../quests/hook/itemgetter/ItemGetter_1_13.java | 233 -------- .../hook/itemgetter/ItemGetter_Late_1_8.java | 161 ------ .../quests/hook/papi/IPlaceholderAPIHook.java | 14 - .../quests/hook/papi/PlaceholderAPIHook.java | 28 - .../leonardobishop/quests/hook/title/Title.java | 8 - .../quests/hook/title/Title_Bukkit.java | 12 - .../quests/hook/title/Title_BukkitNoTimings.java | 13 - .../quests/hook/title/Title_Other.java | 11 - .../quests/listener/MenuController.java | 49 -- .../quests/listener/PlayerJoinListener.java | 48 -- .../quests/listener/PlayerLeaveListener.java | 26 - .../leonardobishop/quests/menu/CancelQMenu.java | 81 --- .../leonardobishop/quests/menu/CategoryQMenu.java | 168 ------ .../com/leonardobishop/quests/menu/DailyQMenu.java | 98 ---- .../com/leonardobishop/quests/menu/MenuUtil.java | 73 --- .../com/leonardobishop/quests/menu/QItemStack.java | 151 ----- .../java/com/leonardobishop/quests/menu/QMenu.java | 14 - .../com/leonardobishop/quests/menu/QuestQMenu.java | 286 --------- .../quests/menu/QuestSortWrapper.java | 44 -- .../leonardobishop/quests/menu/StartedQMenu.java | 173 ------ .../quests/menu/element/CategoryMenuElement.java | 65 --- .../quests/menu/element/CustomMenuElement.java | 17 - .../quests/menu/element/MenuElement.java | 9 - .../quests/menu/element/QuestMenuElement.java | 114 ---- .../quests/menu/element/SpacerMenuElement.java | 15 - .../com/leonardobishop/quests/player/QPlayer.java | 279 --------- .../quests/player/QPlayerManager.java | 179 ------ .../questprogressfile/QPlayerPreferences.java | 18 - .../player/questprogressfile/QuestProgress.java | 143 ----- .../questprogressfile/QuestProgressFile.java | 257 --------- .../player/questprogressfile/TaskProgress.java | 73 --- .../com/leonardobishop/quests/quest/Category.java | 46 -- .../com/leonardobishop/quests/quest/Quest.java | 133 ----- .../leonardobishop/quests/quest/QuestManager.java | 49 -- .../java/com/leonardobishop/quests/quest/Task.java | 41 -- .../quest/controller/DailyQuestController.java | 186 ------ .../quest/controller/NormalQuestController.java | 239 -------- .../quests/quest/controller/QuestController.java | 15 - .../quests/quest/tasktype/ConfigValue.java | 35 -- .../quests/quest/tasktype/TaskType.java | 116 ---- .../quests/quest/tasktype/TaskTypeManager.java | 69 --- .../quests/quest/tasktype/TaskUtils.java | 89 --- .../quest/tasktype/type/BreedingTaskType.java | 101 ---- .../tasktype/type/BrewingCertainTaskType.java | 114 ---- .../quest/tasktype/type/BrewingTaskType.java | 114 ---- .../tasktype/type/BuildingCertainTaskType.java | 197 ------- .../quest/tasktype/type/BuildingTaskType.java | 85 --- .../quest/tasktype/type/CommandTaskType.java | 99 ---- .../quest/tasktype/type/DealDamageTaskType.java | 93 --- .../quest/tasktype/type/DistancefromTaskType.java | 118 ---- .../quest/tasktype/type/EnchantingTaskType.java | 87 --- .../quest/tasktype/type/ExpEarnTaskType.java | 85 --- .../quest/tasktype/type/FarmingTaskType.java | 96 ---- .../quest/tasktype/type/FishingTaskType.java | 97 ---- .../quest/tasktype/type/InventoryTaskType.java | 183 ------ .../quest/tasktype/type/MilkingTaskType.java | 98 ---- .../quest/tasktype/type/MiningCertainTaskType.java | 211 ------- .../quests/quest/tasktype/type/MiningTaskType.java | 88 --- .../tasktype/type/MobkillingCertainTaskType.java | 145 ----- .../quest/tasktype/type/MobkillingTaskType.java | 116 ---- .../quest/tasktype/type/PermissionTaskType.java | 76 --- .../quest/tasktype/type/PlayerkillingTaskType.java | 97 ---- .../quest/tasktype/type/PlaytimeTaskType.java | 95 --- .../quest/tasktype/type/PositionTaskType.java | 108 ---- .../quest/tasktype/type/ShearingTaskType.java | 93 --- .../quests/quest/tasktype/type/TamingTaskType.java | 92 --- .../quest/tasktype/type/WalkingTaskType.java | 92 --- .../type/dependent/ASkyBlockLevelType.java | 72 --- .../type/dependent/BentoBoxLevelTaskType.java | 105 ---- .../type/dependent/CitizensDeliverTaskType.java | 150 ----- .../type/dependent/CitizensInteractTaskType.java | 76 --- .../type/dependent/EssentialsBalanceTaskType.java | 101 ---- .../dependent/EssentialsMoneyEarnTaskType.java | 80 --- .../type/dependent/IridiumSkyblockValueType.java | 85 --- .../type/dependent/MythicMobsKillingType.java | 115 ---- .../dependent/PlaceholderAPIEvaluateTaskType.java | 162 ------ .../dependent/ShopGUIPlusBuyCertainTaskType.java | 82 --- .../dependent/ShopGUIPlusSellCertainTaskType.java | 82 --- .../type/dependent/uSkyBlockLevelType.java | 74 --- .../quests/storage/MySqlStorageProvider.java | 278 --------- .../quests/storage/StorageProvider.java | 14 - .../quests/storage/YamlStorageProvider.java | 137 ----- .../com/leonardobishop/quests/updater/Updater.java | 74 --- .../java/com/leonardobishop/quests/util/Items.java | 36 -- .../com/leonardobishop/quests/util/Messages.java | 76 --- .../com/leonardobishop/quests/util/Options.java | 93 --- .../leonardobishop/quests/util/QuestCompleter.java | 99 ---- .../com/leonardobishop/quests/util/QuestMode.java | 8 - .../quests/util/QuestsAutosaveRunnable.java | 45 -- .../quests/util/QuestsConfigLoader.java | 454 --------------- .../leonardobishop/quests/util/QuestsLogger.java | 85 --- src/main/resources/config.yml | 355 ------------ src/main/resources/plugin.yml | 30 - src/main/resources/quests/README.txt | 40 -- src/main/resources/quests/example1.yml | 61 -- src/main/resources/quests/example2.yml | 47 -- src/main/resources/quests/example3.yml | 49 -- src/main/resources/quests/example4.yml | 50 -- src/main/resources/quests/example5.yml | 38 -- src/main/resources/quests/example6.yml | 35 -- src/main/resources/quests/example7.yml | 37 -- 120 files changed, 12261 deletions(-) delete mode 100644 src/main/java/com/leonardobishop/quests/Quests.java delete mode 100644 src/main/java/com/leonardobishop/quests/api/QuestsAPI.java delete mode 100644 src/main/java/com/leonardobishop/quests/api/QuestsPlaceholders.java delete mode 100644 src/main/java/com/leonardobishop/quests/api/enums/QuestStartResult.java delete mode 100644 src/main/java/com/leonardobishop/quests/api/events/PlayerCancelQuestEvent.java delete mode 100644 src/main/java/com/leonardobishop/quests/api/events/PlayerFinishQuestEvent.java delete mode 100644 src/main/java/com/leonardobishop/quests/api/events/PlayerQuestEvent.java delete mode 100644 src/main/java/com/leonardobishop/quests/api/events/PlayerStartQuestEvent.java delete mode 100644 src/main/java/com/leonardobishop/quests/api/events/PlayerStartTrackQuestEvent.java delete mode 100644 src/main/java/com/leonardobishop/quests/api/events/PlayerStopTrackQuestEvent.java delete mode 100644 src/main/java/com/leonardobishop/quests/api/events/PreStartQuestEvent.java delete mode 100644 src/main/java/com/leonardobishop/quests/blocktype/Block.java delete mode 100644 src/main/java/com/leonardobishop/quests/blocktype/SimilarBlocks.java delete mode 100644 src/main/java/com/leonardobishop/quests/command/QuestsCommand.java delete mode 100644 src/main/java/com/leonardobishop/quests/hook/coreprotect/CoreProtectHook.java delete mode 100644 src/main/java/com/leonardobishop/quests/hook/coreprotect/CoreProtectNoHook.java delete mode 100644 src/main/java/com/leonardobishop/quests/hook/coreprotect/ICoreProtectHook.java delete mode 100644 src/main/java/com/leonardobishop/quests/hook/itemgetter/ItemGetter.java delete mode 100644 src/main/java/com/leonardobishop/quests/hook/itemgetter/ItemGetterLatest.java delete mode 100644 src/main/java/com/leonardobishop/quests/hook/itemgetter/ItemGetter_1_13.java delete mode 100644 src/main/java/com/leonardobishop/quests/hook/itemgetter/ItemGetter_Late_1_8.java delete mode 100644 src/main/java/com/leonardobishop/quests/hook/papi/IPlaceholderAPIHook.java delete mode 100644 src/main/java/com/leonardobishop/quests/hook/papi/PlaceholderAPIHook.java delete mode 100644 src/main/java/com/leonardobishop/quests/hook/title/Title.java delete mode 100644 src/main/java/com/leonardobishop/quests/hook/title/Title_Bukkit.java delete mode 100644 src/main/java/com/leonardobishop/quests/hook/title/Title_BukkitNoTimings.java delete mode 100644 src/main/java/com/leonardobishop/quests/hook/title/Title_Other.java delete mode 100644 src/main/java/com/leonardobishop/quests/listener/MenuController.java delete mode 100644 src/main/java/com/leonardobishop/quests/listener/PlayerJoinListener.java delete mode 100644 src/main/java/com/leonardobishop/quests/listener/PlayerLeaveListener.java delete mode 100644 src/main/java/com/leonardobishop/quests/menu/CancelQMenu.java delete mode 100644 src/main/java/com/leonardobishop/quests/menu/CategoryQMenu.java delete mode 100644 src/main/java/com/leonardobishop/quests/menu/DailyQMenu.java delete mode 100644 src/main/java/com/leonardobishop/quests/menu/MenuUtil.java delete mode 100644 src/main/java/com/leonardobishop/quests/menu/QItemStack.java delete mode 100644 src/main/java/com/leonardobishop/quests/menu/QMenu.java delete mode 100644 src/main/java/com/leonardobishop/quests/menu/QuestQMenu.java delete mode 100644 src/main/java/com/leonardobishop/quests/menu/QuestSortWrapper.java delete mode 100644 src/main/java/com/leonardobishop/quests/menu/StartedQMenu.java delete mode 100644 src/main/java/com/leonardobishop/quests/menu/element/CategoryMenuElement.java delete mode 100644 src/main/java/com/leonardobishop/quests/menu/element/CustomMenuElement.java delete mode 100644 src/main/java/com/leonardobishop/quests/menu/element/MenuElement.java delete mode 100644 src/main/java/com/leonardobishop/quests/menu/element/QuestMenuElement.java delete mode 100644 src/main/java/com/leonardobishop/quests/menu/element/SpacerMenuElement.java delete mode 100644 src/main/java/com/leonardobishop/quests/player/QPlayer.java delete mode 100644 src/main/java/com/leonardobishop/quests/player/QPlayerManager.java delete mode 100644 src/main/java/com/leonardobishop/quests/player/questprogressfile/QPlayerPreferences.java delete mode 100644 src/main/java/com/leonardobishop/quests/player/questprogressfile/QuestProgress.java delete mode 100644 src/main/java/com/leonardobishop/quests/player/questprogressfile/QuestProgressFile.java delete mode 100644 src/main/java/com/leonardobishop/quests/player/questprogressfile/TaskProgress.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/Category.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/Quest.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/QuestManager.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/Task.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/controller/DailyQuestController.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/controller/NormalQuestController.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/controller/QuestController.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/ConfigValue.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/TaskType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/TaskTypeManager.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/TaskUtils.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/BreedingTaskType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/BrewingCertainTaskType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/BrewingTaskType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/BuildingCertainTaskType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/BuildingTaskType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/CommandTaskType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/DealDamageTaskType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/DistancefromTaskType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/EnchantingTaskType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/ExpEarnTaskType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/FarmingTaskType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/FishingTaskType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/InventoryTaskType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/MilkingTaskType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/MiningCertainTaskType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/MiningTaskType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/MobkillingCertainTaskType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/MobkillingTaskType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/PermissionTaskType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/PlayerkillingTaskType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/PlaytimeTaskType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/PositionTaskType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/ShearingTaskType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/TamingTaskType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/WalkingTaskType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/ASkyBlockLevelType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/BentoBoxLevelTaskType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/CitizensDeliverTaskType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/CitizensInteractTaskType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/EssentialsBalanceTaskType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/EssentialsMoneyEarnTaskType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/IridiumSkyblockValueType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/MythicMobsKillingType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/PlaceholderAPIEvaluateTaskType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/ShopGUIPlusBuyCertainTaskType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/ShopGUIPlusSellCertainTaskType.java delete mode 100644 src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/uSkyBlockLevelType.java delete mode 100644 src/main/java/com/leonardobishop/quests/storage/MySqlStorageProvider.java delete mode 100644 src/main/java/com/leonardobishop/quests/storage/StorageProvider.java delete mode 100644 src/main/java/com/leonardobishop/quests/storage/YamlStorageProvider.java delete mode 100644 src/main/java/com/leonardobishop/quests/updater/Updater.java delete mode 100644 src/main/java/com/leonardobishop/quests/util/Items.java delete mode 100644 src/main/java/com/leonardobishop/quests/util/Messages.java delete mode 100644 src/main/java/com/leonardobishop/quests/util/Options.java delete mode 100644 src/main/java/com/leonardobishop/quests/util/QuestCompleter.java delete mode 100644 src/main/java/com/leonardobishop/quests/util/QuestMode.java delete mode 100644 src/main/java/com/leonardobishop/quests/util/QuestsAutosaveRunnable.java delete mode 100644 src/main/java/com/leonardobishop/quests/util/QuestsConfigLoader.java delete mode 100644 src/main/java/com/leonardobishop/quests/util/QuestsLogger.java delete mode 100644 src/main/resources/config.yml delete mode 100644 src/main/resources/plugin.yml delete mode 100644 src/main/resources/quests/README.txt delete mode 100644 src/main/resources/quests/example1.yml delete mode 100644 src/main/resources/quests/example2.yml delete mode 100644 src/main/resources/quests/example3.yml delete mode 100644 src/main/resources/quests/example4.yml delete mode 100644 src/main/resources/quests/example5.yml delete mode 100644 src/main/resources/quests/example6.yml delete mode 100644 src/main/resources/quests/example7.yml (limited to 'src') diff --git a/src/main/java/com/leonardobishop/quests/Quests.java b/src/main/java/com/leonardobishop/quests/Quests.java deleted file mode 100644 index db842b0c..00000000 --- a/src/main/java/com/leonardobishop/quests/Quests.java +++ /dev/null @@ -1,493 +0,0 @@ -package com.leonardobishop.quests; - -import com.leonardobishop.quests.command.QuestsCommand; -import com.leonardobishop.quests.listener.PlayerJoinListener; -import com.leonardobishop.quests.listener.PlayerLeaveListener; -import com.leonardobishop.quests.listener.MenuController; -import com.leonardobishop.quests.hook.coreprotect.CoreProtectHook; -import com.leonardobishop.quests.hook.coreprotect.CoreProtectNoHook; -import com.leonardobishop.quests.hook.coreprotect.ICoreProtectHook; -import com.leonardobishop.quests.hook.itemgetter.ItemGetter; -import com.leonardobishop.quests.hook.itemgetter.ItemGetterLatest; -import com.leonardobishop.quests.hook.itemgetter.ItemGetter_1_13; -import com.leonardobishop.quests.hook.itemgetter.ItemGetter_Late_1_8; -import com.leonardobishop.quests.hook.papi.IPlaceholderAPIHook; -import com.leonardobishop.quests.hook.papi.PlaceholderAPIHook; -import com.leonardobishop.quests.hook.title.Title; -import com.leonardobishop.quests.hook.title.Title_Bukkit; -import com.leonardobishop.quests.hook.title.Title_BukkitNoTimings; -import com.leonardobishop.quests.hook.title.Title_Other; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.QPlayerManager; -import com.leonardobishop.quests.quest.QuestManager; -import com.leonardobishop.quests.quest.controller.NormalQuestController; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskTypeManager; -import com.leonardobishop.quests.quest.tasktype.type.BreedingTaskType; -import com.leonardobishop.quests.quest.tasktype.type.BrewingTaskType; -import com.leonardobishop.quests.quest.tasktype.type.BuildingCertainTaskType; -import com.leonardobishop.quests.quest.tasktype.type.BuildingTaskType; -import com.leonardobishop.quests.quest.tasktype.type.CommandTaskType; -import com.leonardobishop.quests.quest.tasktype.type.DealDamageTaskType; -import com.leonardobishop.quests.quest.tasktype.type.DistancefromTaskType; -import com.leonardobishop.quests.quest.tasktype.type.EnchantingTaskType; -import com.leonardobishop.quests.quest.tasktype.type.ExpEarnTaskType; -import com.leonardobishop.quests.quest.tasktype.type.FishingTaskType; -import com.leonardobishop.quests.quest.tasktype.type.InventoryTaskType; -import com.leonardobishop.quests.quest.tasktype.type.MilkingTaskType; -import com.leonardobishop.quests.quest.tasktype.type.MiningCertainTaskType; -import com.leonardobishop.quests.quest.tasktype.type.MiningTaskType; -import com.leonardobishop.quests.quest.tasktype.type.MobkillingCertainTaskType; -import com.leonardobishop.quests.quest.tasktype.type.MobkillingTaskType; -import com.leonardobishop.quests.quest.tasktype.type.PermissionTaskType; -import com.leonardobishop.quests.quest.tasktype.type.PlayerkillingTaskType; -import com.leonardobishop.quests.quest.tasktype.type.PlaytimeTaskType; -import com.leonardobishop.quests.quest.tasktype.type.PositionTaskType; -import com.leonardobishop.quests.quest.tasktype.type.ShearingTaskType; -import com.leonardobishop.quests.quest.tasktype.type.TamingTaskType; -import com.leonardobishop.quests.quest.tasktype.type.WalkingTaskType; -import com.leonardobishop.quests.quest.tasktype.type.dependent.ASkyBlockLevelType; -import com.leonardobishop.quests.quest.tasktype.type.dependent.BentoBoxLevelTaskType; -import com.leonardobishop.quests.quest.tasktype.type.dependent.CitizensDeliverTaskType; -import com.leonardobishop.quests.quest.tasktype.type.dependent.CitizensInteractTaskType; -import com.leonardobishop.quests.quest.tasktype.type.dependent.EssentialsBalanceTaskType; -import com.leonardobishop.quests.quest.tasktype.type.dependent.EssentialsMoneyEarnTaskType; -import com.leonardobishop.quests.quest.tasktype.type.dependent.IridiumSkyblockValueType; -import com.leonardobishop.quests.quest.tasktype.type.dependent.MythicMobsKillingType; -import com.leonardobishop.quests.quest.tasktype.type.dependent.PlaceholderAPIEvaluateTaskType; -import com.leonardobishop.quests.quest.tasktype.type.dependent.ShopGUIPlusBuyCertainTaskType; -import com.leonardobishop.quests.quest.tasktype.type.dependent.ShopGUIPlusSellCertainTaskType; -import com.leonardobishop.quests.quest.tasktype.type.dependent.uSkyBlockLevelType; -import com.leonardobishop.quests.updater.Updater; -import com.leonardobishop.quests.util.Messages; -import com.leonardobishop.quests.util.QuestCompleter; -import com.leonardobishop.quests.util.QuestMode; -import com.leonardobishop.quests.util.QuestsAutosaveRunnable; -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.util.QuestsLogger; -import org.bstats.bukkit.MetricsLite; -import org.bukkit.Bukkit; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.plugin.java.JavaPlugin; -import org.bukkit.scheduler.BukkitTask; - -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.ArrayList; - -public class Quests extends JavaPlugin { - - private static Quests instance; - - /** Handles anything to do with loaded quests */ - private QuestManager questManager; - /** Handles anything to do with task types */ - private TaskTypeManager taskTypeManager; - /** Handles anything to do with players */ - private QPlayerManager qPlayerManager; - - /** Checks and records ready plugin updates */ - private Updater updater; - /** Abstract title handle to allow for cross version compatibility */ - private Title titleHandle; - /** Abstract item handle to allow for cross version compatibility */ - private ItemGetter itemGetter; - /** Task which checks quests and marks them as complete if requirements are satisfied */ - private QuestCompleter questCompleter; - /** Loads configurations and tracks errors */ - private QuestsConfigLoader questsConfigLoader; - /** Quests logger to allow for configurable logging levels */ - private QuestsLogger questsLogger; - /** Handles menu tracking and clicks */ - private MenuController menuController; - - private IPlaceholderAPIHook placeholderAPIHook; - private ICoreProtectHook coreProtectHook; - - /** If true, the plugin should be inoperable */ - private boolean brokenConfig = false; - private BukkitTask questAutosaveTask; - private BukkitTask questQueuePollTask; - private QuestMode questMode; - - public static Quests get() { - return instance; - } - - public QuestManager getQuestManager() { - return questManager; - } - - public QPlayerManager getPlayerManager() { - return qPlayerManager; - } - - public TaskTypeManager getTaskTypeManager() { - return taskTypeManager; - } - - public boolean isBrokenConfig() { - return brokenConfig; - } - - public void setBrokenConfig(boolean brokenConfig) { - this.brokenConfig = brokenConfig; - } - - public Title getTitleHandle() { - return titleHandle; - } - - public Updater getUpdater() { - return updater; - } - - public QuestsConfigLoader getQuestsConfigLoader() { - return questsConfigLoader; - } - - public MenuController getMenuController() { - return menuController; - } - - public QuestMode getQuestMode() { - return questMode; - } - - public void setQuestMode(QuestMode questMode) { - this.questMode = questMode; - } - - public String convertToFormat(long m) { //seconds please - long hours = m / 3600; - long minutes = (m % 3600) / 60; - long seconds = ((m % 3600) % 60) % 60; - - return Messages.TIME_FORMAT.getMessage() - .replace("{hours}", String.format("%02d", hours)) - .replace("{minutes}", String.format("%02d", minutes)) - .replace("{seconds}", String.format("%02d", seconds)); - } - - @Override - public void onEnable() { - instance = this; - questMode = QuestMode.NORMAL; - - questsLogger = new QuestsLogger(this, QuestsLogger.LoggingLevel.INFO); - questCompleter = new QuestCompleter(this); - - this.generateConfigurations(); - this.setupVersionSpecific(); - - taskTypeManager = new TaskTypeManager(this); - questManager = new QuestManager(this); - qPlayerManager = new QPlayerManager(this); - menuController = new MenuController(this); - - super.getCommand("quests").setExecutor(new QuestsCommand(this)); - Bukkit.getPluginManager().registerEvents(new PlayerJoinListener(this), this); - Bukkit.getPluginManager().registerEvents(menuController, this); - Bukkit.getPluginManager().registerEvents(new PlayerLeaveListener(this), this); - - MetricsLite metrics = new MetricsLite(this, 3443); - if (metrics.isEnabled()) { - this.getQuestsLogger().info("Metrics started. This can be disabled at /plugins/bStats/config.yml."); - } - - questsConfigLoader = new QuestsConfigLoader(this); - - // register task types after the server has fully started - Bukkit.getScheduler().runTask(this, () -> { - taskTypeManager.registerTaskType(new MiningTaskType()); - taskTypeManager.registerTaskType(new MiningCertainTaskType(this)); - taskTypeManager.registerTaskType(new BuildingTaskType()); - taskTypeManager.registerTaskType(new BuildingCertainTaskType()); - taskTypeManager.registerTaskType(new MobkillingTaskType()); - taskTypeManager.registerTaskType(new MobkillingCertainTaskType()); - taskTypeManager.registerTaskType(new PlayerkillingTaskType()); - taskTypeManager.registerTaskType(new FishingTaskType()); - taskTypeManager.registerTaskType(new InventoryTaskType(this)); - taskTypeManager.registerTaskType(new WalkingTaskType()); - taskTypeManager.registerTaskType(new TamingTaskType()); - taskTypeManager.registerTaskType(new MilkingTaskType()); - taskTypeManager.registerTaskType(new ShearingTaskType()); - taskTypeManager.registerTaskType(new PositionTaskType()); - taskTypeManager.registerTaskType(new PlaytimeTaskType(this)); - taskTypeManager.registerTaskType(new BrewingTaskType()); - taskTypeManager.registerTaskType(new ExpEarnTaskType()); - taskTypeManager.registerTaskType(new BreedingTaskType()); - taskTypeManager.registerTaskType(new EnchantingTaskType()); - taskTypeManager.registerTaskType(new DealDamageTaskType()); - taskTypeManager.registerTaskType(new PermissionTaskType(this)); - taskTypeManager.registerTaskType(new DistancefromTaskType()); - taskTypeManager.registerTaskType(new CommandTaskType()); - // TODO: FIX - // taskTypeManager.registerTaskType(new BrewingCertainTaskType()); - if (Bukkit.getPluginManager().isPluginEnabled("ASkyBlock")) { - taskTypeManager.registerTaskType(new ASkyBlockLevelType()); - } - if (Bukkit.getPluginManager().isPluginEnabled("BentoBox")) { - BentoBoxLevelTaskType.register(taskTypeManager); - } - if (Bukkit.getPluginManager().isPluginEnabled("IridiumSkyblock")) { - taskTypeManager.registerTaskType(new IridiumSkyblockValueType()); - } - if (Bukkit.getPluginManager().isPluginEnabled("uSkyBlock")) { - taskTypeManager.registerTaskType(new uSkyBlockLevelType()); - } - if (Bukkit.getPluginManager().isPluginEnabled("Citizens")) { - taskTypeManager.registerTaskType(new CitizensDeliverTaskType(this)); - taskTypeManager.registerTaskType(new CitizensInteractTaskType()); - } - if (Bukkit.getPluginManager().isPluginEnabled("MythicMobs")) { - taskTypeManager.registerTaskType(new MythicMobsKillingType()); - } - if (Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")) { - taskTypeManager.registerTaskType(new PlaceholderAPIEvaluateTaskType(this)); - } - if (Bukkit.getPluginManager().isPluginEnabled("Essentials")) { - taskTypeManager.registerTaskType(new EssentialsMoneyEarnTaskType()); - taskTypeManager.registerTaskType(new EssentialsBalanceTaskType()); - } - if (Bukkit.getPluginManager().isPluginEnabled("ShopGUIPlus")) { - // not tested - taskTypeManager.registerTaskType(new ShopGUIPlusBuyCertainTaskType()); - taskTypeManager.registerTaskType(new ShopGUIPlusSellCertainTaskType()); - } - - taskTypeManager.closeRegistrations(); - reloadQuests(); - - for (Player player : Bukkit.getOnlinePlayers()) { - qPlayerManager.loadPlayer(player.getUniqueId()); - } - }); - - if (Bukkit.getPluginManager().isPluginEnabled("PlaceholderAPI")) { - this.placeholderAPIHook = new PlaceholderAPIHook(); - this.placeholderAPIHook.registerExpansion(this); - } - - if (Bukkit.getPluginManager().isPluginEnabled("CoreProtect")) { - this.coreProtectHook = new CoreProtectHook(); - } else { - this.coreProtectHook = new CoreProtectNoHook(); - } - - // this intentionally should not be documented - boolean ignoreUpdates = false; - try { - ignoreUpdates = new File(this.getDataFolder() + File.separator + "stfuQuestsUpdate").exists(); - } catch (Throwable ignored) { } - - - updater = new Updater(this, !ignoreUpdates); - if (!ignoreUpdates) { - Bukkit.getScheduler().runTaskAsynchronously(this, () -> { - updater.check(); - }); - } - } - - public IPlaceholderAPIHook getPlaceholderAPIHook() { - return placeholderAPIHook; - } - - public ICoreProtectHook getCoreProtectHook() { - return coreProtectHook; - } - - @Override - public void onDisable() { - for (TaskType taskType : getTaskTypeManager().getTaskTypes()) { - try { - taskType.onDisable(); - } catch (Exception ignored) { } - } - for (QPlayer qPlayer : qPlayerManager.getQPlayers()) { - try { - qPlayerManager.savePlayerSync(qPlayer.getPlayerUUID()); - } catch (Exception ignored) { } - } - if (placeholderAPIHook != null) placeholderAPIHook.unregisterExpansion(); - try { - qPlayerManager.getStorageProvider().shutdown(); - } catch (Exception ignored) { } - } - - public void reloadQuests() { - questManager.getQuests().clear(); - questManager.getCategories().clear(); - taskTypeManager.resetTaskTypes(); - - questsConfigLoader.loadConfig(); - - switch (this.questMode) { -// TODO -// case DAILY: -// qPlayerManager.setActiveQuestController(new DailyQuestController(this)); -// break; - default: - case NORMAL: - qPlayerManager.setActiveQuestController(new NormalQuestController(this)); - break; - } - - long autosaveInterval = 12000; - if (!isBrokenConfig()) { - autosaveInterval = this.getConfig().getLong("options.performance-tweaking.quest-autosave-interval", 12000); - } - boolean autosaveTaskCancelled = true; - if (questAutosaveTask != null) { - try { - questAutosaveTask.cancel(); - } catch (Exception ex) { - questsLogger.debug("Cannot cancel and restart quest autosave task"); - autosaveTaskCancelled = false; - } - } - if (autosaveTaskCancelled) { - questAutosaveTask = Bukkit.getScheduler().runTaskTimer(this, () -> new QuestsAutosaveRunnable(this), autosaveInterval, autosaveInterval); - } - - boolean queuePollTaskCancelled = true; - long queueExecuteInterval = 1; - if (!isBrokenConfig()) { - queueExecuteInterval = this.getConfig().getLong("options.performance-tweaking.quest-queue-executor-interval", 1); - } - if (questQueuePollTask != null) { - try { - questQueuePollTask.cancel(); - } catch (Exception ex) { - questsLogger.debug("Cannot cancel and restart quest autosave task"); - queuePollTaskCancelled = false; - } - } - if (queuePollTaskCancelled) { - questQueuePollTask = Bukkit.getScheduler().runTaskTimer(this, questCompleter, queueExecuteInterval, queueExecuteInterval); - } - } - - public ItemStack getItemStack(String path, ConfigurationSection config, ItemGetter.Filter... excludes) { - return itemGetter.getItem(path, config, this, excludes); - } - - public ItemGetter getItemGetter() { - return itemGetter; - } - - private void setupVersionSpecific() { - String version; - try { - version = Bukkit.getServer().getClass().getPackage().getName().replace(".", ",").split(",")[3]; - } catch (ArrayIndexOutOfBoundsException e) { - getQuestsLogger().warning("Failed to resolve server version - some features will not work!"); - titleHandle = new Title_Other(); - itemGetter = new ItemGetter_Late_1_8(); - return; - } - - getQuestsLogger().info("Your server is running version " + version + "."); - - if (version.startsWith("v1_7")) { - titleHandle = new Title_Other(); - } else if (version.startsWith("v1_8") || version.startsWith("v1_9") || version.startsWith("v1_10")) { - titleHandle = new Title_BukkitNoTimings(); - } else { - titleHandle = new Title_Bukkit(); - } - - if (version.startsWith("v1_7") || version.startsWith("v1_8") || version.startsWith("v1_9") - || version.startsWith("v1_10") || version.startsWith("v1_11") || version.startsWith("v1_12")) { - itemGetter = new ItemGetter_Late_1_8(); - } else if (version.startsWith("v1_13")) { - itemGetter = new ItemGetter_1_13(); - } else { - itemGetter = new ItemGetterLatest(); - } - - if (titleHandle instanceof Title_Bukkit) { - getQuestsLogger().info("Titles have been enabled."); - } else if (titleHandle instanceof Title_BukkitNoTimings) { - getQuestsLogger().info("Titles have been enabled, although they have limited timings."); - } else { - getQuestsLogger().info("Titles are not supported for this version."); - } - } - - private void generateConfigurations() { - File directory = new File(String.valueOf(this.getDataFolder())); - if (!directory.exists() && !directory.isDirectory()) { - directory.mkdir(); - } - - File config = new File(this.getDataFolder() + File.separator + "config.yml"); - if (!config.exists()) { - try { - config.createNewFile(); - try (InputStream in = this.getResource("config.yml")) { - OutputStream out = new FileOutputStream(config); - byte[] buffer = new byte[1024]; - int lenght = in.read(buffer); - while (lenght != -1) { - out.write(buffer, 0, lenght); - lenght = in.read(buffer); - } - } catch (IOException e) { - e.printStackTrace(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - - File questsDirectory = new File(this.getDataFolder() + File.separator + "quests"); - if (!questsDirectory.exists() && !questsDirectory.isDirectory()) { - questsDirectory.mkdir(); - - ArrayList examples = new ArrayList<>(); - examples.add("example1.yml"); - examples.add("example2.yml"); - examples.add("example3.yml"); - examples.add("example4.yml"); - examples.add("example5.yml"); - examples.add("example6.yml"); - examples.add("example7.yml"); - examples.add("README.txt"); - - for (String name : examples) { - File file = new File(this.getDataFolder() + File.separator + "quests" + File.separator + name); - try { - file.createNewFile(); - try (InputStream in = this.getResource("quests/" + name)) { - OutputStream out = new FileOutputStream(file); - byte[] buffer = new byte[1024]; - int lenght = in.read(buffer); - while (lenght != -1) { - out.write(buffer, 0, lenght); - lenght = in.read(buffer); - } - } catch (IOException e) { - e.printStackTrace(); - } - } catch (IOException e) { - e.printStackTrace(); - } - } - } - } - - public QuestCompleter getQuestCompleter() { - return questCompleter; - } - - public QuestsLogger getQuestsLogger() { - return questsLogger; - } -} diff --git a/src/main/java/com/leonardobishop/quests/api/QuestsAPI.java b/src/main/java/com/leonardobishop/quests/api/QuestsAPI.java deleted file mode 100644 index db7ed470..00000000 --- a/src/main/java/com/leonardobishop/quests/api/QuestsAPI.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.leonardobishop.quests.api; - -import com.leonardobishop.quests.Quests; -import com.leonardobishop.quests.player.QPlayerManager; -import com.leonardobishop.quests.quest.QuestManager; -import com.leonardobishop.quests.quest.tasktype.TaskTypeManager; -import org.bukkit.Bukkit; - -/** - * This contains some methods from the main Quests class which - * will be useful in task type development. This is no different than - * simply getting an instance of the main class, however this is the - * preferred method of obtaining an instance of Quest classes outside - * of the core plugin itself. - * - * It is recommended to use this over {@code Quests.get()}, unless there - * are methods there that you absolutely need. - */ -public class QuestsAPI { - - private final static Quests plugin = (Quests) Bukkit.getPluginManager().getPlugin("Quests") ; - - public static QuestManager getQuestManager() { - return plugin.getQuestManager(); - } - - public static QPlayerManager getPlayerManager() { - return plugin.getPlayerManager(); - } - - public static TaskTypeManager getTaskTypeManager() { - return plugin.getTaskTypeManager(); - } - -} diff --git a/src/main/java/com/leonardobishop/quests/api/QuestsPlaceholders.java b/src/main/java/com/leonardobishop/quests/api/QuestsPlaceholders.java deleted file mode 100644 index 5c82cf6b..00000000 --- a/src/main/java/com/leonardobishop/quests/api/QuestsPlaceholders.java +++ /dev/null @@ -1,334 +0,0 @@ -package com.leonardobishop.quests.api; - -import com.leonardobishop.quests.Quests; -import com.leonardobishop.quests.api.enums.QuestStartResult; -import com.leonardobishop.quests.menu.QItemStack; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgressFile; -import com.leonardobishop.quests.quest.Category; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.util.Options; -import me.clip.placeholderapi.expansion.Cacheable; -import me.clip.placeholderapi.expansion.PlaceholderExpansion; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -public class QuestsPlaceholders extends PlaceholderExpansion implements Cacheable { - - private final Quests plugin; - private final Map> cache = new HashMap<>(); - private final Map formats = new HashMap<>(); - - public QuestsPlaceholders(Quests plugin) { - this.plugin = plugin; - } - - @Override - public void clear() { - cache.clear(); - formats.clear(); - } - - @Override - public String getIdentifier() { - return "quests"; - } - - @Override - public String getAuthor() { - return plugin.getDescription().getAuthors().toString(); - } - - @Override - public String getVersion() { - return plugin.getDescription().getVersion(); - } - - @Override - public boolean persist() { - return true; - } - - @Override - public String onPlaceholderRequest(Player p, String params) { - if (p == null || !p.isOnline()) return null; - if (cache.containsKey(p.getName()) && cache.get(p.getName()).containsKey(params)) - return cache.get(p.getName()).get(params); - - String[] args = params.split("_", 4); - if (args.length < 1) return "Invalid Placeholder"; - - final boolean save = args[args.length - 1].toLowerCase().equals("cache"); - if (save) args = Arrays.copyOf(args, args.length - 1); - - final QPlayer qPlayer = plugin.getPlayerManager().getPlayer(p.getUniqueId()); - if (qPlayer == null) return "Data not loaded"; - String split = args[args.length - 1]; - - String result = "null"; - if (!args[0].contains(":") && !args[0].equalsIgnoreCase("tracked")) { - if (args.length > 1 && split.equals(args[1])) split = ","; - - switch (args[0].toLowerCase()) { - case "all": - case "a": - final List listAll = new ArrayList<>(plugin.getQuestManager().getQuests().values()); - result = (args.length == 1 ? String.valueOf(listAll.size()) : parseList((List) listAll, args[1], split)); - break; - case "completed": - case "c": - final List listCompleted = qPlayer.getQuestProgressFile().getAllQuestsFromProgress(QuestProgressFile.QuestsProgressFilter.COMPLETED); - result = (args.length == 1 ? String.valueOf(listCompleted.size()) : parseList(listCompleted, args[1], split)); - break; - case "completedbefore": - case "cb": - final List listCompletedB = qPlayer.getQuestProgressFile().getAllQuestsFromProgress(QuestProgressFile.QuestsProgressFilter.COMPLETED_BEFORE); - result = (args.length == 1 ? String.valueOf(listCompletedB.size()) : parseList(listCompletedB, args[1], split)); - break; - case "started": - case "s": - final List listStarted = qPlayer.getQuestProgressFile().getAllQuestsFromProgress(QuestProgressFile.QuestsProgressFilter.STARTED); - result = (args.length == 1 ? String.valueOf(listStarted.size()) : parseList(listStarted, args[1], split)); - break; - case "categories": - if (args.length == 1) { - result = String.valueOf(plugin.getQuestManager().getCategories().size()); - } else { - final List listCategories = new ArrayList<>(); - switch (args[1].toLowerCase()) { - case "list": - case "l": - plugin.getQuestManager().getCategories().forEach(c -> listCategories.add(c.getDisplayNameStripped())); - break; - case "listid": - case "lid": - plugin.getQuestManager().getCategories().forEach(c -> listCategories.add(c.getId())); - break; - default: - return args[0] + "_" + args[1] + " is not a valid placeholder"; - } - result = String.join(split, listCategories); - } - break; - default: - return args[0] + " is not a valid placeholder"; - } - } else { - final String[] key = args[0].split(":"); - switch (key[0].toLowerCase()) { - case "quest": - case "q": - case "tracked": - if (!key[0].equalsIgnoreCase("tracked") && key.length == 1) return "Please specify quest name"; - - final Quest quest; - if (!key[0].equalsIgnoreCase("tracked")) { - quest = plugin.getQuestManager().getQuestById(key[1]); - if (quest == null) return key[1] + " is not a quest"; - } else { - quest = plugin.getQuestManager().getQuestById(qPlayer.getPlayerPreferences().getTrackedQuestId()); - if (quest == null) { - if (args.length == 1) { - return "No tracked quest"; - } else { - return ""; - } - } - } - - if (args.length == 1) { - result = quest.getDisplayNameStripped(); - } else { - switch (args[1].toLowerCase()) { - case "started": - case "s": - result = (qPlayer.getQuestProgressFile().getQuestProgress(quest).isStarted() ? "true" : "false"); - break; - case "completed": - case "c": - result = (qPlayer.getQuestProgressFile().getQuestProgress(quest).isCompleted() ? "true" : "false"); - break; - case "completedbefore": - case "cb": - result = (qPlayer.getQuestProgressFile().getQuestProgress(quest).isCompletedBefore() ? "true" : "false"); - break; - case "completiondate": - case "cd": - if (qPlayer.getQuestProgressFile().getQuestProgress(quest).isCompleted()) { - result = parseDate(args, qPlayer.getQuestProgressFile().getQuestProgress(quest).getCompletionDate()); - } else { - result = "Never"; - } - break; - case "cooldown": - if (qPlayer.getQuestProgressFile().getQuestProgress(quest).isCompleted()) { - final String time = plugin.convertToFormat(TimeUnit.SECONDS.convert(qPlayer.getQuestProgressFile().getCooldownFor(quest), TimeUnit.MILLISECONDS)); - if (!time.startsWith("-")) result = time; - } else { - result = "0"; - } - break; - case "canaccept": - result = (qPlayer.canStartQuest(quest) == QuestStartResult.QUEST_SUCCESS ? "true" : "false"); - break; - case "meetsrequirements": - result = (qPlayer.getQuestProgressFile().hasMetRequirements(quest) ? "true" : "false"); - break; - default: - if (!args[1].contains(":")) - return args[0] + "_" + args[1] + " is not a valid placeholder"; - - final String[] t = args[1].split(":"); - if (t[0].equalsIgnoreCase("task") || t[0].equalsIgnoreCase("t")) { - if (t.length == 1) return "Please specify task name"; - - if (args.length == 2) { - result = qPlayer.getQuestProgressFile().getQuestProgress(quest).getTaskProgress(t[1]).getTaskId(); - } else { - switch (args[2].toLowerCase()) { - case "progress": - case "p": - final Object progress = qPlayer.getQuestProgressFile().getQuestProgress(quest).getTaskProgress(t[1]).getProgress(); - result = (progress == null ? "0" : String.valueOf(progress)); - break; - case "completed": - case "c": - result = String.valueOf(qPlayer.getQuestProgressFile().getQuestProgress(quest).getTaskProgress(t[1]).isCompleted()); - break; - default: - return args[0] + "_" + args[1] + "_" + args[2] + " is not a valid placeholder"; - } - } - } else if (t[0].equalsIgnoreCase("placeholder") || t[0].equalsIgnoreCase("p")) { - if (t.length == 1) return "Please specify placeholder name"; - - String placeholder = quest.getPlaceholders().get(t[1]); - if (placeholder == null) { - return t[1] + " is not a valid placeholder within quest " + quest.getId(); - } - placeholder = QItemStack.processPlaceholders(Options.color(placeholder), qPlayer.getQuestProgressFile().getQuestProgress(quest)); - return placeholder; - } else { - return args[0] + "_" + args[1] + " is not a valid placeholder"; - } - } - } - break; - case "category": - case "c": - if (!Options.CATEGORIES_ENABLED.getBooleanValue()) return "Categories Disabled"; - if (key.length == 1) return "Please specify category name"; - - final Category category = plugin.getQuestManager().getCategoryById(key[1]); - if (category == null) return key[1] + " is not a category"; - - if (args.length == 1) { - result = category.getDisplayNameStripped(); - } else { - if (args.length > 2 && split.equals(args[2])) split = ","; - switch (args[1].toLowerCase()) { - case "all": - case "a": - final List listAll = getCategoryQuests(qPlayer, category, QuestProgressFile.QuestsProgressFilter.ALL); - result = (args.length == 2 ? String.valueOf(listAll.size()) : parseList(listAll, args[2], split)); - break; - case "completed": - case "c": - final List listCompleted = getCategoryQuests(qPlayer, category, QuestProgressFile.QuestsProgressFilter.COMPLETED); - result = (args.length == 2 ? String.valueOf(listCompleted.size()) : parseList(listCompleted, args[2], split)); - break; - case "completedbefore": - case "cb": - final List listCompletedB = getCategoryQuests(qPlayer, category, QuestProgressFile.QuestsProgressFilter.COMPLETED_BEFORE); - result = (args.length == 2 ? String.valueOf(listCompletedB.size()) : parseList(listCompletedB, args[2], split)); - break; - case "started": - case "s": - final List listStarted = getCategoryQuests(qPlayer, category, QuestProgressFile.QuestsProgressFilter.STARTED); - result = (args.length == 2 ? String.valueOf(listStarted.size()) : parseList(listStarted, args[2], split)); - break; - default: - return args[0] + "_" + args[1] + " is not a valid placeholder"; - } - } - break; - default: - return args[0] + " is not a valid placeholder"; - } - } - return (save ? cache(p.getName(), params, result) : result); - } - - private String cache(String player, String params, String result) { - if (!cache.containsKey(player) || !cache.get(player).containsKey(params)) { - final Map map = new HashMap<>(); - map.put(params, result); - cache.put(player, map); - Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> cache.get(player).remove(params), plugin.getConfig().getInt("options.placeholder-cache-time", 10) * 20); - } - return result; - } - - private String parseDate(String[] args, Long date) { - final String format = (args[args.length - 1].equals(args[1]) ? "dd/MM/yyyy" : args[args.length - 1]); - SimpleDateFormat sdf; - if (formats.containsKey(format)) { - sdf = formats.get(format); - } else { - sdf = new SimpleDateFormat(format); - formats.put(format, sdf); - } - return sdf.format(date); - } - - private String parseList(List list, String type, String separator) { - final List quests = new ArrayList<>(); - switch (type.toLowerCase()) { - case "list": - case "l": - list.forEach(q -> quests.add(q.getDisplayNameStripped())); - break; - case "listid": - case "lid": - list.forEach(q -> quests.add(q.getId())); - break; - default: - return type + "is not a valid placeholder"; - } - return String.join(separator, quests); - } - - private List getCategoryQuests(QPlayer questP, Category category, QuestProgressFile.QuestsProgressFilter filter) { - final List categoryQuests = new ArrayList<>(); - category.getRegisteredQuestIds().forEach(q -> { - Quest quest = plugin.getQuestManager().getQuestById(q); - if (quest != null) { - switch (filter) { - case STARTED: - if (questP.getQuestProgressFile().getQuestProgress(quest).isStarted()) - categoryQuests.add(quest); - break; - case COMPLETED: - if (questP.getQuestProgressFile().getQuestProgress(quest).isCompleted()) - categoryQuests.add(quest); - break; - case COMPLETED_BEFORE: - if (questP.getQuestProgressFile().getQuestProgress(quest).isCompletedBefore()) - categoryQuests.add(quest); - break; - default: - categoryQuests.add(quest); - } - } - }); - return categoryQuests; - } -} diff --git a/src/main/java/com/leonardobishop/quests/api/enums/QuestStartResult.java b/src/main/java/com/leonardobishop/quests/api/enums/QuestStartResult.java deleted file mode 100644 index 7241668d..00000000 --- a/src/main/java/com/leonardobishop/quests/api/enums/QuestStartResult.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.leonardobishop.quests.api.enums; - -public enum QuestStartResult { - QUEST_SUCCESS, //0 - QUEST_LIMIT_REACHED, //1 - QUEST_ALREADY_COMPLETED, //2 - QUEST_COOLDOWN, //3 - QUEST_LOCKED, //4 - QUEST_ALREADY_STARTED, //5 - QUEST_NO_PERMISSION, //6 - NO_PERMISSION_FOR_CATEGORY, //7 - OTHER //8 -} diff --git a/src/main/java/com/leonardobishop/quests/api/events/PlayerCancelQuestEvent.java b/src/main/java/com/leonardobishop/quests/api/events/PlayerCancelQuestEvent.java deleted file mode 100644 index 58e46206..00000000 --- a/src/main/java/com/leonardobishop/quests/api/events/PlayerCancelQuestEvent.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.leonardobishop.quests.api.events; - -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -public class PlayerCancelQuestEvent extends PlayerQuestEvent { - private final static HandlerList handlers = new HandlerList(); - private final QuestProgress questProgress; - private String questCancelMessage; - - public PlayerCancelQuestEvent(@NotNull Player who, @NotNull QPlayer questPlayer, @NotNull QuestProgress questProgress, String questCancelMessage) { - super(who, questPlayer); - this.questProgress = questProgress; - this.questCancelMessage = questCancelMessage; - } - - /** - * @return The quest progress - */ - public QuestProgress getQuestProgress() { - return this.questProgress; - } - - /** - * @return The message sent to the player that cancel the quest - */ - public String getQuestCancelMessage() { - return this.questCancelMessage; - } - - /** - * @param questCancelMessage The quest cancel message - * @return The quest cancel message set - */ - public String setQuestCancelMessage(String questCancelMessage) { - return (this.questCancelMessage = questCancelMessage); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/src/main/java/com/leonardobishop/quests/api/events/PlayerFinishQuestEvent.java b/src/main/java/com/leonardobishop/quests/api/events/PlayerFinishQuestEvent.java deleted file mode 100644 index 8bd4c5e6..00000000 --- a/src/main/java/com/leonardobishop/quests/api/events/PlayerFinishQuestEvent.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.leonardobishop.quests.api.events; - -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -public class PlayerFinishQuestEvent extends PlayerQuestEvent { - private final static HandlerList handlers = new HandlerList(); - private final QuestProgress questProgress; - private String questFinishMessage; - - public PlayerFinishQuestEvent(@NotNull Player who, @NotNull QPlayer questPlayer, @NotNull QuestProgress questProgress, String questFinishMessage) { - super(who, questPlayer); - this.questProgress = questProgress; - this.questFinishMessage = questFinishMessage; - } - - /** - * @return The quest progress - */ - public QuestProgress getQuestProgress() { - return this.questProgress; - } - - /** - * @return The message sent to the player that finish the quest - */ - public String getQuestFinishMessage() { - return this.questFinishMessage; - } - - /** - * @param questFinishMessage The quest finish message - * @return The quest finish message set - */ - public String setQuestFinishMessage(String questFinishMessage) { - return (this.questFinishMessage = questFinishMessage); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/src/main/java/com/leonardobishop/quests/api/events/PlayerQuestEvent.java b/src/main/java/com/leonardobishop/quests/api/events/PlayerQuestEvent.java deleted file mode 100644 index b78726ef..00000000 --- a/src/main/java/com/leonardobishop/quests/api/events/PlayerQuestEvent.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.leonardobishop.quests.api.events; - -import com.leonardobishop.quests.player.QPlayer; -import org.bukkit.entity.Player; -import org.bukkit.event.player.PlayerEvent; -import org.jetbrains.annotations.NotNull; - -public abstract class PlayerQuestEvent extends PlayerEvent { - private final QPlayer questPlayer; - - public PlayerQuestEvent(@NotNull Player who, @NotNull QPlayer questPlayer) { - super(who); - this.questPlayer = questPlayer; - } - - public QPlayer getQuestPlayer() { - return this.questPlayer; - } -} diff --git a/src/main/java/com/leonardobishop/quests/api/events/PlayerStartQuestEvent.java b/src/main/java/com/leonardobishop/quests/api/events/PlayerStartQuestEvent.java deleted file mode 100644 index 3602979f..00000000 --- a/src/main/java/com/leonardobishop/quests/api/events/PlayerStartQuestEvent.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.leonardobishop.quests.api.events; - -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -public class PlayerStartQuestEvent extends PlayerQuestEvent { - private final static HandlerList handlers = new HandlerList(); - private final QuestProgress questProgress; - private String questStartMessage; - - public PlayerStartQuestEvent(@NotNull Player who, @NotNull QPlayer questPlayer, @NotNull QuestProgress questProgress, String questStartMessage) { - super(who, questPlayer); - this.questProgress = questProgress; - this.questStartMessage = questStartMessage; - } - - /** - * @return The quest progress - */ - public QuestProgress getQuestProgress() { - return this.questProgress; - } - - /** - * @return The message sent to the player that start the quest - */ - public String getQuestStartMessage() { - return this.questStartMessage; - } - - /** - * @param questStartMessage The quest start message - * @return The quest start message set - */ - public String setQuestStartMessage(String questStartMessage) { - return (this.questStartMessage = questStartMessage); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/src/main/java/com/leonardobishop/quests/api/events/PlayerStartTrackQuestEvent.java b/src/main/java/com/leonardobishop/quests/api/events/PlayerStartTrackQuestEvent.java deleted file mode 100644 index 70b14dce..00000000 --- a/src/main/java/com/leonardobishop/quests/api/events/PlayerStartTrackQuestEvent.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.leonardobishop.quests.api.events; - -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgressFile; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerEvent; -import org.jetbrains.annotations.NotNull; - -public class PlayerStartTrackQuestEvent extends PlayerQuestEvent { - private final static HandlerList handlers = new HandlerList(); - private final QPlayer qPlayer; - - public PlayerStartTrackQuestEvent(@NotNull Player who, QPlayer qPlayer) { - super(who, qPlayer); - this.qPlayer = qPlayer; - } - - public QPlayer getQPlayer() { - return qPlayer; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - public static HandlerList getHandlerList() { - return handlers; - } - - -} diff --git a/src/main/java/com/leonardobishop/quests/api/events/PlayerStopTrackQuestEvent.java b/src/main/java/com/leonardobishop/quests/api/events/PlayerStopTrackQuestEvent.java deleted file mode 100644 index 42b3d263..00000000 --- a/src/main/java/com/leonardobishop/quests/api/events/PlayerStopTrackQuestEvent.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.leonardobishop.quests.api.events; - -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgressFile; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.bukkit.event.player.PlayerEvent; -import org.jetbrains.annotations.NotNull; - -public class PlayerStopTrackQuestEvent extends PlayerQuestEvent { - - private final static HandlerList handlers = new HandlerList(); - private final QPlayer qPlayer; - - public PlayerStopTrackQuestEvent(@NotNull Player who, QPlayer qPlayer) { - super(who, qPlayer); - this.qPlayer = qPlayer; - } - - public QPlayer getQPlayer() { - return qPlayer; - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } -} diff --git a/src/main/java/com/leonardobishop/quests/api/events/PreStartQuestEvent.java b/src/main/java/com/leonardobishop/quests/api/events/PreStartQuestEvent.java deleted file mode 100644 index abbbd77d..00000000 --- a/src/main/java/com/leonardobishop/quests/api/events/PreStartQuestEvent.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.leonardobishop.quests.api.events; - -import com.leonardobishop.quests.api.enums.QuestStartResult; -import com.leonardobishop.quests.player.QPlayer; -import org.bukkit.entity.Player; -import org.bukkit.event.HandlerList; -import org.jetbrains.annotations.NotNull; - -public class PreStartQuestEvent extends PlayerQuestEvent { - - private final static HandlerList handlers = new HandlerList(); - private QuestStartResult questStartResult; - private String questResultMessage; - - public PreStartQuestEvent(@NotNull Player who, @NotNull QPlayer questPlayer, String questResultMessage, @NotNull QuestStartResult questStartResult) { - super(who, questPlayer); - this.questStartResult = questStartResult; - this.questResultMessage = questResultMessage; - } - - public QuestStartResult getQuestStartResult() { - return this.questStartResult; - } - - public QuestStartResult setQuestStartResult(QuestStartResult questStartResult) { - return (this.questStartResult = questStartResult); - } - - /** - * @return The message sent to the player of the result of the quest - *

- * For {@link QuestStartResult#QUEST_SUCCESS} please use {@link PlayerStartQuestEvent} - */ - public String getQuestResultMessage() { - return this.questResultMessage; - } - - /** - * @param questResultMessage The quest result message - * @return The quest result message set - *

- * For {@link QuestStartResult#QUEST_SUCCESS} please use {@link PlayerStartQuestEvent} - */ - public String setQuestResultMessage(String questResultMessage) { - return (this.questResultMessage = questResultMessage); - } - - @NotNull - @Override - public HandlerList getHandlers() { - return handlers; - } - - public static HandlerList getHandlerList() { - return handlers; - } -} diff --git a/src/main/java/com/leonardobishop/quests/blocktype/Block.java b/src/main/java/com/leonardobishop/quests/blocktype/Block.java deleted file mode 100644 index 4b3b7d6a..00000000 --- a/src/main/java/com/leonardobishop/quests/blocktype/Block.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.leonardobishop.quests.blocktype; - -import org.bukkit.Material; - -@Deprecated -public class Block { - - private Material material; - private short data; - - public Block(Material material, short data) { - this.material = material; - this.data = data; - } - - public Block(Material material) { - this.material = material; - } - - public Material getMaterial() { - return material; - } - - public short getData() { - return data; - } - - public void setMaterial(Material material) { - this.material = material; - } - - public void setData(short data) { - this.data = data; - } -} diff --git a/src/main/java/com/leonardobishop/quests/blocktype/SimilarBlocks.java b/src/main/java/com/leonardobishop/quests/blocktype/SimilarBlocks.java deleted file mode 100644 index fc910170..00000000 --- a/src/main/java/com/leonardobishop/quests/blocktype/SimilarBlocks.java +++ /dev/null @@ -1,93 +0,0 @@ -//package com.leonardobishop.quests.blocktype; -// -//import org.bukkit.Material; -// -//import java.util.HashMap; -//import java.util.Map; -// -//public class SimilarBlocks { -// -// private static HashMap similarBlocks = new HashMap<>(); -// -// static { -// // Redstone Ore -// similarBlocks.put(new Block(Material.REDSTONE_ORE), new Block(Material.GLOWING_REDSTONE_ORE)); -// similarBlocks.put(new Block(Material.GLOWING_REDSTONE_ORE), new Block(Material.REDSTONE_ORE)); -// -// // Oak Door -// similarBlocks.put(new Block(Material.WOODEN_DOOR, (short) 0), new Block(Material.WOODEN_DOOR)); -// similarBlocks.put(new Block(Material.WOODEN_DOOR, (short) 1), new Block(Material.WOODEN_DOOR)); -// similarBlocks.put(new Block(Material.WOODEN_DOOR, (short) 2), new Block(Material.WOODEN_DOOR)); -// similarBlocks.put(new Block(Material.WOODEN_DOOR, (short) 3), new Block(Material.WOODEN_DOOR)); -// -// // Dark Oak Door -// similarBlocks.put(new Block(Material.DARK_OAK_DOOR, (short) 0), new Block(Material.DARK_OAK_DOOR)); -// similarBlocks.put(new Block(Material.DARK_OAK_DOOR, (short) 1), new Block(Material.DARK_OAK_DOOR)); -// similarBlocks.put(new Block(Material.DARK_OAK_DOOR, (short) 2), new Block(Material.DARK_OAK_DOOR)); -// similarBlocks.put(new Block(Material.DARK_OAK_DOOR, (short) 3), new Block(Material.DARK_OAK_DOOR)); -// -// // Acacia Door -// similarBlocks.put(new Block(Material.ACACIA_DOOR, (short) 0), new Block(Material.ACACIA_DOOR)); -// similarBlocks.put(new Block(Material.ACACIA_DOOR, (short) 1), new Block(Material.ACACIA_DOOR)); -// similarBlocks.put(new Block(Material.ACACIA_DOOR, (short) 2), new Block(Material.ACACIA_DOOR)); -// similarBlocks.put(new Block(Material.ACACIA_DOOR, (short) 3), new Block(Material.ACACIA_DOOR)); -// -// // Birch Door -// similarBlocks.put(new Block(Material.BIRCH_DOOR, (short) 0), new Block(Material.BIRCH_DOOR)); -// similarBlocks.put(new Block(Material.BIRCH_DOOR, (short) 1), new Block(Material.BIRCH_DOOR)); -// similarBlocks.put(new Block(Material.BIRCH_DOOR, (short) 2), new Block(Material.BIRCH_DOOR)); -// similarBlocks.put(new Block(Material.BIRCH_DOOR, (short) 3), new Block(Material.BIRCH_DOOR)); -// -// // Jungle Door -// similarBlocks.put(new Block(Material.JUNGLE_DOOR, (short) 0), new Block(Material.JUNGLE_DOOR)); -// similarBlocks.put(new Block(Material.JUNGLE_DOOR, (short) 1), new Block(Material.JUNGLE_DOOR)); -// similarBlocks.put(new Block(Material.JUNGLE_DOOR, (short) 2), new Block(Material.JUNGLE_DOOR)); -// similarBlocks.put(new Block(Material.JUNGLE_DOOR, (short) 3), new Block(Material.JUNGLE_DOOR)); -// -// // Spruce Door -// similarBlocks.put(new Block(Material.SPRUCE_DOOR, (short) 0), new Block(Material.SPRUCE_DOOR)); -// similarBlocks.put(new Block(Material.SPRUCE_DOOR, (short) 1), new Block(Material.SPRUCE_DOOR)); -// similarBlocks.put(new Block(Material.SPRUCE_DOOR, (short) 2), new Block(Material.SPRUCE_DOOR)); -// similarBlocks.put(new Block(Material.SPRUCE_DOOR, (short) 3), new Block(Material.SPRUCE_DOOR)); -// -// // Iron Door -// similarBlocks.put(new Block(Material.IRON_DOOR, (short) 0), new Block(Material.IRON_DOOR)); -// similarBlocks.put(new Block(Material.IRON_DOOR, (short) 1), new Block(Material.IRON_DOOR)); -// similarBlocks.put(new Block(Material.IRON_DOOR, (short) 2), new Block(Material.IRON_DOOR)); -// similarBlocks.put(new Block(Material.IRON_DOOR, (short) 3), new Block(Material.IRON_DOOR)); -// -// // Oak Log -// similarBlocks.put(new Block(Material.LOG, (short) 4), new Block(Material.LOG, (short) 0)); -// similarBlocks.put(new Block(Material.LOG, (short) 8), new Block(Material.LOG, (short) 0)); -// -// // Spruce Log -// similarBlocks.put(new Block(Material.LOG, (short) 5), new Block(Material.LOG, (short) 1)); -// similarBlocks.put(new Block(Material.LOG, (short) 9), new Block(Material.LOG, (short) 1)); -// -// // Birch Log -// similarBlocks.put(new Block(Material.LOG, (short) 6), new Block(Material.LOG, (short) 2)); -// similarBlocks.put(new Block(Material.LOG, (short) 10), new Block(Material.LOG, (short) 2)); -// -// // Jungle Log -// similarBlocks.put(new Block(Material.LOG, (short) 7), new Block(Material.LOG, (short) 3)); -// similarBlocks.put(new Block(Material.LOG, (short) 11), new Block(Material.LOG, (short) 3)); -// -// // Acacia Log -// similarBlocks.put(new Block(Material.LOG_2, (short) 4), new Block(Material.LOG, (short) 0)); -// similarBlocks.put(new Block(Material.LOG_2, (short) 8), new Block(Material.LOG, (short) 0)); -// -// // Dark Oak Log -// similarBlocks.put(new Block(Material.LOG_2, (short) 5), new Block(Material.LOG, (short) 1)); -// similarBlocks.put(new Block(Material.LOG_2, (short) 9), new Block(Material.LOG, (short) 1)); -// } -// -// public static Block getSimilarBlock(Block block) { -// for (Map.Entry entry : similarBlocks.entrySet()) { -// if (entry.getKey().getMaterial() == block.getMaterial() && entry.getKey().getData() == block.getData()) { -// return entry.getValue(); -// } -// } -// return null; -// } -// -//} diff --git a/src/main/java/com/leonardobishop/quests/command/QuestsCommand.java b/src/main/java/com/leonardobishop/quests/command/QuestsCommand.java deleted file mode 100644 index 0906b3c9..00000000 --- a/src/main/java/com/leonardobishop/quests/command/QuestsCommand.java +++ /dev/null @@ -1,636 +0,0 @@ -package com.leonardobishop.quests.command; - -import com.leonardobishop.quests.Quests; -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.api.enums.QuestStartResult; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgressFile; -import com.leonardobishop.quests.quest.Category; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.util.Messages; -import com.leonardobishop.quests.util.Options; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.OfflinePlayer; -import org.bukkit.command.Command; -import org.bukkit.command.CommandSender; -import org.bukkit.command.TabExecutor; -import org.bukkit.entity.Player; -import org.bukkit.util.StringUtil; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.ThreadLocalRandom; - -public class QuestsCommand implements TabExecutor { - - private final Quests plugin; - - public QuestsCommand(Quests plugin) { - this.plugin = plugin; - } - - @SuppressWarnings("deprecation") - @Override - public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) { - if (plugin.getTaskTypeManager().areRegistrationsAccepted()) { - sender.sendMessage(ChatColor.RED + "Quests is not ready yet."); - return true; - } - if (plugin.isBrokenConfig() && - !(args.length >= 2 && - (args[0].equalsIgnoreCase("a") || args[0].equalsIgnoreCase("admin")) && - args[1].equalsIgnoreCase("reload"))) { - sender.sendMessage(ChatColor.RED + "Quests cannot be used right now. Please speak to an administrator."); - if (sender.hasPermission("quests.admin")) { - showProblems(sender); - sender.sendMessage(ChatColor.RED + "The main config (config.yml) must be in tact before quests can be used. " + - "Please use the above information to help rectify the problem."); - } - return true; - } - - if (args.length >= 1 && args[0].equalsIgnoreCase("help")) { - showHelp(sender); - return true; - } - - if (args.length == 0 && sender instanceof Player) { - Player player = (Player) sender; - QPlayer qPlayer = plugin.getPlayerManager().getPlayer(player.getUniqueId()); - if (qPlayer == null) { - player.sendMessage(Messages.COMMAND_DATA_NOT_LOADED.getMessage()); - return true; - } - qPlayer.openQuests(); - return true; - } else if (args.length >= 1) { - if ((args[0].equalsIgnoreCase("a") || args[0].equalsIgnoreCase("admin")) && sender.hasPermission("quests.admin")) { - if (args.length == 2) { - if (args[1].equalsIgnoreCase("opengui")) { - showAdminHelp(sender, "opengui"); - return true; - } else if (args[1].equalsIgnoreCase("moddata")) { - showAdminHelp(sender, "moddata"); - return true; - } else if (args[1].equalsIgnoreCase("reload")) { - sender.sendMessage(ChatColor.GRAY + "Please note that some options, such as storage, require a full restart for chances to take effect."); - plugin.reloadConfig(); - plugin.reloadQuests(); - if (!plugin.getQuestsConfigLoader().getFilesWithProblems().isEmpty()) showProblems(sender); - sender.sendMessage(ChatColor.GREEN + "Quests successfully reloaded."); - return true; - } else if (args[1].equalsIgnoreCase("config")) { - showProblems(sender); - return true; - //TODO -// } else if (args[1].equalsIgnoreCase("itemstack")) { -// if (!(sender instanceof Player)) { -// sender.sendMessage("You must be a player to use this command."); -// return true; -// } -// Player player = (Player) sender; -// ItemStack is = player.getItemInHand(); -// if (is == null || is.getType() == Material.AIR) { -// sender.sendMessage(ChatColor.GRAY + "There is no information about this ItemStack."); -// return true; -// } -// sender.sendMessage(ToStringBuilder.reflectionToString(is)); -// sender.sendMessage(ToStringBuilder.reflectionToString(is.getItemMeta())); -// return true; - } else if (args[1].equalsIgnoreCase("types")) { - sender.sendMessage(ChatColor.GRAY + "Registered task types:"); - for (TaskType taskType : plugin.getTaskTypeManager().getTaskTypes()) { - sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + taskType.getType()); - } - sender.sendMessage(ChatColor.DARK_GRAY + "View info using /q a types [type]."); - return true; - } else if (args[1].equalsIgnoreCase("info")) { - sender.sendMessage(ChatColor.RED + "Quest mode: " + plugin.getQuestMode().toString()); - sender.sendMessage(ChatColor.GRAY + "Loaded quests:"); - for (Quest quest : plugin.getQuestManager().getQuests().values()) { - sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + quest.getId() + ChatColor.GRAY + " [" + quest.getTasks().size() + " tasks]"); - } - sender.sendMessage(ChatColor.DARK_GRAY + "View info using /q a info [quest]."); - return true; - } else if (args[1].equalsIgnoreCase("update")) { - sender.sendMessage(ChatColor.GRAY + "Checking for updates..."); - Bukkit.getScheduler().runTaskAsynchronously(this.plugin, () -> { - plugin.getUpdater().check(); - if (plugin.getUpdater().isUpdateReady()) { - sender.sendMessage(plugin.getUpdater().getMessage()); - } else { - sender.sendMessage(ChatColor.GRAY + "No updates were found."); - } - }); - return true; - } else if (args[1].equalsIgnoreCase("wiki")) { - sender.sendMessage(ChatColor.RED + "Link to Quests wiki: " + ChatColor.GRAY + "https://github.com/LMBishop/Quests/wiki"); - return true; - } else if (args[1].equalsIgnoreCase("about")) { - sender.sendMessage(ChatColor.RED + "Quests " + ChatColor.BOLD + "v" + plugin.getDescription().getVersion()); - sender.sendMessage(ChatColor.DARK_GRAY + " - " + ChatColor.RED + "Source code: " + ChatColor.GRAY + "https://github.com/LMBishop/Quests/"); - sender.sendMessage(ChatColor.DARK_GRAY + " - " + ChatColor.RED + "Report an issue: " + ChatColor.GRAY + "https://github.com/LMBishop/Quests/issues"); - sender.sendMessage(ChatColor.DARK_GRAY + " - " + ChatColor.RED + "Wiki: " + ChatColor.GRAY + "https://github.com/LMBishop/Quests/wiki"); - sender.sendMessage(ChatColor.DARK_GRAY + " - " + ChatColor.RED + "Licensed under the GPLv3"); - sender.sendMessage(ChatColor.GRAY + "Many contributors have written source code and task types for Quests," + - " please see the GitHub link for an up-to-date list of contributors."); - return true; - } - } else if (args.length == 3) { - if (args[1].equalsIgnoreCase("opengui")) { - showAdminHelp(sender, "opengui"); - return true; - } else if (args[1].equalsIgnoreCase("moddata")) { - showAdminHelp(sender, "moddata"); - return true; - } else if (args[1].equalsIgnoreCase("types")) { - TaskType taskType = null; - for (TaskType task : plugin.getTaskTypeManager().getTaskTypes()) { - if (task.getType().equals(args[2])) { - taskType = task; - } - } - if (taskType == null) { - sender.sendMessage(Messages.COMMAND_TASKVIEW_ADMIN_FAIL.getMessage().replace("{task}", args[2])); - } else { - sender.sendMessage(ChatColor.RED + "Task type: " + ChatColor.GRAY + taskType.getType()); - sender.sendMessage(ChatColor.RED + "Author: " + ChatColor.GRAY + taskType.getAuthor()); - sender.sendMessage(ChatColor.RED + "Description: " + ChatColor.GRAY + taskType.getDescription()); - } - return true; - } else if (args[1].equalsIgnoreCase("info")) { - Quest quest = plugin.getQuestManager().getQuestById(args[2]); - if (quest == null) { - sender.sendMessage(Messages.COMMAND_QUEST_GENERAL_DOESNTEXIST.getMessage().replace("{quest}", args[2])); - } else { - sender.sendMessage(ChatColor.RED.toString() + ChatColor.BOLD + "Information for quest '" + quest.getId() + "'"); - sender.sendMessage(ChatColor.RED.toString() + ChatColor.UNDERLINE + "Task configurations (" + quest.getTasks().size() + ")"); - for (Task task : quest.getTasks()) { - sender.sendMessage(ChatColor.RED + "Task '" + task.getId() + "':"); - for (Map.Entry config : task.getConfigValues().entrySet()) { - sender.sendMessage(ChatColor.DARK_GRAY + " | " + ChatColor.GRAY + config.getKey() + ": " + ChatColor.GRAY + ChatColor.ITALIC + config.getValue()); - } - } - sender.sendMessage(ChatColor.RED.toString() + ChatColor.UNDERLINE + "Start string"); - for (String s : quest.getStartString()) { - sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.GRAY + s); - } - sender.sendMessage(ChatColor.RED.toString() + ChatColor.UNDERLINE + "Reward string"); - for (String s : quest.getRewardString()) { - sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.GRAY + s); - } - sender.sendMessage(ChatColor.RED.toString() + ChatColor.UNDERLINE + "Rewards"); - for (String s : quest.getRewards()) { - sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.GRAY + s); - } - sender.sendMessage(ChatColor.RED.toString() + ChatColor.UNDERLINE + "Quest options"); - sender.sendMessage(ChatColor.RED + "Category: " + ChatColor.GRAY + quest.getCategoryId()); - sender.sendMessage(ChatColor.RED + "Repeatable: " + ChatColor.GRAY + quest.isRepeatable()); - sender.sendMessage(ChatColor.RED + "Requirements: " + ChatColor.GRAY + String.join(", ", quest.getRequirements())); - sender.sendMessage(ChatColor.RED + "Cooldown enabled: " + ChatColor.GRAY + quest.isCooldownEnabled()); - sender.sendMessage(ChatColor.RED + "Cooldown time: " + ChatColor.GRAY + quest.getCooldown()); - } - return true; - } - } else if (args.length == 4) { - if (args[1].equalsIgnoreCase("opengui")) { - if (args[2].equalsIgnoreCase("q") || args[2].equalsIgnoreCase("quests")) { - Player player = Bukkit.getPlayer(args[3]); - if (player != null) { - QPlayer qPlayer = plugin.getPlayerManager().getPlayer(player.getUniqueId()); - if (qPlayer != null) { - qPlayer.openQuests(); - sender.sendMessage(Messages.COMMAND_QUEST_OPENQUESTS_ADMIN_SUCCESS.getMessage().replace("{player}", player.getName())); - return true; - } - } - sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_PLAYERNOTFOUND.getMessage().replace("{player}", args[3])); - return true; - } - showAdminHelp(sender, "opengui"); - return true; - } else if (args[1].equalsIgnoreCase("moddata")) { - QPlayer qPlayer = getOtherPlayer(sender, args[3]); - if (qPlayer == null) return true; - if (args[2].equalsIgnoreCase("fullreset")) { - QuestProgressFile questProgressFile = qPlayer.getQuestProgressFile(); - questProgressFile.clear(); - plugin.getPlayerManager().savePlayerSync(qPlayer.getPlayerUUID(), questProgressFile); - if (Bukkit.getPlayer(qPlayer.getPlayerUUID()) == null) { - plugin.getPlayerManager().dropPlayer(qPlayer.getPlayerUUID()); - } - sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_FULLRESET.getMessage().replace("{player}", args[3])); - return true; - } - showAdminHelp(sender, "moddata"); - return true; - } - } else if (args.length == 5) { - if (args[1].equalsIgnoreCase("opengui")) { - if (args[2].equalsIgnoreCase("c") || args[2].equalsIgnoreCase("category")) { - if (!Options.CATEGORIES_ENABLED.getBooleanValue()) { - sender.sendMessage(Messages.COMMAND_CATEGORY_OPEN_DISABLED.getMessage()); - return true; - } - Category category = plugin.getQuestManager().getCategoryById(args[4]); - if (category == null) { - sender.sendMessage(Messages.COMMAND_CATEGORY_OPEN_DOESNTEXIST.getMessage().replace("{category}", args[4])); - return true; - } - Player player = Bukkit.getPlayer(args[3]); - if (player != null) { - QPlayer qPlayer = plugin.getPlayerManager().getPlayer(player.getUniqueId()); - if (qPlayer != null) { - if (qPlayer.openCategory(category, null, false) == 0) { - sender.sendMessage(Messages.COMMAND_QUEST_OPENCATEGORY_ADMIN_SUCCESS.getMessage().replace("{player}", player.getName()) - .replace("{category}", category.getId())); - } else { - sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_CATEGORY_PERMISSION.getMessage().replace("{player}", player.getName()) - .replace("{category}", category.getId())); - } - return true; - } - } - sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_PLAYERNOTFOUND.getMessage().replace("{player}", args[3])); - return true; - } - } else if (args[1].equalsIgnoreCase("moddata")) { - boolean success = false; - QPlayer qPlayer = getOtherPlayer(sender, args[3]); - if (qPlayer == null) return true; - QuestProgressFile questProgressFile = qPlayer.getQuestProgressFile(); - Quest quest = plugin.getQuestManager().getQuestById(args[4]); - if (quest == null) { - sender.sendMessage(Messages.COMMAND_QUEST_START_DOESNTEXIST.getMessage().replace("{quest}", args[4])); - //success = true; - return true; - } - if (args[2].equalsIgnoreCase("reset")) { - questProgressFile.generateBlankQuestProgress(quest); - plugin.getPlayerManager().savePlayerSync(qPlayer.getPlayerUUID(), questProgressFile); - sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_RESET_SUCCESS.getMessage().replace("{player}", args[3]).replace("{quest}", quest.getId())); - success = true; - } else if (args[2].equalsIgnoreCase("start")) { - QuestStartResult response = qPlayer.startQuest(quest); - if (response == QuestStartResult.QUEST_LIMIT_REACHED) { - sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_START_FAILLIMIT.getMessage().replace("{player}", args[3]).replace("{quest}", quest.getId())); - return true; - } else if (response == QuestStartResult.QUEST_ALREADY_COMPLETED) { - sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_START_FAILCOMPLETE.getMessage().replace("{player}", args[3]).replace("{quest}", quest.getId())); - return true; - } else if (response == QuestStartResult.QUEST_COOLDOWN) { - sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_START_FAILCOOLDOWN.getMessage().replace("{player}", args[3]).replace("{quest}", quest.getId())); - return true; - } else if (response == QuestStartResult.QUEST_LOCKED) { - sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_START_FAILLOCKED.getMessage().replace("{player}", args[3]).replace("{quest}", quest.getId())); - return true; - } else if (response == QuestStartResult.QUEST_ALREADY_STARTED) { - sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_START_FAILSTARTED.getMessage().replace("{player}", args[3]).replace("{quest}", quest.getId())); - return true; - } else if (response == QuestStartResult.QUEST_NO_PERMISSION) { - sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_START_FAILPERMISSION.getMessage().replace("{player}", args[3]).replace("{quest}", quest.getId())); - return true; - } else if (response == QuestStartResult.NO_PERMISSION_FOR_CATEGORY) { - sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_START_FAILCATEGORYPERMISSION.getMessage().replace("{player}", args[3]).replace("{quest}", quest.getId())); - return true; - } - plugin.getPlayerManager().savePlayerSync(qPlayer.getPlayerUUID(), questProgressFile); - sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_START_SUCCESS.getMessage().replace("{player}", args[3]).replace("{quest}", quest.getId())); - success = true; - } else if (args[2].equalsIgnoreCase("complete")) { - qPlayer.completeQuest(quest); - plugin.getPlayerManager().savePlayerSync(qPlayer.getPlayerUUID(), questProgressFile); - sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_COMPLETE_SUCCESS.getMessage().replace("{player}", args[3]).replace("{quest}", quest.getId())); - success = true; - } - if (!success) { - showAdminHelp(sender, "moddata"); - } - if (Bukkit.getPlayer(qPlayer.getPlayerUUID()) == null) { - plugin.getPlayerManager().dropPlayer(qPlayer.getPlayerUUID()); - } - return true; - } - } - showAdminHelp(sender, null); - return true; - } - if (sender instanceof Player && (args[0].equalsIgnoreCase("q") || args[0].equalsIgnoreCase("quests") || args[0].equalsIgnoreCase("quest"))) { - Player player = (Player) sender; - if (args.length >= 3) { - Quest quest = plugin.getQuestManager().getQuestById(args[1]); - QPlayer qPlayer = plugin.getPlayerManager().getPlayer(player.getUniqueId()); - if (qPlayer == null) { - player.sendMessage(Messages.COMMAND_DATA_NOT_LOADED.getMessage()); - return true; - } - if (quest == null) { - sender.sendMessage(Messages.COMMAND_QUEST_GENERAL_DOESNTEXIST.getMessage().replace("{quest}", args[1])); - } - if (args[2].equalsIgnoreCase("s") || args[2].equalsIgnoreCase("start")) { - qPlayer.startQuest(quest); - } else if (args[2].equalsIgnoreCase("c") || args[2].equalsIgnoreCase("cancel")) { - qPlayer.cancelQuest(quest); - } else if (args[2].equalsIgnoreCase("t") || args[2].equalsIgnoreCase("track")) { - qPlayer.trackQuest(quest); - } else { - sender.sendMessage(Messages.COMMAND_SUB_DOESNTEXIST.getMessage().replace("{sub}", args[2])); - } - return true; - } - } else if (sender instanceof Player && (args[0].equalsIgnoreCase("c") || args[0].equalsIgnoreCase("category"))) { - if (!Options.CATEGORIES_ENABLED.getBooleanValue()) { - sender.sendMessage(Messages.COMMAND_CATEGORY_OPEN_DISABLED.getMessage()); - return true; - } - Player player = (Player) sender; - if (args.length >= 2) { - Category category = plugin.getQuestManager().getCategoryById(args[1]); - QPlayer qPlayer = plugin.getPlayerManager().getPlayer(player.getUniqueId()); - if (qPlayer == null) { - player.sendMessage(Messages.COMMAND_DATA_NOT_LOADED.getMessage()); - return true; - } - if (category == null) { - sender.sendMessage(Messages.COMMAND_CATEGORY_OPEN_DOESNTEXIST.getMessage().replace("{category}", args[1])); - } else { - qPlayer.openCategory(category, null, false); - return true; - } - return true; - } - } else if (sender instanceof Player && (args[0].equalsIgnoreCase("random")) && sender.hasPermission("quests.command.random")) { - Player player = (Player) sender; - QPlayer qPlayer = plugin.getPlayerManager().getPlayer(player.getUniqueId()); - if (qPlayer == null) { - player.sendMessage(Messages.COMMAND_DATA_NOT_LOADED.getMessage()); - return true; - } - List validQuests = new ArrayList<>(); - for (Quest quest : plugin.getQuestManager().getQuests().values()) { - if (qPlayer.canStartQuest(quest) == QuestStartResult.QUEST_SUCCESS) { - validQuests.add(quest); - } - } - - if (validQuests.isEmpty()) { - player.sendMessage(Messages.QUEST_RANDOM_NONE.getMessage()); - return true; - } - int random = ThreadLocalRandom.current().nextInt(0, validQuests.size()); - qPlayer.startQuest(validQuests.get(random)); - return true; - } else if (sender instanceof Player && (args[0].equalsIgnoreCase("started"))) { - Player player = (Player) sender; - QPlayer qPlayer = plugin.getPlayerManager().getPlayer(player.getUniqueId()); - if (qPlayer == null) { - player.sendMessage(Messages.COMMAND_DATA_NOT_LOADED.getMessage()); - return true; - } - qPlayer.openStartedQuests(); - return true; - } - showHelp(sender); - } else { - sender.sendMessage(ChatColor.RED + "Only admin commands are available to non-player senders."); - } - return true; - } - - private QPlayer getOtherPlayer(CommandSender sender, String name) { - OfflinePlayer ofp = Bukkit.getOfflinePlayer(name); - UUID uuid; - String username; - if (ofp.hasPlayedBefore()) { - uuid = ofp.getUniqueId(); - username = ofp.getName(); - } else { - sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_PLAYERNOTFOUND.getMessage().replace("{player}", name)); - return null; - } - QPlayer qPlayer = plugin.getPlayerManager().getPlayer(uuid); - if (qPlayer == null) { - sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_LOADDATA.getMessage().replace("{player}", username)); - plugin.getPlayerManager().loadPlayer(uuid); - qPlayer = plugin.getPlayerManager().getPlayer(uuid); - } - if (qPlayer == null) { - sender.sendMessage(Messages.COMMAND_QUEST_ADMIN_NODATA.getMessage().replace("{player}", username)); - return null; - } - return qPlayer; - } - - private void showProblems(CommandSender sender) { - if (!plugin.getQuestsConfigLoader().getFilesWithProblems().isEmpty()) { -// sender.sendMessage(ChatColor.DARK_GRAY.toString() + "----"); - sender.sendMessage(ChatColor.GRAY + "Detected problems and potential issues:"); - Set problemTypes = new HashSet<>(); - for (Map.Entry> entry : plugin.getQuestsConfigLoader().getFilesWithProblems().entrySet()) { - HashMap> sortedProblems = new HashMap<>(); - for (QuestsConfigLoader.ConfigProblem problem : entry.getValue()) { - if (sortedProblems.containsKey(problem.getType())) { - sortedProblems.get(problem.getType()).add(problem); - } else { - List specificProblems = new ArrayList<>(); - specificProblems.add(problem); - sortedProblems.put(problem.getType(), specificProblems); - } - problemTypes.add(problem.getType()); - } - QuestsConfigLoader.ConfigProblemType highest = null; - for (QuestsConfigLoader.ConfigProblemType type : QuestsConfigLoader.ConfigProblemType.values()) { - if (sortedProblems.containsKey(type)) { - highest = type; - break; - } - } - ChatColor highestColor = ChatColor.WHITE; - if (highest != null) { - highestColor = highest.getColor(); - } - sender.sendMessage(highestColor + entry.getKey() + ChatColor.DARK_GRAY + " ----"); - for (QuestsConfigLoader.ConfigProblemType type : QuestsConfigLoader.ConfigProblemType.values()) { - if (sortedProblems.containsKey(type)) { - for (QuestsConfigLoader.ConfigProblem problem : sortedProblems.get(type)) { - sender.sendMessage(ChatColor.DARK_GRAY + " | - " + problem.getType().getColor() - + problem.getType().getShortened() + ChatColor.DARK_GRAY + ": " - + ChatColor.GRAY + problem.getDescription() + ChatColor.DARK_GRAY + " :" + problem.getLocation()); - } - } - } - } -// sender.sendMessage(ChatColor.DARK_GRAY.toString() + "----"); - List legend = new ArrayList<>(); - for (QuestsConfigLoader.ConfigProblemType type : QuestsConfigLoader.ConfigProblemType.values()) { - if (problemTypes.contains(type)) - legend.add(type.getColor() + type.getShortened() + ChatColor.DARK_GRAY + " = " + type.getColor() + type.getTitle()); - } - sender.sendMessage(ChatColor.DARK_GRAY.toString() + "----"); - sender.sendMessage(ChatColor.GRAY.toString() + plugin.getQuestsConfigLoader().getProblemsCount() + " problem(s) | " + String.join(ChatColor.DARK_GRAY + ", ", legend)); - } else { - sender.sendMessage(ChatColor.GRAY + "Quests did not detect any problems with your configuration."); - } - } - - private void showHelp(CommandSender sender) { - sender.sendMessage(ChatColor.GRAY.toString() + ChatColor.STRIKETHROUGH + "------------=[" + ChatColor.RED + " Quests v" + plugin - .getDescription().getVersion() + " " + ChatColor.GRAY.toString() + ChatColor.STRIKETHROUGH + "]=------------"); - sender.sendMessage(ChatColor.GRAY + "The following commands are available: "); - sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests " + ChatColor.DARK_GRAY + ": show quests"); - sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests c/category " + ChatColor.DARK_GRAY + ": open category by ID"); - sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests q/quest " + ChatColor.DARK_GRAY + ": start, cancel or track quest by ID"); - sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests a/admin " + ChatColor.DARK_GRAY + ": view help for admins"); - sender.sendMessage(ChatColor.GRAY.toString() + ChatColor.STRIKETHROUGH + "--------=[" + ChatColor.RED + " made with <3 by LMBishop " + ChatColor - .GRAY.toString() + ChatColor.STRIKETHROUGH + "]=--------"); - } - - private void showAdminHelp(CommandSender sender, String command) { - if (command != null && command.equalsIgnoreCase("opengui")) { - sender.sendMessage(ChatColor.GRAY.toString() + ChatColor.STRIKETHROUGH + "------------=[" + ChatColor.RED + " Quests Admin: opengui " + ChatColor - .GRAY.toString() + ChatColor.STRIKETHROUGH + "]=------------"); - sender.sendMessage(ChatColor.GRAY + "The following commands are available: "); - sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests a opengui q/quests " + ChatColor.DARK_GRAY + ": forcefully show" + - " quests for player"); - sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests a opengui c/category " + ChatColor.DARK_GRAY + ": " + - "forcefully " + - "open category by ID for player"); - sender.sendMessage(ChatColor.GRAY + "These commands are useful for command NPCs. These will bypass the usual quests.command permission."); - } else if (command != null && command.equalsIgnoreCase("moddata")) { - sender.sendMessage(ChatColor.GRAY.toString() + ChatColor.STRIKETHROUGH + "------------=[" + ChatColor.RED + " Quests Admin: moddata " + ChatColor - .GRAY.toString() + ChatColor.STRIKETHROUGH + "]=------------"); - sender.sendMessage(ChatColor.GRAY + "The following commands are available: "); - sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests a moddata fullreset " + ChatColor.DARK_GRAY + ": clear a " + - "players quest data file"); - sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests a moddata reset " + ChatColor.DARK_GRAY + ": clear a " + - "players data for specifc quest"); - sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests a moddata start " + ChatColor.DARK_GRAY + ": start a " + - "quest for a player"); - sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests a moddata complete " + ChatColor.DARK_GRAY + ": " + - "complete a quest for a player"); - sender.sendMessage(ChatColor.GRAY + "These commands modify quest progress for players. Use them cautiously. Changes are irreversible."); - } else { - sender.sendMessage(ChatColor.GRAY.toString() + ChatColor.STRIKETHROUGH + "------------=[" + ChatColor.RED + " Quests Admin " + ChatColor.GRAY - .toString() + ChatColor.STRIKETHROUGH + "]=------------"); - sender.sendMessage(ChatColor.GRAY + "The following commands are available: "); - sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests a opengui " + ChatColor.DARK_GRAY + ": view help for opengui"); - sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests a moddata " + ChatColor.DARK_GRAY + ": view help for quest progression"); - sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests a types [type]" + ChatColor.DARK_GRAY + ": view registered task types"); - sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests a info [quest]" + ChatColor.DARK_GRAY + ": see information about loaded quests"); - sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests a reload " + ChatColor.DARK_GRAY + ": reload Quests configuration"); - sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests a config " + ChatColor.DARK_GRAY + ": see detected problems in config"); - sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests a itemstack " + ChatColor.DARK_GRAY + ": print information about the current held ItemStack"); - sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests a update " + ChatColor.DARK_GRAY + ": check for updates"); - sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests a wiki " + ChatColor.DARK_GRAY + ": get a link to the Quests wiki"); - sender.sendMessage(ChatColor.DARK_GRAY + " * " + ChatColor.RED + "/quests a about " + ChatColor.DARK_GRAY + ": get information about Quests"); - } - sender.sendMessage(ChatColor.GRAY.toString() + ChatColor.STRIKETHROUGH + "-----=[" + ChatColor.RED + " requires permission: quests.admin " + - ChatColor.GRAY.toString() + ChatColor.STRIKETHROUGH + "]=-----"); - } - - private List matchTabComplete(String arg, List options) { - List completions = new ArrayList<>(); - StringUtil.copyPartialMatches(arg, options, completions); - Collections.sort(completions); - return completions; - } - - private List tabCompleteCategory(String arg) { - List options = new ArrayList<>(); - for (Category c : plugin.getQuestManager().getCategories()) { - options.add(c.getId()); - } - return matchTabComplete(arg, options); - } - - private List tabCompleteQuests(String arg) { - List options = new ArrayList<>(plugin.getQuestManager().getQuests().keySet()); - return matchTabComplete(arg, options); - } - - @Nullable - @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, @NotNull String alias, @NotNull String[] args) { - if (!Options.TAB_COMPLETE_ENABLED.getBooleanValue(true)) { - return null; - } - if (sender instanceof Player) { - if (args.length == 1) { - List options = new ArrayList<>(Arrays.asList("quest", "category", "started")); - if (sender.hasPermission("quests.admin")) { - options.add("admin"); - } - if (sender.hasPermission("quests.command.random")) { - options.add("random"); - } - return matchTabComplete(args[0], options); - } else if (args.length == 2) { - if (args[0].equalsIgnoreCase("c") || args[0].equalsIgnoreCase("category")) { - return tabCompleteCategory(args[1]); - } else if (args[0].equalsIgnoreCase("q") || args[0].equalsIgnoreCase("quest")) { - return tabCompleteQuests(args[1]); - } else if (args[0].equalsIgnoreCase("a") || args[0].equalsIgnoreCase("admin") - && sender.hasPermission("quests.admin")) { - List options = Arrays.asList("opengui", "moddata", "types", "reload", "update", "config", "info", "wiki", "about"); - return matchTabComplete(args[1], options); - } - } else if (args.length == 3) { - if (args[0].equalsIgnoreCase("q") || args[0].equalsIgnoreCase("quest") - && sender.hasPermission("quests.admin")) { - Quest q = plugin.getQuestManager().getQuestById(args[1]); - if (q != null) { - List options = Arrays.asList("start", "cancel", "track"); - return matchTabComplete(args[2], options); - } - } else if (args[0].equalsIgnoreCase("a") || args[0].equalsIgnoreCase("admin") - && sender.hasPermission("quests.admin")) { - if (args[1].equalsIgnoreCase("types")) { - List options = new ArrayList<>(); - for (TaskType taskType : plugin.getTaskTypeManager().getTaskTypes()) { - options.add(taskType.getType()); - } - return matchTabComplete(args[2], options); - } else if (args[1].equalsIgnoreCase("opengui")) { - List options = Arrays.asList("quests", "category"); - return matchTabComplete(args[2], options); - } else if (args[1].equalsIgnoreCase("moddata")) { - List options = Arrays.asList("fullreset", "reset", "start", "complete"); - return matchTabComplete(args[2], options); - } else if (args[1].equalsIgnoreCase("info")) { - return tabCompleteQuests(args[2]); - } - } - } else if (args.length == 4) { - if (sender.hasPermission("quests.admin")) return null; - } else if (args.length == 5) { - if (args[0].equalsIgnoreCase("a") || args[0].equalsIgnoreCase("admin") - && sender.hasPermission("quests.admin")) { - if (args[1].equalsIgnoreCase("opengui")) { - if (args[2].equalsIgnoreCase("c") || args[2].equalsIgnoreCase("category")) { - return tabCompleteCategory(args[4]); - } - } else if (args[1].equalsIgnoreCase("moddata")) { - if (args[2].equalsIgnoreCase("start") - || args[2].equalsIgnoreCase("complete") - || args[2].equalsIgnoreCase("reset")) { - return tabCompleteQuests(args[4]); - } - } - } - } - } - return Collections.emptyList(); - } -} diff --git a/src/main/java/com/leonardobishop/quests/hook/coreprotect/CoreProtectHook.java b/src/main/java/com/leonardobishop/quests/hook/coreprotect/CoreProtectHook.java deleted file mode 100644 index 60f4e0a4..00000000 --- a/src/main/java/com/leonardobishop/quests/hook/coreprotect/CoreProtectHook.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.leonardobishop.quests.hook.coreprotect; - -import net.coreprotect.CoreProtect; -import net.coreprotect.CoreProtectAPI; -import org.bukkit.Bukkit; -import org.bukkit.block.Block; - -import java.util.List; - -public class CoreProtectHook implements ICoreProtectHook { - - private final CoreProtectAPI api; - - public CoreProtectHook() { - api = ((CoreProtect) Bukkit.getPluginManager().getPlugin("CoreProtect")).getAPI(); - } - - @Override - public boolean checkBlock(Block block, int time) { - List lookup = api.blockLookup(block, time); - if (lookup.isEmpty()) return false; - - String[] result = lookup.get(0); - CoreProtectAPI.ParseResult parseResult = api.parseResult(result); - - return !parseResult.getPlayer().isEmpty() && parseResult.getActionId() == 1; - } - -} diff --git a/src/main/java/com/leonardobishop/quests/hook/coreprotect/CoreProtectNoHook.java b/src/main/java/com/leonardobishop/quests/hook/coreprotect/CoreProtectNoHook.java deleted file mode 100644 index 32916934..00000000 --- a/src/main/java/com/leonardobishop/quests/hook/coreprotect/CoreProtectNoHook.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.leonardobishop.quests.hook.coreprotect; - -import org.bukkit.block.Block; - -public class CoreProtectNoHook implements ICoreProtectHook { - @Override - public boolean checkBlock(Block block, int time) { - return false; - } -} diff --git a/src/main/java/com/leonardobishop/quests/hook/coreprotect/ICoreProtectHook.java b/src/main/java/com/leonardobishop/quests/hook/coreprotect/ICoreProtectHook.java deleted file mode 100644 index 5dc1fa36..00000000 --- a/src/main/java/com/leonardobishop/quests/hook/coreprotect/ICoreProtectHook.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.leonardobishop.quests.hook.coreprotect; - -import org.bukkit.block.Block; - -public interface ICoreProtectHook { - - /** - * Check whether or not the most recent edit to a block was the result of a player. - * - * @param block the block - * @param time the time to look back in seconds - * @return true if from a player - */ - boolean checkBlock(Block block, int time); - -} diff --git a/src/main/java/com/leonardobishop/quests/hook/itemgetter/ItemGetter.java b/src/main/java/com/leonardobishop/quests/hook/itemgetter/ItemGetter.java deleted file mode 100644 index f3a6fc7e..00000000 --- a/src/main/java/com/leonardobishop/quests/hook/itemgetter/ItemGetter.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.leonardobishop.quests.hook.itemgetter; - -import com.leonardobishop.quests.Quests; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.inventory.ItemStack; - -public interface ItemGetter { - - /** - * Gets an ItemStack from a configuration. - * Implementations should specific to the server version. - * - * @param path the path to where the item is defined in the config (null if item is defined in second param) - * @param config the configuration file - * @param plugin Quests plugin instance - * @param excludes exclude certain fields in the configuration - * @return {@link org.bukkit.inventory.ItemStack} - */ - ItemStack getItem(String path, ConfigurationSection config, Quests plugin, Filter... excludes); - - /** - * Gets an ItemStack from a given string (which represents a material). - * For pre-1.13 server implementations, the string may use a data code. - * - * @param material the string - * @return {@link org.bukkit.inventory.ItemStack} - */ - ItemStack getItemStack(String material, Quests plugin); - - /** - * Validates a material from a string. - * For pre-1.13 server implementations, the string may use a data code. - * - * @param material the string - * @return true if it a material - */ - boolean isValidMaterial(String material); - - enum Filter { - DISPLAY_NAME, - LORE, - ENCHANTMENTS, - ITEM_FLAGS, - UNBREAKABLE, - ATTRIBUTE_MODIFIER, - CUSTOM_MODEL_DATA; - } -} \ No newline at end of file diff --git a/src/main/java/com/leonardobishop/quests/hook/itemgetter/ItemGetterLatest.java b/src/main/java/com/leonardobishop/quests/hook/itemgetter/ItemGetterLatest.java deleted file mode 100644 index e1215388..00000000 --- a/src/main/java/com/leonardobishop/quests/hook/itemgetter/ItemGetterLatest.java +++ /dev/null @@ -1,244 +0,0 @@ -package com.leonardobishop.quests.hook.itemgetter; - -import com.leonardobishop.quests.Quests; -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.attribute.Attribute; -import org.bukkit.attribute.AttributeModifier; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.EquipmentSlot; -import org.bukkit.inventory.ItemFlag; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -public class ItemGetterLatest implements ItemGetter { - - /* - supporting: - - name - - material - - lore - - enchantments (NamespacedKey) - - itemflags - - unbreakable - - attribute modifier - - custom model data - - requires at least API version 1.14 - */ - @Override - public ItemStack getItem(String path, ConfigurationSection config, Quests plugin, ItemGetter.Filter... excludes) { - if (path != null && !path.equals("")) { - path = path + "."; - } - List filters = Arrays.asList(excludes); - - String cName = config.getString(path + "name", path + "name"); - String cType = config.getString(path + "item", config.getString(path + "type", path + "item")); - boolean hasCustomModelData = config.contains(path + "custommodeldata"); - int customModelData = config.getInt(path + "custommodeldata", 0); - boolean unbreakable = config.getBoolean(path + "unbreakable", false); - List cLore = config.getStringList(path + "lore"); - List cItemFlags = config.getStringList(path + "itemflags"); - boolean hasAttributeModifiers = config.contains(path + "attributemodifiers"); - List> cAttributeModifiers = config.getMapList(path + "attributemodifiers"); - - String name; - Material type = null; - int data = 0; - - // material - ItemStack is = getItemStack(cType, plugin); - ItemMeta ism = is.getItemMeta(); - - // name - if (!filters.contains(Filter.DISPLAY_NAME)) { - name = ChatColor.translateAlternateColorCodes('&', cName); - ism.setDisplayName(name); - } - - // lore - if (!filters.contains(Filter.LORE)) { - List lore = new ArrayList<>(); - if (cLore != null) { - for (String s : cLore) { - lore.add(ChatColor.translateAlternateColorCodes('&', s)); - } - } - ism.setLore(lore); - } - - // attribute modifiers - if (!filters.contains(Filter.ATTRIBUTE_MODIFIER)) { - if (hasAttributeModifiers) { - for (Map attr : cAttributeModifiers) { - String cAttribute = (String) attr.get("attribute"); - Attribute attribute = null; - for (Attribute enumattr : Attribute.values()) { - if (enumattr.toString().equals(cAttribute)) { - attribute = enumattr; - break; - } - } - - if (attribute == null) continue; - - Map configurationSection = (Map) attr.get("modifier"); - - String cUUID = (String) configurationSection.get("uuid"); - String cModifierName = (String) configurationSection.get("name"); - String cModifierOperation = (String) configurationSection.get("operation"); - double cAmount; - try { - Object cAmountObj = configurationSection.get("amount"); - if (cAmountObj instanceof Integer) { - cAmount = ((Integer) cAmountObj).doubleValue(); - } else { - cAmount = (Double) cAmountObj; - } - } catch (Exception e) { - cAmount = 1; - } - String cEquipmentSlot = (String) configurationSection.get("equipmentslot"); - - UUID uuid = null; - if (cUUID != null) { - try { - uuid = UUID.fromString(cUUID); - } catch (Exception ignored) { - // ignored - } - } - EquipmentSlot equipmentSlot = null; - if (cEquipmentSlot != null) { - try { - equipmentSlot = EquipmentSlot.valueOf(cEquipmentSlot); - } catch (Exception ignored) { - // ignored - } - } - AttributeModifier.Operation operation = AttributeModifier.Operation.ADD_NUMBER; - try { - operation = AttributeModifier.Operation.valueOf(cModifierOperation); - } catch (Exception ignored) { - // ignored - } - - AttributeModifier modifier; - if (uuid == null) { - modifier = new AttributeModifier(cModifierName, cAmount, operation); - } else if (equipmentSlot == null) { - modifier = new AttributeModifier(uuid, cModifierName, cAmount, operation); - } else { - modifier = new AttributeModifier(uuid, cModifierName, cAmount, operation, equipmentSlot); - } - - ism.addAttributeModifier(attribute, modifier); - } - } - } - - // item flags - if (!filters.contains(Filter.ITEM_FLAGS)) { - if (config.isSet(path + "itemflags")) { - for (String flag : cItemFlags) { - for (ItemFlag iflag : ItemFlag.values()) { - if (iflag.toString().equals(flag)) { - ism.addItemFlags(iflag); - break; - } - } - } - } - } - - // custom model data - if (!filters.contains(Filter.CUSTOM_MODEL_DATA)) { - if (hasCustomModelData) { - ism.setCustomModelData(customModelData); - } - } - - // unbreakable - if (!filters.contains(Filter.UNBREAKABLE)) { - ism.setUnbreakable(unbreakable); - } - - // enchantments - if (!filters.contains(Filter.ENCHANTMENTS)) { - if (config.isSet(path + "enchantments")) { - for (String key : config.getStringList(path + "enchantments")) { - String[] split = key.split(":"); - if (split.length < 2) { - plugin.getQuestsLogger().debug("Enchantment does not follow format {namespace}:{name}:{level} : " + key); - continue; - } - String namespace = split[0]; - String ench = split[1]; - String levelName; - if (split.length >= 3) { - levelName = split[2]; - } else { - levelName = "1"; - } - - // TODO i don't know how these namespaces work -// NamespacedKey namespacedKey; -// try { -// namespacedKey = new NamespacedKey(namespace, ench); -// } catch (Exception e) { -// plugin.getQuestsLogger().debug("Unrecognised namespace: " + namespace); -// e.printStackTrace(); -// continue; -// } - Enchantment enchantment; - if ((enchantment = Enchantment.getByName(ench)) == null) { - plugin.getQuestsLogger().debug("Unrecognised enchantment: " + ench); - continue; - } - - int level; - try { - level = Integer.parseInt(levelName); - } catch (NumberFormatException e) { - level = 1; - } - - ism.addEnchant(enchantment, level, true); - } - } - } - - is.setItemMeta(ism); - return is; - } - - @Override - public ItemStack getItemStack(String material, Quests plugin) { - Material type; - try { - type = Material.valueOf(material); - } catch (Exception e) { - plugin.getQuestsLogger().debug("Unrecognised material: " + material); - type = Material.STONE; - } - return new ItemStack(type, 1); - } - - @Override - public boolean isValidMaterial(String material) { - try { - Material.valueOf(material); - return true; - } catch (IllegalArgumentException ex) { - return false; - } - } -} diff --git a/src/main/java/com/leonardobishop/quests/hook/itemgetter/ItemGetter_1_13.java b/src/main/java/com/leonardobishop/quests/hook/itemgetter/ItemGetter_1_13.java deleted file mode 100644 index f25aab0c..00000000 --- a/src/main/java/com/leonardobishop/quests/hook/itemgetter/ItemGetter_1_13.java +++ /dev/null @@ -1,233 +0,0 @@ -package com.leonardobishop.quests.hook.itemgetter; - -import com.leonardobishop.quests.Quests; -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.attribute.Attribute; -import org.bukkit.attribute.AttributeModifier; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.EquipmentSlot; -import org.bukkit.inventory.ItemFlag; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -public class ItemGetter_1_13 implements ItemGetter { - /* - reads the following: - - name - - material - - lore - - enchantments (NamespacedKey) - - itemflags - - unbreakable - - attribute modifier - - requires at least API version 1.13 - */ - @Override - public ItemStack getItem(String path, ConfigurationSection config, Quests plugin, ItemGetter.Filter... excludes) { - if (path != null && !path.equals("")) { - path = path + "."; - } - List filters = Arrays.asList(excludes); - - String cName = config.getString(path + "name", path + "name"); - String cType = config.getString(path + "item", config.getString(path + "type", path + "item")); - boolean unbreakable = config.getBoolean(path + "unbreakable", false); - List cLore = config.getStringList(path + "lore"); - List cItemFlags = config.getStringList(path + "itemflags"); - boolean hasAttributeModifiers = config.contains(path + "attributemodifiers"); - List> cAttributeModifiers = config.getMapList(path + "attributemodifiers"); - - String name; - Material type = null; - int data = 0; - - // material - ItemStack is = getItemStack(cType, plugin); - ItemMeta ism = is.getItemMeta(); - - // name - if (!filters.contains(Filter.DISPLAY_NAME)) { - name = ChatColor.translateAlternateColorCodes('&', cName); - ism.setDisplayName(name); - } - - // lore - if (!filters.contains(Filter.LORE)) { - List lore = new ArrayList<>(); - if (cLore != null) { - for (String s : cLore) { - lore.add(ChatColor.translateAlternateColorCodes('&', s)); - } - } - ism.setLore(lore); - } - - // attribute modifiers - if (!filters.contains(Filter.ATTRIBUTE_MODIFIER)) { - if (hasAttributeModifiers) { - for (Map attr : cAttributeModifiers) { - String cAttribute = (String) attr.get("attribute"); - Attribute attribute = null; - for (Attribute enumattr : Attribute.values()) { - if (enumattr.toString().equals(cAttribute)) { - attribute = enumattr; - break; - } - } - - if (attribute == null) continue; - - Map configurationSection = (Map) attr.get("modifier"); - - String cUUID = (String) configurationSection.get("uuid"); - String cModifierName = (String) configurationSection.get("name"); - String cModifierOperation = (String) configurationSection.get("operation"); - double cAmount; - try { - Object cAmountObj = configurationSection.get("amount"); - if (cAmountObj instanceof Integer) { - cAmount = ((Integer) cAmountObj).doubleValue(); - } else { - cAmount = (Double) cAmountObj; - } - } catch (Exception e) { - cAmount = 1; - } - String cEquipmentSlot = (String) configurationSection.get("equipmentslot"); - - UUID uuid = null; - if (cUUID != null) { - try { - uuid = UUID.fromString(cUUID); - } catch (Exception ignored) { - // ignored - } - } - EquipmentSlot equipmentSlot = null; - if (cEquipmentSlot != null) { - try { - equipmentSlot = EquipmentSlot.valueOf(cEquipmentSlot); - } catch (Exception ignored) { - // ignored - } - } - AttributeModifier.Operation operation = AttributeModifier.Operation.ADD_NUMBER; - try { - operation = AttributeModifier.Operation.valueOf(cModifierOperation); - } catch (Exception ignored) { - // ignored - } - - AttributeModifier modifier; - if (uuid == null) { - modifier = new AttributeModifier(cModifierName, cAmount, operation); - } else if (equipmentSlot == null) { - modifier = new AttributeModifier(uuid, cModifierName, cAmount, operation); - } else { - modifier = new AttributeModifier(uuid, cModifierName, cAmount, operation, equipmentSlot); - } - - ism.addAttributeModifier(attribute, modifier); - } - } - } - - // item flags - if (!filters.contains(Filter.ITEM_FLAGS)) { - if (config.isSet(path + "itemflags")) { - for (String flag : cItemFlags) { - for (ItemFlag iflag : ItemFlag.values()) { - if (iflag.toString().equals(flag)) { - ism.addItemFlags(iflag); - break; - } - } - } - } - } - - // unbreakable - if (!filters.contains(Filter.UNBREAKABLE)) { - ism.setUnbreakable(unbreakable); - } - - // enchantments - if (!filters.contains(Filter.ENCHANTMENTS)) { - if (config.isSet(path + "enchantments")) { - for (String key : config.getStringList(path + "enchantments")) { - String[] split = key.split(":"); - if (split.length < 2) { - plugin.getQuestsLogger().debug("Enchantment does not follow format {namespace}:{name}:{level} : " + key); - continue; - } - String namespace = split[0]; - String ench = split[1]; - String levelName; - if (split.length >= 3) { - levelName = split[2]; - } else { - levelName = "1"; - } - - // TODO i don't know how these namespaces work -// NamespacedKey namespacedKey; -// try { -// namespacedKey = new NamespacedKey(namespace, ench); -// } catch (Exception e) { -// plugin.getQuestsLogger().debug("Unrecognised namespace: " + namespace); -// e.printStackTrace(); -// continue; -// } - Enchantment enchantment; - if ((enchantment = Enchantment.getByName(ench)) == null) { - plugin.getQuestsLogger().debug("Unrecognised enchantment: " + ench); - continue; - } - - int level; - try { - level = Integer.parseInt(levelName); - } catch (NumberFormatException e) { - level = 1; - } - - is.addUnsafeEnchantment(enchantment, level); - } - } - } - - is.setItemMeta(ism); - return is; - } - - @Override - public ItemStack getItemStack(String material, Quests plugin) { - Material type; - try { - type = Material.valueOf(material); - } catch (Exception e) { - plugin.getQuestsLogger().debug("Unrecognised material: " + material); - type = Material.STONE; - } - return new ItemStack(type, 1); - } - - @Override - public boolean isValidMaterial(String material) { - try { - Material.valueOf(material); - return true; - } catch (IllegalArgumentException ex) { - return false; - } - } -} diff --git a/src/main/java/com/leonardobishop/quests/hook/itemgetter/ItemGetter_Late_1_8.java b/src/main/java/com/leonardobishop/quests/hook/itemgetter/ItemGetter_Late_1_8.java deleted file mode 100644 index 84525cfb..00000000 --- a/src/main/java/com/leonardobishop/quests/hook/itemgetter/ItemGetter_Late_1_8.java +++ /dev/null @@ -1,161 +0,0 @@ -package com.leonardobishop.quests.hook.itemgetter; - -import com.leonardobishop.quests.Quests; -import org.apache.commons.lang.StringUtils; -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.ItemFlag; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.regex.Pattern; - -public class ItemGetter_Late_1_8 implements ItemGetter { - /* - reads the following: - - name - - material (+ DATA) - - lore - - enchantments (NOT NamespacedKey) - - itemflags - - requires at least API version 1.8 (?) - */ - @Override - public ItemStack getItem(String path, ConfigurationSection config, Quests plugin, Filter... excludes) { - if (path != null && !path.equals("")) { - path = path + "."; - } - List filters = Arrays.asList(excludes); - - - String cName = config.getString(path + "name", path + "name"); - String cType = config.getString(path + "item", config.getString(path + "type", path + "item")); - List cLore = config.getStringList(path + "lore"); - List cItemFlags = config.getStringList(path + "itemflags"); - - String name; - Material type = null; - int data = 0; - - // material - ItemStack is = getItemStack(cType, plugin); - ItemMeta ism = is.getItemMeta(); - - // lore - if (!filters.contains(Filter.LORE)) { - List lore = new ArrayList<>(); - if (cLore != null) { - for (String s : cLore) { - lore.add(ChatColor.translateAlternateColorCodes('&', s)); - } - } - ism.setLore(lore); - } - - // name - if (!filters.contains(Filter.DISPLAY_NAME)) { - name = ChatColor.translateAlternateColorCodes('&', cName); - ism.setDisplayName(name); - } - - - // item flags - if (!filters.contains(Filter.ITEM_FLAGS)) { - if (config.isSet(path + "itemflags")) { - for (String flag : cItemFlags) { - for (ItemFlag iflag : ItemFlag.values()) { - if (iflag.toString().equals(flag)) { - ism.addItemFlags(iflag); - break; - } - } - } - } - } - - // enchantments - if (!filters.contains(Filter.ENCHANTMENTS)) { - if (config.isSet(path + "enchantments")) { - for (String key : config.getStringList(path + "enchantments")) { - String[] split = key.split(":"); - String ench = split[0]; - String levelName; - if (split.length >= 2) { - levelName = split[1]; - } else { - levelName = "1"; - } - - Enchantment enchantment; - if ((enchantment = Enchantment.getByName(ench)) == null) { - plugin.getQuestsLogger().debug("Unrecognised enchantment: " + ench); - continue; - } - - int level; - try { - level = Integer.parseInt(levelName); - } catch (NumberFormatException e) { - level = 1; - } - - ism.addEnchant(enchantment, level, true); - } - } - } - - is.setItemMeta(ism); - return is; - } - - - @Override - public ItemStack getItemStack(String material, Quests plugin) { - Material type = null; - int data = 0; - - if (Material.getMaterial(material) != null) { - type = Material.getMaterial(material); - } else if (material.contains(":")) { - String[] parts = material.split(Pattern.quote(":")); - if (parts.length > 1) { - if (Material.getMaterial(parts[0]) != null) { - type = Material.getMaterial(parts[0]); - } - if (StringUtils.isNumeric(parts[1])) { - data = Integer.parseInt(parts[1]); - } - } - } - - if (type == null) { - plugin.getQuestsLogger().debug("Unrecognised material: " + material); - type = Material.STONE; - } - return new ItemStack(type, 1, (short) data); - } - - @Override - public boolean isValidMaterial(String material) { - Material type = null; - - if (Material.getMaterial(material) != null) { - type = Material.getMaterial(material); - } else if (material.contains(":")) { - String[] parts = material.split(Pattern.quote(":")); - if (parts.length > 1) { - if (Material.getMaterial(parts[0]) != null) { - type = Material.getMaterial(parts[0]); - } - } - } - - return !(type == null); - } -} diff --git a/src/main/java/com/leonardobishop/quests/hook/papi/IPlaceholderAPIHook.java b/src/main/java/com/leonardobishop/quests/hook/papi/IPlaceholderAPIHook.java deleted file mode 100644 index 454ee02e..00000000 --- a/src/main/java/com/leonardobishop/quests/hook/papi/IPlaceholderAPIHook.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.leonardobishop.quests.hook.papi; - -import com.leonardobishop.quests.Quests; -import org.bukkit.entity.Player; - -public interface IPlaceholderAPIHook { - - String replacePlaceholders(Player player, String text); - - void registerExpansion(Quests plugin); - - void unregisterExpansion(); - -} diff --git a/src/main/java/com/leonardobishop/quests/hook/papi/PlaceholderAPIHook.java b/src/main/java/com/leonardobishop/quests/hook/papi/PlaceholderAPIHook.java deleted file mode 100644 index 8fd86efc..00000000 --- a/src/main/java/com/leonardobishop/quests/hook/papi/PlaceholderAPIHook.java +++ /dev/null @@ -1,28 +0,0 @@ -package com.leonardobishop.quests.hook.papi; - -import com.leonardobishop.quests.Quests; -import com.leonardobishop.quests.api.QuestsPlaceholders; -import me.clip.placeholderapi.PlaceholderAPI; -import org.bukkit.entity.Player; - -public class PlaceholderAPIHook implements IPlaceholderAPIHook { - - private QuestsPlaceholders placeholder; - - public String replacePlaceholders(Player player, String text) { - return PlaceholderAPI.setPlaceholders(player, text); - } - - @Override - public void registerExpansion(Quests plugin) { - placeholder = new QuestsPlaceholders(plugin); - placeholder.register(); - } - - @Override - public void unregisterExpansion() { - placeholder.unregister(); - } - - -} diff --git a/src/main/java/com/leonardobishop/quests/hook/title/Title.java b/src/main/java/com/leonardobishop/quests/hook/title/Title.java deleted file mode 100644 index ea8f1f57..00000000 --- a/src/main/java/com/leonardobishop/quests/hook/title/Title.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.leonardobishop.quests.hook.title; - -import org.bukkit.entity.Player; - -public interface Title { - - void sendTitle(Player player, String message, String submessage); -} \ No newline at end of file diff --git a/src/main/java/com/leonardobishop/quests/hook/title/Title_Bukkit.java b/src/main/java/com/leonardobishop/quests/hook/title/Title_Bukkit.java deleted file mode 100644 index 34b22f6b..00000000 --- a/src/main/java/com/leonardobishop/quests/hook/title/Title_Bukkit.java +++ /dev/null @@ -1,12 +0,0 @@ -package com.leonardobishop.quests.hook.title; - -import org.bukkit.entity.Player; - -public class Title_Bukkit implements Title { - - // new title function with timings - @Override - public void sendTitle(Player player, String message, String submessage) { - player.sendTitle(message, submessage, 10, 100, 10); - } -} diff --git a/src/main/java/com/leonardobishop/quests/hook/title/Title_BukkitNoTimings.java b/src/main/java/com/leonardobishop/quests/hook/title/Title_BukkitNoTimings.java deleted file mode 100644 index d0f44fe6..00000000 --- a/src/main/java/com/leonardobishop/quests/hook/title/Title_BukkitNoTimings.java +++ /dev/null @@ -1,13 +0,0 @@ -package com.leonardobishop.quests.hook.title; - -import org.bukkit.entity.Player; - -public class Title_BukkitNoTimings implements Title { - - // this one is for 1.8, 1.9 and 1.10 where there was no timings method - @Override - public void sendTitle(Player player, String message, String submessage) { - player.sendTitle(message, submessage); - } - -} diff --git a/src/main/java/com/leonardobishop/quests/hook/title/Title_Other.java b/src/main/java/com/leonardobishop/quests/hook/title/Title_Other.java deleted file mode 100644 index 419bf657..00000000 --- a/src/main/java/com/leonardobishop/quests/hook/title/Title_Other.java +++ /dev/null @@ -1,11 +0,0 @@ -package com.leonardobishop.quests.hook.title; - -import org.bukkit.entity.Player; - -public class Title_Other implements Title { - - @Override - public void sendTitle(Player player, String message, String submessage) { - // title function does not exist - } -} diff --git a/src/main/java/com/leonardobishop/quests/listener/MenuController.java b/src/main/java/com/leonardobishop/quests/listener/MenuController.java deleted file mode 100644 index 117a797c..00000000 --- a/src/main/java/com/leonardobishop/quests/listener/MenuController.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.leonardobishop.quests.listener; - -import com.leonardobishop.quests.Quests; -import com.leonardobishop.quests.menu.QMenu; -import org.bukkit.entity.HumanEntity; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.event.inventory.InventoryCloseEvent; -import org.bukkit.event.inventory.InventoryType; - -import java.util.HashMap; -import java.util.UUID; - -public class MenuController implements Listener { - - private final HashMap tracker = new HashMap<>(); - private final Quests plugin; - - public MenuController(Quests plugin) { - this.plugin = plugin; - } - - public void openMenu(HumanEntity player, QMenu qMenu, int page) { - player.openInventory(qMenu.toInventory(page)); - tracker.put(player.getUniqueId(), qMenu); - } - - @EventHandler - private void onClose(InventoryCloseEvent event) { - tracker.remove(event.getPlayer().getUniqueId()); - } - - @EventHandler - private void onClick(InventoryClickEvent event) { - // check if the player has a quest menu open - if (tracker.containsKey(event.getWhoClicked().getUniqueId())) { - event.setCancelled(true); - if (event.getClickedInventory() == null) - return; //The player clicked outside the inventory - if (event.getClickedInventory().getType() == InventoryType.PLAYER) - return; //The clicked inventory is a player inventory type - - QMenu qMenu = tracker.get(event.getWhoClicked().getUniqueId()); - qMenu.handleClick(event, this); - } - } - -} diff --git a/src/main/java/com/leonardobishop/quests/listener/PlayerJoinListener.java b/src/main/java/com/leonardobishop/quests/listener/PlayerJoinListener.java deleted file mode 100644 index 53916c32..00000000 --- a/src/main/java/com/leonardobishop/quests/listener/PlayerJoinListener.java +++ /dev/null @@ -1,48 +0,0 @@ -package com.leonardobishop.quests.listener; - -import com.leonardobishop.quests.Quests; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.util.Messages; -import com.leonardobishop.quests.util.Options; -import org.bukkit.Bukkit; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.Listener; -import org.bukkit.event.player.AsyncPlayerPreLoginEvent; -import org.bukkit.event.player.PlayerJoinEvent; - -import java.util.UUID; - -public class PlayerJoinListener implements Listener { - - private final Quests plugin; - - public PlayerJoinListener(Quests plugin) { - this.plugin = plugin; - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onAsyncJoin(AsyncPlayerPreLoginEvent event) { - plugin.getPlayerManager().loadPlayer(event.getUniqueId()); - } - - @EventHandler - public void onEvent(PlayerJoinEvent event) { - UUID playerUuid = event.getPlayer().getUniqueId(); - plugin.getPlayerManager().loadPlayer(playerUuid); - if (plugin.getDescription().getVersion().contains("beta") && event.getPlayer().hasPermission("quests.admin")) { - event.getPlayer().sendMessage(Messages.BETA_REMINDER.getMessage()); - } - if (plugin.getUpdater().isUpdateReady() && event.getPlayer().hasPermission("quests.admin")) { - // delay for a bit so they actually see the message - Bukkit.getScheduler().runTaskLater(this.plugin, () -> event.getPlayer().sendMessage(plugin.getUpdater().getMessage()), 50L); - } - - QPlayer qPlayer = plugin.getPlayerManager().getPlayer(playerUuid); - if (qPlayer == null) return; - - // run a full check to check for any missed quest completions - plugin.getQuestCompleter().queueFullCheck(qPlayer.getQuestProgressFile()); - } - -} diff --git a/src/main/java/com/leonardobishop/quests/listener/PlayerLeaveListener.java b/src/main/java/com/leonardobishop/quests/listener/PlayerLeaveListener.java deleted file mode 100644 index d246e1f6..00000000 --- a/src/main/java/com/leonardobishop/quests/listener/PlayerLeaveListener.java +++ /dev/null @@ -1,26 +0,0 @@ -package com.leonardobishop.quests.listener; - -import com.leonardobishop.quests.Quests; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgressFile; -import org.bukkit.Bukkit; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.player.PlayerQuitEvent; - -public class PlayerLeaveListener implements Listener { - - private final Quests plugin; - - public PlayerLeaveListener(Quests plugin) { - this.plugin = plugin; - } - - @EventHandler - public void onEvent(PlayerQuitEvent event) { - QPlayer qPlayer = plugin.getPlayerManager().getPlayer(event.getPlayer().getUniqueId()); - if (qPlayer == null) return; - plugin.getPlayerManager().removePlayer(qPlayer.getPlayerUUID()); - } - -} diff --git a/src/main/java/com/leonardobishop/quests/menu/CancelQMenu.java b/src/main/java/com/leonardobishop/quests/menu/CancelQMenu.java deleted file mode 100644 index 12186348..00000000 --- a/src/main/java/com/leonardobishop/quests/menu/CancelQMenu.java +++ /dev/null @@ -1,81 +0,0 @@ -package com.leonardobishop.quests.menu; - -import com.leonardobishop.quests.listener.MenuController; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.util.Items; -import com.leonardobishop.quests.util.Options; -import org.bukkit.Bukkit; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; - -/** - * Represents a cancellation confirmation menu for a specific quest. - */ -public class CancelQMenu implements QMenu { - - private final QMenu superMenu; - private final QPlayer owner; - private final Quest quest; - - public CancelQMenu(QPlayer owner, QMenu superMenu, Quest quest) { - this.owner = owner; - this.superMenu = superMenu; - this.quest = quest; - } - - public Quest getQuest() { - return quest; - } - - @Override - public QPlayer getOwner() { - return owner; - } - - public Inventory toInventory(int page) { - String title = Options.color(Options.GUITITLE_QUEST_CANCEL.getStringValue()); - - ItemStack yes = Items.QUEST_CANCEL_YES.getItem(); - ItemStack no = Items.QUEST_CANCEL_NO.getItem(); - - ItemStack background = Items.QUEST_CANCEL_BACKGROUND.getItem(); - ItemMeta backgroundMeta = background.getItemMeta(); - backgroundMeta.setDisplayName(" "); - background.setItemMeta(backgroundMeta); - - Inventory inventory = Bukkit.createInventory(null, 27, title); - - for (int i = 0; i < inventory.getSize(); i++) { - inventory.setItem(i, background); - } - - inventory.setItem(10, no); - inventory.setItem(11, no); - inventory.setItem(12, no); - inventory.setItem(13, quest.getDisplayItem().toItemStack(quest, owner, owner.getQuestProgressFile().getQuestProgress(quest))); - inventory.setItem(14, yes); - inventory.setItem(15, yes); - inventory.setItem(16, yes); - - return inventory; - } - - @Override - public void handleClick(InventoryClickEvent event, MenuController controller) { - if (event.getSlot() == 10 || event.getSlot() == 11 || event.getSlot() == 12) { - controller.openMenu(event.getWhoClicked(), superMenu, 1); - } else if (event.getSlot() == 14 || event.getSlot() == 15 || event.getSlot() == 16) { - if (owner.cancelQuest(quest)) { - event.getWhoClicked().closeInventory(); - } - } - } - - public QMenu getSuperMenu() { - return superMenu; - } - -} diff --git a/src/main/java/com/leonardobishop/quests/menu/CategoryQMenu.java b/src/main/java/com/leonardobishop/quests/menu/CategoryQMenu.java deleted file mode 100644 index 3afb4eb4..00000000 --- a/src/main/java/com/leonardobishop/quests/menu/CategoryQMenu.java +++ /dev/null @@ -1,168 +0,0 @@ -package com.leonardobishop.quests.menu; - -import com.leonardobishop.quests.Quests; -import com.leonardobishop.quests.listener.MenuController; -import com.leonardobishop.quests.menu.element.CategoryMenuElement; -import com.leonardobishop.quests.menu.element.CustomMenuElement; -import com.leonardobishop.quests.menu.element.MenuElement; -import com.leonardobishop.quests.menu.element.SpacerMenuElement; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.util.Items; -import com.leonardobishop.quests.util.Messages; -import com.leonardobishop.quests.util.Options; -import org.apache.commons.lang.math.NumberUtils; -import org.bukkit.Bukkit; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Represents a menu which contains a listing of different categories. - */ -public class CategoryQMenu implements QMenu { - - private final Quests plugin; - private final HashMap menuElements = new HashMap<>(); - private final QPlayer owner; - - private int pageSize = 45; - private int maxElement = 0; - private int pagePrevLocation = -1; - private int pageNextLocation = -1; - private int currentPage = -1; - - public CategoryQMenu(Quests plugin, QPlayer owner) { - this.plugin = plugin; - this.owner = owner; - } - - public void populate(List menuQuests) { - if (plugin.getConfig().isConfigurationSection("custom-elements.categories")) { - for (String s : plugin.getConfig().getConfigurationSection("custom-elements.categories").getKeys(false)) { - if (!NumberUtils.isNumber(s)) continue; - int slot = Integer.parseInt(s); - int repeat = plugin.getConfig().getInt("custom-elements.categories." + s + ".repeat"); - MenuElement menuElement; - if (plugin.getConfig().contains("custom-elements.categories." + s + ".display")) { - ItemStack is = plugin.getItemStack("custom-elements.categories." + s + ".display", plugin.getConfig()); - menuElement = new CustomMenuElement(is); - } else if (plugin.getConfig().getBoolean("custom-elements.categories." + s + ".spacer", false)) { - menuElement = new SpacerMenuElement(); - } else continue; // user = idiot - - for (int i = 0; i <= repeat; i++) { - menuElements.put(slot + i, menuElement); - } - } - } - int slot = 0; - for (QuestQMenu questQMenu : menuQuests) { - while (menuElements.containsKey(slot)) slot++; - if (Options.GUI_HIDE_CATEGORIES_NOPERMISSION.getBooleanValue() && plugin.getQuestManager().getCategoryById(questQMenu.getCategoryName()).isPermissionRequired()) { - if (!Bukkit.getPlayer(owner.getPlayerUUID()).hasPermission("quests.category." + questQMenu.getCategoryName())) { - continue; - } - } - menuElements.put(slot, new CategoryMenuElement(plugin, owner.getPlayerUUID(), questQMenu)); - slot++; - } - - for (Integer integer : menuElements.keySet()) { - if (integer + 1 > maxElement) maxElement = integer + 1; - } - - // stop bottom row of pg1 going to pg2 if entire inv contents would fit on pg1 perfectly - if (maxElement > 45 && maxElement <= 54) { - pageSize = 54; - } else { - pageSize = 45; - } - } - - @Override - public QPlayer getOwner() { - return owner; - } - - public Inventory toInventory(int page) { - currentPage = page; - int pageMin = pageSize * (page - 1); - int pageMax = pageSize * page; - String title = Options.color(Options.GUITITLE_QUESTS_CATEGORY.getStringValue()); - - ItemStack pageIs; - ItemStack pagePrevIs; - ItemStack pageNextIs; - Inventory inventory = Bukkit.createInventory(null, 54, title); - - int highestOnPage = 0; - for (int pointer = pageMin; pointer < pageMax; pointer++) { - if (menuElements.containsKey(pointer)) { - inventory.setItem(pointer - ((page - 1) * pageSize), menuElements.get(pointer).asItemStack()); - if (pointer + 1 > highestOnPage) highestOnPage = pointer + 1; - } - } - - pageNextLocation = -1; - pagePrevLocation = -1; - - Map pageplaceholders = new HashMap<>(); - pageplaceholders.put("{prevpage}", String.valueOf(page - 1)); - pageplaceholders.put("{nextpage}", String.valueOf(page + 1)); - pageplaceholders.put("{page}", String.valueOf(page)); - pageIs = MenuUtil.applyPlaceholders(plugin, owner.getPlayerUUID(), Items.PAGE_DESCRIPTION.getItem(), pageplaceholders); - pageIs.setAmount(Math.min(page, 64)); - pagePrevIs = MenuUtil.applyPlaceholders(plugin, owner.getPlayerUUID(), Items.PAGE_PREV.getItem(), pageplaceholders); - pageNextIs = MenuUtil.applyPlaceholders(plugin, owner.getPlayerUUID(), Items.PAGE_NEXT.getItem(), pageplaceholders); - - if (maxElement > pageSize) { - inventory.setItem(49, pageIs); - if (page != 1) { - inventory.setItem(48, pagePrevIs); - pagePrevLocation = 48; - } - if (Math.ceil((double) maxElement / ((double) pageSize)) != page) { - inventory.setItem(50, pageNextIs); - pageNextLocation = 50; - } - } else if (Options.TRIM_GUI_SIZE.getBooleanValue() && page == 1) { - int inventorySize = highestOnPage + (9 - highestOnPage % 9) * Math.min(1, highestOnPage % 9); - inventorySize = inventorySize <= 0 ? 9 : inventorySize; - if (inventorySize == 54) { - return inventory; - } - - Inventory trimmedInventory = Bukkit.createInventory(null, inventorySize, title); - - for (int slot = 0; slot < trimmedInventory.getSize(); slot++) { - trimmedInventory.setItem(slot, inventory.getItem(slot)); - } - return trimmedInventory; - } - return inventory; - } - - @Override - public void handleClick(InventoryClickEvent event, MenuController controller) { - if (pagePrevLocation == event.getSlot()) { - controller.openMenu(event.getWhoClicked(), this, currentPage - 1); - - } else if (pageNextLocation == event.getSlot()) { - controller.openMenu(event.getWhoClicked(), this, currentPage + 1); - - } else if (event.getSlot() < pageSize && menuElements.containsKey(event.getSlot() + (((currentPage) - 1) * pageSize))) { - MenuElement element = menuElements.get(event.getSlot() + ((currentPage - 1) * pageSize)); - if (element instanceof CategoryMenuElement) { - CategoryMenuElement categoryMenuElement = (CategoryMenuElement) element; - QuestQMenu questQMenu = categoryMenuElement.getQuestMenu(); - if (owner.openCategory(plugin.getQuestManager().getCategoryById(questQMenu.getCategoryName()), questQMenu) != 0) { - event.getWhoClicked().sendMessage(Messages.QUEST_CATEGORY_PERMISSION.getMessage()); - } - } - } - } -} diff --git a/src/main/java/com/leonardobishop/quests/menu/DailyQMenu.java b/src/main/java/com/leonardobishop/quests/menu/DailyQMenu.java deleted file mode 100644 index 0d6080cd..00000000 --- a/src/main/java/com/leonardobishop/quests/menu/DailyQMenu.java +++ /dev/null @@ -1,98 +0,0 @@ -package com.leonardobishop.quests.menu; - -import com.leonardobishop.quests.Quests; -import com.leonardobishop.quests.api.enums.QuestStartResult; -import com.leonardobishop.quests.listener.MenuController; -import com.leonardobishop.quests.menu.element.MenuElement; -import com.leonardobishop.quests.menu.element.QuestMenuElement; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.controller.DailyQuestController; -import com.leonardobishop.quests.quest.controller.QuestController; -import com.leonardobishop.quests.util.Items; -import com.leonardobishop.quests.util.Options; -import org.bukkit.Bukkit; -import org.bukkit.event.inventory.ClickType; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Represents a cancellation confirmation menu for a specific quest. - */ -public class DailyQMenu implements QMenu { - - private final Map menuElements = new HashMap<>(); - private final Quests plugin; - private final QPlayer owner; - - public DailyQMenu(Quests plugin, QPlayer owner) { - this.plugin = plugin; - this.owner = owner; - } - - @Override - public QPlayer getOwner() { - return owner; - } - - public void populate() { - if (!(owner.getQuestController() instanceof DailyQuestController)) { - return; - } - DailyQuestController dailyQuestController = (DailyQuestController) owner.getQuestController(); - List quests = dailyQuestController.getQuests(); - for (int i = 0; i < quests.size(); i++) { - menuElements.put(11 + i, new QuestMenuElement(plugin, owner, quests.get(i))); - } - } - - public Inventory toInventory(int page) { - String title = Options.color(Options.GUITITLE_DAILY_QUESTS.getStringValue()); - - ItemStack background = Items.QUEST_CANCEL_BACKGROUND.getItem(); - ItemMeta backgroundMeta = background.getItemMeta(); - backgroundMeta.setDisplayName(" "); - background.setItemMeta(backgroundMeta); - - Inventory inventory = Bukkit.createInventory(null, 27, title); - - for (int i = 0; i < inventory.getSize(); i++) { - inventory.setItem(i, background); - } - - for (int pointer = 0; pointer < 27; pointer++) { - if (menuElements.containsKey(pointer)) { - inventory.setItem(pointer, menuElements.get(pointer).asItemStack()); - } - } - - return inventory; - } - - @Override - public void handleClick(InventoryClickEvent event, MenuController controller) { - if (menuElements.containsKey(event.getSlot())) { - MenuElement menuElement = menuElements.get(event.getSlot()); - if (menuElement instanceof QuestMenuElement) { - QuestMenuElement questMenuElement = (QuestMenuElement) menuElement; - Quest quest = plugin.getQuestManager().getQuestById(questMenuElement.getQuestId()); - if (event.getClick() == ClickType.LEFT) { - if (Options.QUEST_AUTOSTART.getBooleanValue()) return; - if (owner.startQuest(quest) == QuestStartResult.QUEST_SUCCESS) { - event.getWhoClicked().closeInventory(); //TODO Option to keep the menu open - } - } else if (event.getClick() == ClickType.MIDDLE && Options.ALLOW_QUEST_TRACK.getBooleanValue()) { - MenuUtil.handleMiddleClick(this, quest, Bukkit.getPlayer(owner.getPlayerUUID()), controller); - } - } - } - } - - -} diff --git a/src/main/java/com/leonardobishop/quests/menu/MenuUtil.java b/src/main/java/com/leonardobishop/quests/menu/MenuUtil.java deleted file mode 100644 index 2f04a4f2..00000000 --- a/src/main/java/com/leonardobishop/quests/menu/MenuUtil.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.leonardobishop.quests.menu; - -import com.leonardobishop.quests.Quests; -import com.leonardobishop.quests.listener.MenuController; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.util.Options; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -public class MenuUtil { - - public static ItemStack applyPlaceholders(Quests plugin, UUID owner, ItemStack is) { - return applyPlaceholders(plugin, owner, is, Collections.emptyMap()); - } - - public static ItemStack applyPlaceholders(Quests plugin, UUID owner, ItemStack is, Map placeholders) { - ItemStack newItemStack = is.clone(); - List lore = newItemStack.getItemMeta().getLore(); - List newLore = new ArrayList<>(); - ItemMeta ism = newItemStack.getItemMeta(); - Player player = Bukkit.getPlayer(owner); - if (lore != null) { - for (String s : lore) { - for (Map.Entry entry : placeholders.entrySet()) { - s = s.replace(entry.getKey(), entry.getValue()); - if (plugin.getPlaceholderAPIHook() != null && Options.GUI_USE_PLACEHOLDERAPI.getBooleanValue()) { - s = plugin.getPlaceholderAPIHook().replacePlaceholders(player, s); - } - } - newLore.add(s); - } - } - for (Map.Entry entry : placeholders.entrySet()) { - ism.setDisplayName(ism.getDisplayName().replace(entry.getKey(), entry.getValue())); - if (plugin.getPlaceholderAPIHook() != null && Options.GUI_USE_PLACEHOLDERAPI.getBooleanValue()) { - ism.setDisplayName(plugin.getPlaceholderAPIHook().replacePlaceholders(player, ism.getDisplayName())); - } - } - ism.setLore(newLore); - newItemStack.setItemMeta(ism); - return newItemStack; - } - - public static void handleMiddleClick(QMenu menu, Quest quest, Player player, MenuController controller) { - if (menu.getOwner().hasStartedQuest(quest)) { - String tracked = menu.getOwner().getPlayerPreferences().getTrackedQuestId(); - - if (quest.getId().equals(tracked)) { - menu.getOwner().trackQuest(null); - } else { - menu.getOwner().trackQuest(quest); - } - player.closeInventory(); - } - } - - public static void handleRightClick(QMenu menu, Quest quest, Player player, MenuController controller) { - if (menu.getOwner().hasStartedQuest(quest)) { - if (Options.QUEST_AUTOSTART.getBooleanValue()) return; - CancelQMenu cancelQMenu = new CancelQMenu(menu.getOwner(), menu, quest); - controller.openMenu(player, cancelQMenu, 1); - } - } - -} diff --git a/src/main/java/com/leonardobishop/quests/menu/QItemStack.java b/src/main/java/com/leonardobishop/quests/menu/QItemStack.java deleted file mode 100644 index 81568605..00000000 --- a/src/main/java/com/leonardobishop/quests/menu/QItemStack.java +++ /dev/null @@ -1,151 +0,0 @@ -package com.leonardobishop.quests.menu; - -import com.leonardobishop.quests.Quests; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.util.Options; -import org.bukkit.Bukkit; -import org.bukkit.enchantments.Enchantment; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemFlag; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; - -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class QItemStack { - - private final Quests plugin; - - private String name; - private List loreNormal; - private List loreStarted; - private final List globalLoreAppendNormal; - private final List globalLoreAppendNotStarted; - private final List globalLoreAppendStarted; - private final List globalLoreAppendTracked; - private ItemStack startingItemStack; - - public QItemStack(Quests plugin, String name, List loreNormal, List loreStarted, ItemStack startingItemStack) { - this.plugin = plugin; - this.name = name; - this.loreNormal = loreNormal; - this.loreStarted = loreStarted; - this.startingItemStack = startingItemStack; - - this.globalLoreAppendNormal = Options.color(Options.GLOBAL_QUEST_DISPLAY_LORE_APPEND_NORMAL.getStringListValue()); - this.globalLoreAppendNotStarted = Options.color(Options.GLOBAL_QUEST_DISPLAY_LORE_APPEND_NOT_STARTED.getStringListValue()); - this.globalLoreAppendStarted = Options.color(Options.GLOBAL_QUEST_DISPLAY_LORE_APPEND_STARTED.getStringListValue()); - this.globalLoreAppendTracked = Options.color(Options.GLOBAL_QUEST_DISPLAY_LORE_APPEND_TRACKED.getStringListValue()); - } - - public String getName() { - return name; - } - - public void setName(String name) { - this.name = name; - } - - public List getLoreNormal() { - return loreNormal; - } - - public void setLoreNormal(List loreNormal) { - this.loreNormal = loreNormal; - } - - public List getLoreStarted() { - return loreStarted; - } - - public void setLoreStarted(List loreStarted) { - this.loreStarted = loreStarted; - } - - public ItemStack getStartingItemStack() { - return startingItemStack; - } - - public void setStartingItemStack(ItemStack startingItemStack) { - this.startingItemStack = startingItemStack; - } - - @SuppressWarnings("deprecation") - public ItemStack toItemStack(Quest quest, QPlayer qPlayer, QuestProgress questProgress) { - ItemStack is = new ItemStack(startingItemStack); - ItemMeta ism = is.getItemMeta(); - ism.setDisplayName(name); - List formattedLore = new ArrayList<>(); - List tempLore = new ArrayList<>(); - - if (Options.GLOBAL_QUEST_DISPLAY_CONFIGURATION_OVERRIDE.getBooleanValue() && !globalLoreAppendNormal.isEmpty()) { - tempLore.addAll(globalLoreAppendNormal); - } else { - tempLore.addAll(loreNormal); - tempLore.addAll(globalLoreAppendNormal); - } - - Player player = Bukkit.getPlayer(qPlayer.getPlayerUUID()); - if (qPlayer.hasStartedQuest(quest)) { - boolean tracked = quest.getId().equals(qPlayer.getPlayerPreferences().getTrackedQuestId()); - if (!Options.GLOBAL_QUEST_DISPLAY_CONFIGURATION_OVERRIDE.getBooleanValue() || globalLoreAppendStarted.isEmpty()) { - tempLore.addAll(loreStarted); - } - if (tracked) { - tempLore.addAll(globalLoreAppendTracked); - } else { - tempLore.addAll(globalLoreAppendStarted); - } - ism.addEnchant(Enchantment.ARROW_INFINITE, 1, true); - try { - ism.addItemFlags(ItemFlag.HIDE_ENCHANTS); - ism.addItemFlags(ItemFlag.HIDE_ATTRIBUTES); - } catch (Exception ignored) { - - } - } else { - tempLore.addAll(globalLoreAppendNotStarted); - } - if (plugin.getPlaceholderAPIHook() != null && Options.GUI_USE_PLACEHOLDERAPI.getBooleanValue()) { - ism.setDisplayName(plugin.getPlaceholderAPIHook().replacePlaceholders(player, ism.getDisplayName())); - } - if (questProgress != null) { - for (String s : tempLore) { - s = processPlaceholders(s, questProgress); - if (plugin.getPlaceholderAPIHook() != null && Options.GUI_USE_PLACEHOLDERAPI.getBooleanValue()) { - s = plugin.getPlaceholderAPIHook().replacePlaceholders(player, s); - } - formattedLore.add(s); - } - } - ism.setLore(formattedLore); - is.setItemMeta(ism); - return is; - } - - public static String processPlaceholders(String s, QuestProgress questProgress) { - Matcher m = Pattern.compile("\\{([^}]+)}").matcher(s); - while (m.find()) { - String[] parts = m.group(1).split(":"); - if (parts.length > 1) { - if (questProgress.getTaskProgress(parts[0]) == null) { - continue; - } - if (parts[1].equals("progress")) { - String str = String.valueOf(questProgress.getTaskProgress(parts[0]).getProgress()); - s = s.replace("{" + m.group(1) + "}", (str.equals("null") ? String.valueOf(0) : str)); - } - if (parts[1].equals("complete")) { - String str = String.valueOf(questProgress.getTaskProgress(parts[0]).isCompleted()); - s = s.replace("{" + m.group(1) + "}", str); - } - } - } - return s; - } -} diff --git a/src/main/java/com/leonardobishop/quests/menu/QMenu.java b/src/main/java/com/leonardobishop/quests/menu/QMenu.java deleted file mode 100644 index 6b793c77..00000000 --- a/src/main/java/com/leonardobishop/quests/menu/QMenu.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.leonardobishop.quests.menu; - -import com.leonardobishop.quests.listener.MenuController; -import com.leonardobishop.quests.player.QPlayer; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.inventory.Inventory; - -public interface QMenu { - - QPlayer getOwner(); - Inventory toInventory(int page); - void handleClick(InventoryClickEvent event, MenuController controller); - -} diff --git a/src/main/java/com/leonardobishop/quests/menu/QuestQMenu.java b/src/main/java/com/leonardobishop/quests/menu/QuestQMenu.java deleted file mode 100644 index af655886..00000000 --- a/src/main/java/com/leonardobishop/quests/menu/QuestQMenu.java +++ /dev/null @@ -1,286 +0,0 @@ -package com.leonardobishop.quests.menu; - -import com.leonardobishop.quests.Quests; -import com.leonardobishop.quests.api.enums.QuestStartResult; -import com.leonardobishop.quests.listener.MenuController; -import com.leonardobishop.quests.menu.element.CustomMenuElement; -import com.leonardobishop.quests.menu.element.MenuElement; -import com.leonardobishop.quests.menu.element.QuestMenuElement; -import com.leonardobishop.quests.menu.element.SpacerMenuElement; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.util.Items; -import com.leonardobishop.quests.util.Options; -import org.apache.commons.lang.math.NumberUtils; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.event.inventory.ClickType; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Represents a menu for a specified category (or all if they are disabled), - * which contains a listing of different quests. - */ -public class QuestQMenu implements QMenu { - - private final Quests plugin; - private final HashMap menuElements = new HashMap<>(); - private final CategoryQMenu superMenu; - private final String categoryName; - private final int pageSize = 45; - private final QPlayer owner; - - private int maxElement = 0; - private int backButtonLocation = -1; - private int pagePrevLocation = -1; - private int pageNextLocation = -1; - private int currentPage = -1; - private boolean backButtonEnabled = true; - - public QuestQMenu(Quests plugin, QPlayer owner, String categoryName, CategoryQMenu superMenu) { - this.plugin = plugin; - this.owner = owner; - this.categoryName = categoryName; - this.superMenu = superMenu; - } - - public void populate(List quests) { - String path; - if (Options.CATEGORIES_ENABLED.getBooleanValue()) { - path = "custom-elements.c:" + categoryName; - } else { - path = "custom-elements.quests"; - } - if (plugin.getConfig().isConfigurationSection(path)) { - for (String s : plugin.getConfig().getConfigurationSection(path).getKeys(false)) { - if (!NumberUtils.isNumber(s)) continue; - int slot = Integer.parseInt(s); - int repeat = plugin.getConfig().getInt(path + "." + s + ".repeat"); - MenuElement menuElement; - if (plugin.getConfig().contains(path + "." + s + ".display")) { - ItemStack is = plugin.getItemStack(path + "." + s + ".display", plugin.getConfig()); - menuElement = new CustomMenuElement(is); - } else if (plugin.getConfig().getBoolean(path + "." + s + ".spacer", false)) { - menuElement = new SpacerMenuElement(); - } else continue; // user = idiot - - for (int i = 0; i <= repeat; i++) { - menuElements.put(slot + i, menuElement); - } - } - } - - Collections.sort(quests); - int slot = 0; - for (Quest quest : quests) { - while (menuElements.containsKey(slot)) slot++; - if (Options.GUI_HIDE_LOCKED.getBooleanValue()) { - QuestProgress questProgress = owner.getQuestProgressFile().getQuestProgress(quest); - long cooldown = owner.getQuestProgressFile().getCooldownFor(quest); - if (!owner.getQuestProgressFile().hasMetRequirements(quest) || (!quest.isRepeatable() && questProgress.isCompletedBefore()) || cooldown > 0) { - continue; - } - } - if (Options.GUI_HIDE_QUESTS_NOPERMISSION.getBooleanValue() && quest.isPermissionRequired()) { - if (!Bukkit.getPlayer(owner.getPlayerUUID()).hasPermission("quests.quest." + quest.getId())) { - continue; - } - } - menuElements.put(slot, new QuestMenuElement(plugin, owner, quest.getId())); - slot++; - } - - for (Integer integer : menuElements.keySet()) { - if (integer + 1 > maxElement) maxElement = integer + 1; - } - } - - @Override - public QPlayer getOwner() { - return owner; - } - - public String getCategoryName() { - return categoryName; - } - - public int getPagePrevLocation() { - return pagePrevLocation; - } - - public int getPageNextLocation() { - return pageNextLocation; - } - - public int getCurrentPage() { - return currentPage; - } - - public int getPageSize() { - return pageSize; - } - - public Inventory toInventory(int page) { - currentPage = page; - int pageMin = pageSize * (page - 1); - int pageMax = pageSize * page; - String title = Options.color(Options.GUITITLE_QUESTS.getStringValue()); - - ItemStack pageIs; - ItemStack pagePrevIs; - ItemStack pageNextIs; - ItemStack back = Items.BACK_BUTTON.getItem(); - - Inventory inventory = Bukkit.createInventory(null, 54, title); - - int highestOnPage = 0; - for (int pointer = pageMin; pointer < pageMax; pointer++) { - if (menuElements.containsKey(pointer)) { - inventory.setItem(pointer - ((page - 1) * pageSize), menuElements.get(pointer).asItemStack()); - if (pointer + 1 > highestOnPage) highestOnPage = pointer + 1; - } - } - - pageNextLocation = -1; - pagePrevLocation = -1; - - Map pageplaceholders = new HashMap<>(); - pageplaceholders.put("{prevpage}", String.valueOf(page - 1)); - pageplaceholders.put("{nextpage}", String.valueOf(page + 1)); - pageplaceholders.put("{page}", String.valueOf(page)); - pageIs = replaceItemStack(Items.PAGE_DESCRIPTION.getItem(), pageplaceholders); - pageIs.setAmount(Math.min(page, 64)); - pagePrevIs = replaceItemStack(Items.PAGE_PREV.getItem(), pageplaceholders); - pageNextIs = replaceItemStack(Items.PAGE_NEXT.getItem(), pageplaceholders); - - if (Options.CATEGORIES_ENABLED.getBooleanValue() && backButtonEnabled) { - inventory.setItem(45, back); - backButtonLocation = 45; - } - if (maxElement > pageSize) { - inventory.setItem(49, pageIs); - if (page != 1) { - inventory.setItem(48, pagePrevIs); - pagePrevLocation = 48; - } - if (Math.ceil((double) maxElement / ((double) pageSize)) != page) { - inventory.setItem(50, pageNextIs); - pageNextLocation = 50; - } - } else if (Options.TRIM_GUI_SIZE.getBooleanValue() && page == 1) { - int inventorySize = highestOnPage + (9 - highestOnPage % 9) * Math.min(1, highestOnPage % 9); - inventorySize = inventorySize <= 0 ? 9 : inventorySize; - if (inventorySize == 54) { - return inventory; - } else if (Options.CATEGORIES_ENABLED.getBooleanValue() && backButtonEnabled) { - inventorySize += 9; - } - - Inventory trimmedInventory = Bukkit.createInventory(null, inventorySize, title); - - for (int slot = 0; slot < trimmedInventory.getSize(); slot++) { - if (slot >= (trimmedInventory.getSize() - 9) && backButtonEnabled){ - if (Options.CATEGORIES_ENABLED.getBooleanValue()) { - trimmedInventory.setItem(slot, back); - backButtonLocation = slot; - } - break; - } - trimmedInventory.setItem(slot, inventory.getItem(slot)); - } - return trimmedInventory; - } - - return inventory; - } - - @Override - public void handleClick(InventoryClickEvent event, MenuController controller) { - //TODO maybe redo this maybe - if (pagePrevLocation == event.getSlot()) { - controller.openMenu(event.getWhoClicked(), this, currentPage - 1); - - } else if (pageNextLocation == event.getSlot()) { - controller.openMenu(event.getWhoClicked(), this, currentPage + 1); - - } else if (Options.CATEGORIES_ENABLED.getBooleanValue() && backButtonLocation == event.getSlot()) { - controller.openMenu(event.getWhoClicked(), superMenu, 1); - - } else if (event.getSlot() < pageSize && menuElements.containsKey(event.getSlot() + (((currentPage) - 1) * pageSize))) { - MenuElement menuElement = menuElements.get(event.getSlot() + ((currentPage - 1) * pageSize)); - if (menuElement instanceof QuestMenuElement) { - QuestMenuElement questMenuElement = (QuestMenuElement) menuElement; - Quest quest = plugin.getQuestManager().getQuestById(questMenuElement.getQuestId()); - if (event.getClick() == ClickType.LEFT) { - if (Options.QUEST_AUTOSTART.getBooleanValue()) return; - if (owner.startQuest(quest) == QuestStartResult.QUEST_SUCCESS) { - event.getWhoClicked().closeInventory(); //TODO Option to keep the menu open - } - } else if (event.getClick() == ClickType.MIDDLE && Options.ALLOW_QUEST_TRACK.getBooleanValue()) { - MenuUtil.handleMiddleClick(this, quest, Bukkit.getPlayer(owner.getPlayerUUID()), controller); - } else if (event.getClick() == ClickType.RIGHT && Options.ALLOW_QUEST_CANCEL.getBooleanValue() - && owner.hasStartedQuest(quest)) { - MenuUtil.handleRightClick(this, quest, Bukkit.getPlayer(owner.getPlayerUUID()), controller); - } - } - } - } - - public boolean isBackButtonEnabled() { - return backButtonEnabled; - } - - public void setBackButtonEnabled(boolean backButtonEnabled) { - this.backButtonEnabled = backButtonEnabled; - } - - public int getBackButtonLocation() { - return backButtonLocation; - } - - public CategoryQMenu getSuperMenu() { - return superMenu; - } - - public ItemStack replaceItemStack(ItemStack is) { - return replaceItemStack(is, Collections.emptyMap()); - } - - public ItemStack replaceItemStack(ItemStack is, Map placeholders) { - ItemStack newItemStack = is.clone(); - List lore = newItemStack.getItemMeta().getLore(); - List newLore = new ArrayList<>(); - ItemMeta ism = newItemStack.getItemMeta(); - Player player = Bukkit.getPlayer(owner.getPlayerUUID()); - if (lore != null) { - for (String s : lore) { - for (Map.Entry entry : placeholders.entrySet()) { - s = s.replace(entry.getKey(), entry.getValue()); - if (plugin.getPlaceholderAPIHook() != null && Options.GUI_USE_PLACEHOLDERAPI.getBooleanValue()) { - s = plugin.getPlaceholderAPIHook().replacePlaceholders(player, s); - } - } - newLore.add(s); - } - } - for (Map.Entry entry : placeholders.entrySet()) { - ism.setDisplayName(ism.getDisplayName().replace(entry.getKey(), entry.getValue())); - if (plugin.getPlaceholderAPIHook() != null && Options.GUI_USE_PLACEHOLDERAPI.getBooleanValue()) { - ism.setDisplayName(plugin.getPlaceholderAPIHook().replacePlaceholders(player, ism.getDisplayName())); - } - } - ism.setLore(newLore); - newItemStack.setItemMeta(ism); - return newItemStack; - } -} diff --git a/src/main/java/com/leonardobishop/quests/menu/QuestSortWrapper.java b/src/main/java/com/leonardobishop/quests/menu/QuestSortWrapper.java deleted file mode 100644 index 2d15ac87..00000000 --- a/src/main/java/com/leonardobishop/quests/menu/QuestSortWrapper.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.leonardobishop.quests.menu; - -import com.leonardobishop.quests.Quests; -import com.leonardobishop.quests.quest.Category; -import com.leonardobishop.quests.quest.Quest; - -public class QuestSortWrapper implements Comparable { - - private int weightedSortOrder; - private final Quest quest; - - public QuestSortWrapper(Quests plugin, Quest quest) { - this.quest = quest; - if (quest.getCategoryId() == null) { - weightedSortOrder = quest.getSortOrder(); - return; - } - Category c = plugin.getQuestManager().getCategoryById(quest.getCategoryId()); - if (c != null) { - int index = plugin.getQuestManager().getCategories().indexOf(c); - int amountBelow = 0; - //TODO precalculate - for (int i = index; i > 0; i--) { - Category below = plugin.getQuestManager().getCategories().get(i - 1); - amountBelow += below.getRegisteredQuestIds().size(); - } - weightedSortOrder = amountBelow + quest.getSortOrder(); - } - } - - public int getWeightedSortOrder() { - return weightedSortOrder; - } - - public Quest getQuest() { - return quest; - } - - @Override - public int compareTo(QuestSortWrapper quest) { - return (weightedSortOrder - quest.weightedSortOrder); - } - -} diff --git a/src/main/java/com/leonardobishop/quests/menu/StartedQMenu.java b/src/main/java/com/leonardobishop/quests/menu/StartedQMenu.java deleted file mode 100644 index 317d2839..00000000 --- a/src/main/java/com/leonardobishop/quests/menu/StartedQMenu.java +++ /dev/null @@ -1,173 +0,0 @@ -package com.leonardobishop.quests.menu; - -import com.leonardobishop.quests.Quests; -import com.leonardobishop.quests.listener.MenuController; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.util.Items; -import com.leonardobishop.quests.util.Options; -import org.bukkit.Bukkit; -import org.bukkit.event.inventory.ClickType; -import org.bukkit.event.inventory.InventoryClickEvent; -import org.bukkit.inventory.Inventory; -import org.bukkit.inventory.ItemStack; - -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * Represents a menu listing quests the player has started. - */ -public class StartedQMenu implements QMenu { - - private final Quests plugin; - private final HashMap slotsToQuestIds = new HashMap<>(); - private final int pageSize = 45; - private final QPlayer owner; - - private int pagePrevLocation = -1; - private int pageNextLocation = -1; - private int currentPage = -1; - - public StartedQMenu(Quests plugin, QPlayer owner) { - this.plugin = plugin; - this.owner = owner; - } - - public void populate(List quests) { - Collections.sort(quests); - int slot = 0; - for (QuestSortWrapper quest : quests) { - if (owner.hasStartedQuest(quest.getQuest())) { - slotsToQuestIds.put(slot, quest.getQuest().getId()); - slot++; - } - } - } - - public HashMap getSlotsToMenu() { - return slotsToQuestIds; - } - - @Override - public QPlayer getOwner() { - return owner; - } - - public int getPagePrevLocation() { - return pagePrevLocation; - } - - public int getPageNextLocation() { - return pageNextLocation; - } - - public int getCurrentPage() { - return currentPage; - } - - public int getPageSize() { - return pageSize; - } - - public Inventory toInventory(int page) { - currentPage = page; - int pageMin = pageSize * (page - 1); - int pageMax = pageSize * page; - String title = Options.color(Options.GUITITLE_QUESTS_STARTED.getStringValue()); - - ItemStack pageIs; - ItemStack pagePrevIs; - ItemStack pageNextIs; - ItemStack none = Items.NO_STARTED_QUESTS.getItem(); - - Inventory inventory = Bukkit.createInventory(null, 54, title); - - int invSlot = 0; - if (!slotsToQuestIds.isEmpty()) { - for (int pointer = pageMin; pointer < pageMax; pointer++) { - if (slotsToQuestIds.containsKey(pointer)) { - Quest quest = plugin.getQuestManager().getQuestById(slotsToQuestIds.get(pointer)); - QuestProgress questProgress = owner.getQuestProgressFile().getQuestProgress(quest); - - inventory.setItem(invSlot, MenuUtil.applyPlaceholders(plugin, owner.getPlayerUUID(), plugin.getQuestManager().getQuestById( - quest.getId()).getDisplayItem().toItemStack(quest, owner, questProgress))); - } - invSlot++; - } - } else { - inventory.setItem(4, none); - } - - pageNextLocation = -1; - pagePrevLocation = -1; - - Map pageplaceholders = new HashMap<>(); - pageplaceholders.put("{prevpage}", String.valueOf(page - 1)); - pageplaceholders.put("{nextpage}", String.valueOf(page + 1)); - pageplaceholders.put("{page}", String.valueOf(page)); - pageIs = MenuUtil.applyPlaceholders(plugin, owner.getPlayerUUID(), Items.PAGE_DESCRIPTION.getItem(), pageplaceholders); - pageIs.setAmount(Math.min(page, 64)); - pagePrevIs = MenuUtil.applyPlaceholders(plugin, owner.getPlayerUUID(), Items.PAGE_PREV.getItem(), pageplaceholders); - pageNextIs = MenuUtil.applyPlaceholders(plugin, owner.getPlayerUUID(), Items.PAGE_NEXT.getItem(), pageplaceholders); - - if (slotsToQuestIds.size() > pageSize) { - inventory.setItem(49, pageIs); - if (page != 1) { - inventory.setItem(48, pagePrevIs); - pagePrevLocation = 48; - } - if (Math.ceil((double) slotsToQuestIds.size() / ((double) 45)) != page) { - inventory.setItem(50, pageNextIs); - pageNextLocation = 50; - } - } else if (Options.TRIM_GUI_SIZE.getBooleanValue() && page == 1) { - int slotsUsed = 0; - for (int pointer = 0; pointer < pageMax; pointer++) { - if (inventory.getItem(pointer) != null) { - slotsUsed++; - } - } - - int inventorySize = (slotsUsed >= 54) ? 54 : slotsUsed + (9 - slotsUsed % 9) * Math.min(1, slotsUsed % 9); - inventorySize = inventorySize <= 0 ? 9 : inventorySize; - if (inventorySize == 54) { - return inventory; - } - - Inventory trimmedInventory = Bukkit.createInventory(null, inventorySize, title); - - for (int slot = 0; slot < trimmedInventory.getSize(); slot++) { - trimmedInventory.setItem(slot, inventory.getItem(slot)); - } - return trimmedInventory; - } - - return inventory; - } - - @Override - public void handleClick(InventoryClickEvent event, MenuController controller) { - if (pagePrevLocation == event.getSlot()) { - controller.openMenu(event.getWhoClicked(), this, currentPage - 1); - - } else if (pageNextLocation == event.getSlot()) { - controller.openMenu(event.getWhoClicked(), this, currentPage + 1); - - } else if (event.getSlot() < pageSize && slotsToQuestIds.containsKey(event.getSlot() + ((currentPage) - 1) * pageSize)) { - - // repeat from above - String questid = slotsToQuestIds.get(event.getSlot() + (((currentPage) - 1) * pageSize)); - Quest quest = plugin.getQuestManager().getQuestById(questid); - if (event.getClick() == ClickType.MIDDLE && Options.ALLOW_QUEST_TRACK.getBooleanValue()) { - MenuUtil.handleMiddleClick(this, quest, Bukkit.getPlayer(owner.getPlayerUUID()), controller); - } else if (event.getClick() == ClickType.RIGHT && Options.ALLOW_QUEST_CANCEL.getBooleanValue() - && owner.hasStartedQuest(quest)) { - MenuUtil.handleRightClick(this, quest, Bukkit.getPlayer(owner.getPlayerUUID()), controller); - } - } - } -} diff --git a/src/main/java/com/leonardobishop/quests/menu/element/CategoryMenuElement.java b/src/main/java/com/leonardobishop/quests/menu/element/CategoryMenuElement.java deleted file mode 100644 index 13d8a734..00000000 --- a/src/main/java/com/leonardobishop/quests/menu/element/CategoryMenuElement.java +++ /dev/null @@ -1,65 +0,0 @@ -package com.leonardobishop.quests.menu.element; - -import com.leonardobishop.quests.Quests; -import com.leonardobishop.quests.menu.QuestQMenu; -import com.leonardobishop.quests.quest.Category; -import com.leonardobishop.quests.util.Options; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; - -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; - -public class CategoryMenuElement extends MenuElement { - - private final Quests plugin; - private final UUID owner; - private final QuestQMenu questMenu; - - public CategoryMenuElement(Quests plugin, UUID owner, QuestQMenu questMenu) { - this.plugin = plugin; - this.owner = owner; - this.questMenu = questMenu; - } - - public UUID getOwner() { - return owner; - } - - public QuestQMenu getQuestMenu() { - return questMenu; - } - - @Override - public ItemStack asItemStack() { - Category category = plugin.getQuestManager().getCategoryById(questMenu.getCategoryName()); - if (category != null) { - return replaceItemStack(category.getDisplayItem()); - } - return null; - } - - private ItemStack replaceItemStack(ItemStack is) { - if (plugin.getPlaceholderAPIHook() != null && Options.GUI_USE_PLACEHOLDERAPI.getBooleanValue()) { - ItemStack newItemStack = is.clone(); - List lore = newItemStack.getItemMeta().getLore(); - List newLore = new ArrayList<>(); - ItemMeta ism = newItemStack.getItemMeta(); - Player player = Bukkit.getPlayer(owner); - ism.setDisplayName(plugin.getPlaceholderAPIHook().replacePlaceholders(player, ism.getDisplayName())); - if (lore != null) { - for (String s : lore) { - s = plugin.getPlaceholderAPIHook().replacePlaceholders(player, s); - newLore.add(s); - } - } - ism.setLore(newLore); - newItemStack.setItemMeta(ism); - return newItemStack; - } - return is; - } -} diff --git a/src/main/java/com/leonardobishop/quests/menu/element/CustomMenuElement.java b/src/main/java/com/leonardobishop/quests/menu/element/CustomMenuElement.java deleted file mode 100644 index d1986f18..00000000 --- a/src/main/java/com/leonardobishop/quests/menu/element/CustomMenuElement.java +++ /dev/null @@ -1,17 +0,0 @@ -package com.leonardobishop.quests.menu.element; - -import org.bukkit.inventory.ItemStack; - -public class CustomMenuElement extends MenuElement{ - - private ItemStack itemStack; - - public CustomMenuElement(ItemStack itemStack) { - this.itemStack = itemStack; - } - - @Override - public ItemStack asItemStack() { - return itemStack; - } -} diff --git a/src/main/java/com/leonardobishop/quests/menu/element/MenuElement.java b/src/main/java/com/leonardobishop/quests/menu/element/MenuElement.java deleted file mode 100644 index a7ee580a..00000000 --- a/src/main/java/com/leonardobishop/quests/menu/element/MenuElement.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.leonardobishop.quests.menu.element; - -import org.bukkit.inventory.ItemStack; - -public abstract class MenuElement { - - public abstract ItemStack asItemStack(); - -} diff --git a/src/main/java/com/leonardobishop/quests/menu/element/QuestMenuElement.java b/src/main/java/com/leonardobishop/quests/menu/element/QuestMenuElement.java deleted file mode 100644 index 6d13c0c5..00000000 --- a/src/main/java/com/leonardobishop/quests/menu/element/QuestMenuElement.java +++ /dev/null @@ -1,114 +0,0 @@ -package com.leonardobishop.quests.menu.element; - -import com.leonardobishop.quests.Quests; -import com.leonardobishop.quests.api.enums.QuestStartResult; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.util.Items; -import com.leonardobishop.quests.util.Options; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; -import org.bukkit.inventory.meta.ItemMeta; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -public class QuestMenuElement extends MenuElement { - - private final Quests plugin; - private final QPlayer owner; - private final String questId; - - public QuestMenuElement(Quests plugin, QPlayer owner, String questId) { - this.plugin = plugin; - this.owner = owner; - this.questId = questId; - } - - public QPlayer getOwner() { - return owner; - } - - public String getQuestId() { - return questId; - } - - @Override - public ItemStack asItemStack() { - Quest quest = plugin.getQuestManager().getQuestById(questId); - QuestProgress questProgress = owner.getQuestProgressFile().getQuestProgress(quest); - QuestStartResult status = owner.canStartQuest(quest); - long cooldown = owner.getQuestProgressFile().getCooldownFor(quest); - if (status == QuestStartResult.QUEST_LOCKED) { - List quests = new ArrayList<>(); - for (String requirement : quest.getRequirements()) { - Quest requirementQuest = Quests.get().getQuestManager().getQuestById(requirement); - if (!owner.getQuestProgressFile().hasQuestProgress(requirementQuest) || - !owner.getQuestProgressFile().getQuestProgress(requirementQuest).isCompletedBefore()) { - quests.add(requirementQuest.getDisplayNameStripped()); - } - } - Map placeholders = new HashMap<>(); - placeholders.put("{quest}", quest.getDisplayNameStripped()); - placeholders.put("{requirements}", String.join(", ", quests)); - ItemStack is = replaceItemStack(Items.QUEST_LOCKED.getItem(), placeholders); - return is; - } else if (status == QuestStartResult.QUEST_ALREADY_COMPLETED) { - Map placeholders = new HashMap<>(); - placeholders.put("{quest}", quest.getDisplayNameStripped()); - ItemStack is = replaceItemStack(Items.QUEST_COMPLETED.getItem(), placeholders); - return is; - } else if (status == QuestStartResult.QUEST_NO_PERMISSION) { - Map placeholders = new HashMap<>(); - placeholders.put("{quest}", quest.getDisplayNameStripped()); - ItemStack is = replaceItemStack(Items.QUEST_PERMISSION.getItem(), placeholders); - return is; - } else if (cooldown > 0) { - Map placeholders = new HashMap<>(); - placeholders.put("{time}", plugin.convertToFormat(TimeUnit.SECONDS.convert(cooldown, TimeUnit.MILLISECONDS))); - placeholders.put("{quest}", quest.getDisplayNameStripped()); - ItemStack is = replaceItemStack(Items.QUEST_COOLDOWN.getItem(), placeholders); - return is; - } else { - return replaceItemStack(quest.getDisplayItem().toItemStack(quest, owner, questProgress)); - } - } - - private ItemStack replaceItemStack(ItemStack is) { - return replaceItemStack(is, Collections.emptyMap()); - } - - private ItemStack replaceItemStack(ItemStack is, Map placeholders) { - ItemStack newItemStack = is.clone(); - List lore = newItemStack.getItemMeta().getLore(); - List newLore = new ArrayList<>(); - ItemMeta ism = newItemStack.getItemMeta(); - Player player = Bukkit.getPlayer(owner.getPlayerUUID()); - if (lore != null) { - for (String s : lore) { - for (Map.Entry entry : placeholders.entrySet()) { - s = s.replace(entry.getKey(), entry.getValue()); - if (plugin.getPlaceholderAPIHook() != null && Options.GUI_USE_PLACEHOLDERAPI.getBooleanValue()) { - s = plugin.getPlaceholderAPIHook().replacePlaceholders(player, s); - } - } - newLore.add(s); - } - } - for (Map.Entry entry : placeholders.entrySet()) { - ism.setDisplayName(ism.getDisplayName().replace(entry.getKey(), entry.getValue())); - if (plugin.getPlaceholderAPIHook() != null && Options.GUI_USE_PLACEHOLDERAPI.getBooleanValue()) { - ism.setDisplayName(plugin.getPlaceholderAPIHook().replacePlaceholders(player, ism.getDisplayName())); - } - } - ism.setLore(newLore); - newItemStack.setItemMeta(ism); - return newItemStack; - } -} diff --git a/src/main/java/com/leonardobishop/quests/menu/element/SpacerMenuElement.java b/src/main/java/com/leonardobishop/quests/menu/element/SpacerMenuElement.java deleted file mode 100644 index e2859718..00000000 --- a/src/main/java/com/leonardobishop/quests/menu/element/SpacerMenuElement.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.leonardobishop.quests.menu.element; - -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; - -/** - * literally has the sole purpose of returning Material.AIR - */ -public class SpacerMenuElement extends MenuElement { - - @Override - public ItemStack asItemStack() { - return new ItemStack(Material.AIR); - } -} diff --git a/src/main/java/com/leonardobishop/quests/player/QPlayer.java b/src/main/java/com/leonardobishop/quests/player/QPlayer.java deleted file mode 100644 index e8dc3306..00000000 --- a/src/main/java/com/leonardobishop/quests/player/QPlayer.java +++ /dev/null @@ -1,279 +0,0 @@ -package com.leonardobishop.quests.player; - -import com.leonardobishop.quests.util.QuestMode; -import com.leonardobishop.quests.Quests; -import com.leonardobishop.quests.api.enums.QuestStartResult; -import com.leonardobishop.quests.api.events.PlayerFinishQuestEvent; -import com.leonardobishop.quests.api.events.PlayerStartTrackQuestEvent; -import com.leonardobishop.quests.api.events.PlayerStopTrackQuestEvent; -import com.leonardobishop.quests.menu.CategoryQMenu; -import com.leonardobishop.quests.menu.DailyQMenu; -import com.leonardobishop.quests.menu.QuestQMenu; -import com.leonardobishop.quests.menu.QuestSortWrapper; -import com.leonardobishop.quests.menu.StartedQMenu; -import com.leonardobishop.quests.player.questprogressfile.QPlayerPreferences; -import com.leonardobishop.quests.player.questprogressfile.QuestProgressFile; -import com.leonardobishop.quests.quest.Category; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.controller.QuestController; -import com.leonardobishop.quests.util.Messages; -import com.leonardobishop.quests.util.Options; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.UUID; - -/** - * Represents a player. - */ -public class QPlayer { - - private final Quests plugin; - private final UUID uuid; - private final QPlayerPreferences playerPreferences; - private final QuestProgressFile questProgressFile; - private QuestController questController; - - public QPlayer(Quests plugin, UUID uuid, QPlayerPreferences playerPreferences, QuestProgressFile questProgressFile, QuestController questController) { - this.plugin = plugin; - this.uuid = uuid; - this.playerPreferences = playerPreferences; - this.questProgressFile = questProgressFile; - this.questController = questController; - } - - public UUID getPlayerUUID() { - return this.uuid; - } - - /** - * Attempt to complete a quest for the player. This will also play all effects (such as titles, messages etc.) - * and also dispatches all rewards for the player. - * - * Warning: rewards will not be sent and the {@link PlayerFinishQuestEvent} will not be fired if the - * player is not online - * - * @param quest the quest to complete - * @return true (always) - */ - public boolean completeQuest(Quest quest) { - return questController.completeQuestForPlayer(this, quest); - } - - /** - * Attempt to track a quest for the player. This will also play all effects (such as titles, messages etc.) - * - * Warning: {@link PlayerStopTrackQuestEvent} is not fired if the player is not online - * - * @param quest the quest to track - */ - public void trackQuest(Quest quest) { - Player player = Bukkit.getPlayer(uuid); - if (quest == null) { - String currentTrackedQuestId = playerPreferences.getTrackedQuestId(); - playerPreferences.setTrackedQuestId(null); - if (player != null) { - Bukkit.getPluginManager().callEvent(new PlayerStopTrackQuestEvent(player, this)); - Quest currentTrackedQuest; - if (currentTrackedQuestId != null && (currentTrackedQuest = plugin.getQuestManager().getQuestById(currentTrackedQuestId)) != null) { - player.sendMessage(Messages.QUEST_TRACK_STOP.getMessage().replace("{quest}", currentTrackedQuest.getDisplayNameStripped())); - } - } - } else if (hasStartedQuest(quest)) { - playerPreferences.setTrackedQuestId(quest.getId()); - if (player != null) { - Bukkit.getPluginManager().callEvent(new PlayerStartTrackQuestEvent(player, this)); - player.sendMessage(Messages.QUEST_TRACK.getMessage().replace("{quest}", quest.getDisplayNameStripped())); - } - } - } - - /** - * Gets whether or not the player has started a specific quest. - * - * @param quest the quest to test for - * @return true if the quest is started or quest autostart is enabled and the quest is ready to start, false otherwise - */ - public boolean hasStartedQuest(Quest quest) { - return questController.hasPlayerStartedQuest(this, quest); - } - - /** - * Attempt to start a quest for the player. This will also play all effects (such as titles, messages etc.) - * - * Warning: will fail if the player is not online. - * - * @param quest the quest to start - * @return the quest start result -- {@code QuestStartResult.QUEST_SUCCESS} indicates success - */ - // TODO PlaceholderAPI support - public QuestStartResult startQuest(Quest quest) { - return questController.startQuestForPlayer(this, quest); - } - - /** - * Attempt to cancel a quest for the player. This will also play all effects (such as titles, messages etc.) - * - * @param quest the quest to start - * @return true if the quest was cancelled, false otherwise - */ - public boolean cancelQuest(Quest quest) { - return questController.cancelQuestForPlayer(this, quest); - } - - /** - * Check if the player can start a quest. - * - * Warning: will fail if the player is not online. - * - * @param quest the quest to check - * @return the quest start result - */ - public QuestStartResult canStartQuest(Quest quest) { - return questController.canPlayerStartQuest(this, quest); - } - - /** - * Opens a category menu for the player. - * - * @return 0 if success, 1 if no permission, 2 is only data loaded, 3 if player not found - */ - public int openCategory(Category category, CategoryQMenu superMenu, boolean backButton) { - Player player = Bukkit.getPlayer(this.uuid); - if (player == null) { - return 3; - } - - if (category.isPermissionRequired() && !player.hasPermission("quests.category." + category.getId())) { - return 1; - } - - // Using `this` instead of searching again for this QPlayer - QuestQMenu questQMenu = new QuestQMenu(plugin, this, category.getId(), superMenu); - List quests = new ArrayList<>(); - for (String questid : category.getRegisteredQuestIds()) { - Quest quest = plugin.getQuestManager().getQuestById(questid); - if (quest != null) { - quests.add(quest); - } - } - questQMenu.populate(quests); - questQMenu.setBackButtonEnabled(backButton); - return openCategory(category, questQMenu); - } - - /** - * Opens a category menu for the player. - * - * @return 0 if success, 1 if no permission, 2 is only data loaded, 3 if player not found - */ - public int openCategory(Category category, QuestQMenu questQMenu) { - Player player = Bukkit.getPlayer(this.uuid); - if (player == null) { - return 3; - } - - if (category.isPermissionRequired() && !player.hasPermission("quests.category." + category.getId())) { - return 1; - } - - plugin.getMenuController().openMenu(player, questQMenu, 1); - return 0; - } - - public void openQuests() { - if (this.uuid == null) { - return; - } - Player player = Bukkit.getPlayer(this.uuid); - if (player == null) { - return; - } - - if (plugin.getQuestMode() == QuestMode.NORMAL) { - if (Options.CATEGORIES_ENABLED.getBooleanValue()) { - CategoryQMenu categoryQMenu = new CategoryQMenu(plugin, this); - List questMenus = new ArrayList<>(); - for (Category category : plugin.getQuestManager().getCategories()) { - QuestQMenu questQMenu = new QuestQMenu(plugin, this, category.getId(), categoryQMenu); - List quests = new ArrayList<>(); - for (String questid : category.getRegisteredQuestIds()) { - Quest quest = plugin.getQuestManager().getQuestById(questid); - if (quest != null) { - quests.add(quest); - } - } - questQMenu.populate(quests); - questMenus.add(questQMenu); - } - categoryQMenu.populate(questMenus); - - plugin.getMenuController().openMenu(player, categoryQMenu, 1); - } else { - QuestQMenu questQMenu = new QuestQMenu(plugin, this, "", null); - List quests = new ArrayList<>(); - for (Map.Entry entry : plugin.getQuestManager().getQuests().entrySet()) { - quests.add(entry.getValue()); - } - questQMenu.populate(quests); - questQMenu.setBackButtonEnabled(false); - - plugin.getMenuController().openMenu(player, questQMenu, 1); - } - } else { - DailyQMenu dailyQMenu = new DailyQMenu(plugin, this); - dailyQMenu.populate(); - plugin.getMenuController().openMenu(player, dailyQMenu, 1); - } - } - - public void openStartedQuests() { - if (this.uuid == null) { - return; - } - Player player = Bukkit.getPlayer(this.uuid); - if (player == null) { - return; - } - - StartedQMenu startedQMenu = new StartedQMenu(plugin, this); - List quests = new ArrayList<>(); - for (Map.Entry entry : plugin.getQuestManager().getQuests().entrySet()) { - quests.add(new QuestSortWrapper(plugin, entry.getValue())); - } - startedQMenu.populate(quests); - - plugin.getMenuController().openMenu(player, startedQMenu, 1); - } - - public QuestProgressFile getQuestProgressFile() { - return questProgressFile; - } - - public QPlayerPreferences getPlayerPreferences() { - return playerPreferences; - } - - public QuestController getQuestController() { - return questController; - } - - public void setQuestController(QuestController questController) { - this.questController = questController; - } - - @Override //Used by java GC - public boolean equals(Object o) { - if (!(o instanceof QPlayer)) return false; - QPlayer qPlayer = (QPlayer) o; - return this.uuid == qPlayer.getPlayerUUID(); - } - - @Override //Used by java GC - public int hashCode() { - return uuid.hashCode() * 73; //uuid hash * prime number - } -} diff --git a/src/main/java/com/leonardobishop/quests/player/QPlayerManager.java b/src/main/java/com/leonardobishop/quests/player/QPlayerManager.java deleted file mode 100644 index 182b5666..00000000 --- a/src/main/java/com/leonardobishop/quests/player/QPlayerManager.java +++ /dev/null @@ -1,179 +0,0 @@ -package com.leonardobishop.quests.player; - -import com.leonardobishop.quests.Quests; -import com.leonardobishop.quests.util.QuestsLogger; -import com.leonardobishop.quests.player.questprogressfile.QPlayerPreferences; -import com.leonardobishop.quests.player.questprogressfile.QuestProgressFile; -import com.leonardobishop.quests.quest.controller.NormalQuestController; -import com.leonardobishop.quests.quest.controller.QuestController; -import com.leonardobishop.quests.storage.MySqlStorageProvider; -import com.leonardobishop.quests.storage.StorageProvider; -import com.leonardobishop.quests.storage.YamlStorageProvider; -import org.bukkit.Bukkit; - -import java.util.Collection; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; - -public class QPlayerManager { - - private final Map qPlayers = new ConcurrentHashMap<>(); - private final Quests plugin; - private StorageProvider storageProvider; - private QuestController activeQuestController; - - - public QPlayerManager(Quests plugin) { - this.plugin = plugin; - - String configuredProvider = plugin.getConfig().getString("options.storage.provider", "yaml"); - if (configuredProvider.equalsIgnoreCase("yaml")) { - this.storageProvider = new YamlStorageProvider(plugin); - } else if (configuredProvider.equalsIgnoreCase("mysql")) { - this.storageProvider = new MySqlStorageProvider(plugin, plugin.getConfig().getConfigurationSection("options.storage.database-settings")); - } else { - plugin.getQuestsLogger().warning("No valid storage provider is configured - Quests will use YAML storage as a default"); - this.storageProvider = new YamlStorageProvider(plugin); - } - try { - storageProvider.init(); - } catch (Exception ignored) { - plugin.getQuestsLogger().severe("An error occurred initialising the storage provider."); - } - - this.activeQuestController = new NormalQuestController(plugin); - } - - /** - * Gets the QPlayer from a given UUID. - * - * @param uuid the uuid - * @return {@link QPlayer} if they are loaded - */ - public QPlayer getPlayer(UUID uuid) { - QPlayer qPlayer = qPlayers.get(uuid); - if (qPlayer == null) { - plugin.getQuestsLogger().debug("QPlayer of " + uuid + " is null, but was requested:"); - if (plugin.getQuestsLogger().getServerLoggingLevel() == QuestsLogger.LoggingLevel.DEBUG) { - Thread.dumpStack(); - } - } - return qPlayer; - } - - /** - * Unloads and schedules a save for the player. See {@link QPlayerManager#savePlayer(UUID)} - * - * @param uuid the uuid of the player - */ - public void removePlayer(UUID uuid) { - plugin.getQuestsLogger().debug("Unloading and saving player " + uuid + ". Main thread: " + Bukkit.isPrimaryThread()); - qPlayers.computeIfPresent(uuid, (mapUUID, qPlayer) -> { - savePlayer(uuid); - return null; - }); - } - - /** - * Schedules a save for the player with the {@link QuestProgressFile} associated by the {@link QPlayerManager}. - * The modified status of the progress file will be reset. - * - * @param uuid the uuid of the player - */ - public void savePlayer(UUID uuid) { - QPlayer qPlayer = getPlayer(uuid); - if (qPlayer == null) return; - savePlayer(uuid, qPlayer.getQuestProgressFile()); - } - - /** - * Schedules a save for the player with a specified {@link QuestProgressFile}. The modified status of the - * specified progress file will be reset. - * - * @param uuid the uuid of the player - * @param originalProgressFile the quest progress file to associate with and save - */ - public void savePlayer(UUID uuid, QuestProgressFile originalProgressFile) { - QuestProgressFile clonedProgressFile = new QuestProgressFile(originalProgressFile); - originalProgressFile.resetModified(); - plugin.getServer().getScheduler().runTaskAsynchronously(plugin, () -> save(uuid, clonedProgressFile)); - } - - /** - * Immediately saves the player with the {@link QuestProgressFile} associated by the {@link QPlayerManager}, - * on the same thread. The modified status of the specified progress file is not changed. - * - * @param uuid the uuid of the player - */ - public void savePlayerSync(UUID uuid) { - QPlayer qPlayer = getPlayer(uuid); - if (qPlayer == null) return; - savePlayerSync(uuid, qPlayer.getQuestProgressFile()); - } - - /** - * Immediately saves the player with a specified {@link QuestProgressFile}, on the same thread. The modified status - * of the specified progress file is not changed. - * - * @param uuid the uuid of the player - * @param questProgressFile the quest progress file to associate with and save - */ - public void savePlayerSync(UUID uuid, QuestProgressFile questProgressFile) { - save(uuid, questProgressFile); - } - - private void save(UUID uuid, QuestProgressFile questProgressFile) { - plugin.getQuestsLogger().debug("Saving player " + uuid + ". Main thread: " + Bukkit.isPrimaryThread()); - storageProvider.saveProgressFile(uuid, questProgressFile); - } - - /** - * Unloads the player without saving to disk. - * - * @param uuid the uuid of the player - */ - public void dropPlayer(UUID uuid) { - plugin.getQuestsLogger().debug("Dropping player " + uuid + "."); - qPlayers.remove(uuid); - } - - public Collection getQPlayers() { - return qPlayers.values(); - } - - /** - * Load the player if they exist, otherwise create a new {@link QuestProgressFile}. - * This will have no effect if player is already loaded. Can be invoked asynchronously. - * - * @param uuid the uuid of the player - */ - public void loadPlayer(UUID uuid) { - plugin.getQuestsLogger().debug("Loading player " + uuid + ". Main thread: " + Bukkit.isPrimaryThread()); - qPlayers.computeIfAbsent(uuid, s -> { - QuestProgressFile questProgressFile = storageProvider.loadProgressFile(uuid); - if (questProgressFile == null) return null; - return new QPlayer(plugin, uuid, new QPlayerPreferences(null), questProgressFile, activeQuestController); - }); - } - - /** - * Gets the current storage provider which loads and saves players. - * - * @return {@link StorageProvider} - */ - public StorageProvider getStorageProvider() { - return storageProvider; - } - - public QuestController getActiveQuestController() { - return activeQuestController; - } - - public void setActiveQuestController(QuestController activeQuestController) { - this.activeQuestController = activeQuestController; - for (QPlayer qPlayer : qPlayers.values()) { - qPlayer.setQuestController(activeQuestController); - } - } -} diff --git a/src/main/java/com/leonardobishop/quests/player/questprogressfile/QPlayerPreferences.java b/src/main/java/com/leonardobishop/quests/player/questprogressfile/QPlayerPreferences.java deleted file mode 100644 index 764189f9..00000000 --- a/src/main/java/com/leonardobishop/quests/player/questprogressfile/QPlayerPreferences.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.leonardobishop.quests.player.questprogressfile; - -public class QPlayerPreferences { - - private String trackedQuestId; - - public QPlayerPreferences(String trackedQuestId) { - this.trackedQuestId = trackedQuestId; - } - - public String getTrackedQuestId() { - return trackedQuestId; - } - - public void setTrackedQuestId(String trackedQuestId) { - this.trackedQuestId = trackedQuestId; - } -} diff --git a/src/main/java/com/leonardobishop/quests/player/questprogressfile/QuestProgress.java b/src/main/java/com/leonardobishop/quests/player/questprogressfile/QuestProgress.java deleted file mode 100644 index d7cac084..00000000 --- a/src/main/java/com/leonardobishop/quests/player/questprogressfile/QuestProgress.java +++ /dev/null @@ -1,143 +0,0 @@ -package com.leonardobishop.quests.player.questprogressfile; - -import com.leonardobishop.quests.Quests; - -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -public class QuestProgress { - - private final Quests plugin; - - private final Map taskProgress = new HashMap<>(); - private final String questid; - private final UUID player; - - private boolean started; - private boolean completed; - private boolean completedBefore; - private long completionDate; - private boolean modified; - - public QuestProgress(Quests plugin, String questid, boolean completed, boolean completedBefore, long completionDate, UUID player, boolean started) { - this.plugin = plugin; - this.questid = questid; - this.completed = completed; - this.completedBefore = completedBefore; - this.completionDate = completionDate; - this.player = player; - this.started = started; - } - - public QuestProgress(Quests plugin, String questid, boolean completed, boolean completedBefore, long completionDate, UUID player, boolean started, boolean modified) { - this(plugin, questid, completed, completedBefore, completionDate, player, started); - this.modified = modified; - } - - public QuestProgress(QuestProgress questProgress) { - this.plugin = questProgress.plugin; - for (Map.Entry progressEntry : questProgress.taskProgress.entrySet()) { - taskProgress.put(progressEntry.getKey(), new TaskProgress(progressEntry.getValue())); - } - this.questid = questProgress.questid; - this.player = questProgress.player; - this.started = questProgress.started; - this.completed = questProgress.completed; - this.completedBefore = questProgress.completedBefore; - this.completionDate = questProgress.completionDate; - this.modified = questProgress.modified; - } - - public String getQuestId() { - return questid; - } - - public boolean isCompleted() { - return completed; - } - - public void setCompleted(boolean completed) { - this.completed = completed; - this.modified = true; - } - - public boolean isStarted() { - return started; - } - - public void setStarted(boolean started) { - this.started = started; - this.modified = true; - } - - public long getCompletionDate() { - return completionDate; - } - - public void setCompletionDate(long completionDate) { - this.completionDate = completionDate; - this.modified = true; - } - - public UUID getPlayer() { - return player; - } - - public boolean isCompletedBefore() { - return completedBefore; - } - - public void setCompletedBefore(boolean completedBefore) { - this.completedBefore = completedBefore; - this.modified = true; - } - - public void addTaskProgress(TaskProgress taskProgress) { - this.taskProgress.put(taskProgress.getTaskId(), taskProgress); - } - - public Collection getTaskProgress() { - return taskProgress.values(); - } - - public Map getTaskProgressMap() { - return taskProgress; - } - - public TaskProgress getTaskProgress(String taskId) { - TaskProgress tP = taskProgress.getOrDefault(taskId, null); - if (tP == null) { - repairTaskProgress(taskId); - tP = taskProgress.getOrDefault(taskId, null); - } - return tP; - } - - public void repairTaskProgress(String taskid) { - TaskProgress taskProgress = new TaskProgress(this, taskid, null, player, false, false); - this.addTaskProgress(taskProgress); - } - - public boolean isModified() { - if (modified) return true; - else { - for (TaskProgress progress : this.taskProgress.values()) { - if (progress.isModified()) return true; - } - return false; - } - } - - public void queueForCompletionTest() { - plugin.getQuestCompleter().queueSingular(this); - } - - public void resetModified() { - this.modified = false; - for (TaskProgress progress : this.taskProgress.values()) { - progress.resetModified(); - } - } -} diff --git a/src/main/java/com/leonardobishop/quests/player/questprogressfile/QuestProgressFile.java b/src/main/java/com/leonardobishop/quests/player/questprogressfile/QuestProgressFile.java deleted file mode 100644 index 3f6d9900..00000000 --- a/src/main/java/com/leonardobishop/quests/player/questprogressfile/QuestProgressFile.java +++ /dev/null @@ -1,257 +0,0 @@ -package com.leonardobishop.quests.player.questprogressfile; - -import com.leonardobishop.quests.Quests; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.util.Options; -import org.bukkit.Bukkit; -import org.bukkit.configuration.file.YamlConfiguration; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.TimeUnit; - -/** - * Represents underlying quest progress for a player. - */ -public class QuestProgressFile { - - private final Map questProgress = new HashMap<>(); - private final UUID playerUUID; - private final Quests plugin; - - public QuestProgressFile(UUID playerUUID, Quests plugin) { - this.playerUUID = playerUUID; - this.plugin = plugin; - } - - public QuestProgressFile(QuestProgressFile questProgressFile) { - for (Map.Entry progressEntry : questProgressFile.questProgress.entrySet()) { - questProgress.put(progressEntry.getKey(), new QuestProgress(progressEntry.getValue())); - } - this.playerUUID = questProgressFile.playerUUID; - this.plugin = questProgressFile.plugin; - } - - public void addQuestProgress(QuestProgress questProgress) { - if (Options.VERIFY_QUEST_EXISTS_ON_LOAD.getBooleanValue(true) && plugin.getQuestManager().getQuestById(questProgress.getQuestId()) == null) { - return; - } - this.questProgress.put(questProgress.getQuestId(), questProgress); - } - - /** - * Gets all started quests. - * Note: if quest autostart is enabled then this may produce unexpected results as quests are - * not "started" by the player if autostart is true. Consider {@link QPlayer#hasStartedQuest(Quest)} instead. - * - * @return list of started quests - */ - public List getStartedQuests() { - List startedQuests = new ArrayList<>(); - for (QuestProgress questProgress : questProgress.values()) { - if (questProgress.isStarted()) { - startedQuests.add(plugin.getQuestManager().getQuestById(questProgress.getQuestId())); - } - } - return startedQuests; - } - - /** - * Returns all {@link Quest} a player has encountered - * (not to be confused with a collection of quest progress) - * - * @return {@code List} all quests - */ - public List getAllQuestsFromProgress(QuestsProgressFilter filter) { - List questsProgress = new ArrayList<>(); - for (QuestProgress qProgress : questProgress.values()) { - boolean condition = false; - if (filter == QuestsProgressFilter.STARTED) { - condition = qProgress.isStarted(); - } else if (filter == QuestsProgressFilter.COMPLETED_BEFORE) { - condition = qProgress.isCompletedBefore(); - } else if (filter == QuestsProgressFilter.COMPLETED) { - condition = qProgress.isCompleted(); - } else if (filter == QuestsProgressFilter.ALL) { - condition = true; - } - if (condition) { - Quest quest = plugin.getQuestManager().getQuestById(qProgress.getQuestId()); - if (quest != null) { - questsProgress.add(quest); - } - } - } - return questsProgress; - } - - public enum QuestsProgressFilter { - ALL("all"), - COMPLETED("completed"), - COMPLETED_BEFORE("completedBefore"), - STARTED("started"); - - private String legacy; - - QuestsProgressFilter(String legacy) { - this.legacy = legacy; - } - - public static QuestsProgressFilter fromLegacy(String filter) { - for (QuestsProgressFilter filterEnum : QuestsProgressFilter.values()) { - if (filterEnum.getLegacy().equals(filter)) return filterEnum; - } - return QuestsProgressFilter.ALL; - } - - public String getLegacy() { - return legacy; - } - } - - /** - * Gets all the quest progress that it has ever encountered. - * - * @return {@code Collection} all quest progresses - */ - public Collection getAllQuestProgress() { - return questProgress.values(); - } - - /** - * Checks whether or not the player has {@link QuestProgress} for a specified quest - * - * @param quest the quest to check for - * @return true if they have quest progress - */ - public boolean hasQuestProgress(Quest quest) { - return questProgress.containsKey(quest.getId()); - } - - /** - * Gets the remaining cooldown before being able to start a specific quest. - * - * @param quest the quest to test for - * @return 0 if no cooldown remaining or the cooldown is disabled, otherwise the cooldown in milliseconds - */ - public long getCooldownFor(Quest quest) { - QuestProgress questProgress = getQuestProgress(quest); - if (quest.isCooldownEnabled() && questProgress.isCompleted()) { - if (questProgress.getCompletionDate() > 0) { - long date = questProgress.getCompletionDate(); - return (date + TimeUnit.MILLISECONDS.convert(quest.getCooldown(), TimeUnit.MINUTES)) - System.currentTimeMillis(); - } - } - return 0; - } - - /** - * Tests whether or not the player meets the requirements to start a specific quest. - * - * @param quest the quest to test for - * @return true if they can start the quest - */ - //TODO possibly move this - public boolean hasMetRequirements(Quest quest) { - for (String id : quest.getRequirements()) { - Quest q = plugin.getQuestManager().getQuestById(id); - if (q == null) { - continue; - } - if (hasQuestProgress(q) && !getQuestProgress(q).isCompletedBefore()) { - return false; - } else if (!hasQuestProgress(q)) { - return false; - } - } - return true; - } - - /** - * Get the {@link UUID} of the player this QuestProgressFile represents - * - * @return UUID - */ - public UUID getPlayerUUID() { - return playerUUID; - } - - /** - * Get the {@link QuestProgress} for a specified {@link Quest}, and generates a new one if it does not exist - * - * @param quest the quest to get progress for - * @return {@link QuestProgress} or null if the quest does not exist - */ - public QuestProgress getQuestProgress(Quest quest) { - if (questProgress.containsKey(quest.getId())) { - return questProgress.get(quest.getId()); - } - generateBlankQuestProgress(quest); - return getQuestProgress(quest); - } - - /** - * Generate a new blank {@link QuestProgress} for a specified {@code quest}. - * Has no effect if there is already an existing {@link QuestProgress} for {@code quest}. - * - * @param quest the quest to generate progress for - */ - public void generateBlankQuestProgress(Quest quest) { - QuestProgress questProgress = new QuestProgress(plugin, quest.getId(), false, false, 0, playerUUID, false, false); - for (Task task : quest.getTasks()) { - TaskProgress taskProgress = new TaskProgress(questProgress, task.getId(), null, playerUUID, false, false); - questProgress.addTaskProgress(taskProgress); - } - - addQuestProgress(questProgress); - } - - public void clear() { - questProgress.clear(); - } - - /** - * Removes any references to quests or tasks which are no longer defined in the config. - */ - @Deprecated - public void clean() { - plugin.getQuestsLogger().debug("Cleaning file " + playerUUID + "."); - if (!plugin.getTaskTypeManager().areRegistrationsAccepted()) { - ArrayList invalidQuests = new ArrayList<>(); - for (String questId : this.questProgress.keySet()) { - Quest q; - if ((q = plugin.getQuestManager().getQuestById(questId)) == null) { - invalidQuests.add(questId); - } else { - ArrayList invalidTasks = new ArrayList<>(); - for (String taskId : this.questProgress.get(questId).getTaskProgressMap().keySet()) { - if (q.getTaskById(taskId) == null) { - invalidTasks.add(taskId); - } - } - for (String taskId : invalidTasks) { - this.questProgress.get(questId).getTaskProgressMap().remove(taskId); - } - } - } - for (String questId : invalidQuests) { - this.questProgress.remove(questId); - } - } - } - - public void resetModified() { - for (QuestProgress questProgress : questProgress.values()) { - questProgress.resetModified(); - } - } - -} diff --git a/src/main/java/com/leonardobishop/quests/player/questprogressfile/TaskProgress.java b/src/main/java/com/leonardobishop/quests/player/questprogressfile/TaskProgress.java deleted file mode 100644 index e0943ff3..00000000 --- a/src/main/java/com/leonardobishop/quests/player/questprogressfile/TaskProgress.java +++ /dev/null @@ -1,73 +0,0 @@ -package com.leonardobishop.quests.player.questprogressfile; - -import java.util.UUID; - -public class TaskProgress { - - private final String taskid; - private final UUID player; - - private QuestProgress linkedQuestProgress; - private boolean modified; - private Object progress; - private boolean completed; - - public TaskProgress(QuestProgress linkedQuestProgress, String taskid, Object progress, UUID player, boolean completed) { - this.linkedQuestProgress = linkedQuestProgress; - this.taskid = taskid; - this.progress = progress; - this.player = player; - this.completed = completed; - } - - public TaskProgress(QuestProgress linkedQuestProgress, String taskid, Object progress, UUID player, boolean completed, boolean modified) { - this(linkedQuestProgress, taskid, progress, player, completed); - this.modified = modified; - } - - public TaskProgress(TaskProgress taskProgress) { - this.taskid = taskProgress.taskid; - this.player = taskProgress.player; - this.modified = taskProgress.modified; - this.progress = taskProgress.progress; - this.completed = taskProgress.completed; - } - - public String getTaskId() { - return taskid; - } - - public Object getProgress() { - return progress; - } - - public void setProgress(Object progress) { - this.progress = progress; - this.modified = true; - } - - public UUID getPlayer() { - return player; - } - - public boolean isCompleted() { - return completed; - } - - public void setCompleted(boolean complete) { - this.completed = complete; - this.modified = true; - - if (complete) { - linkedQuestProgress.queueForCompletionTest(); - } - } - - public boolean isModified() { - return modified; - } - - public void resetModified() { - this.modified = false; - } -} diff --git a/src/main/java/com/leonardobishop/quests/quest/Category.java b/src/main/java/com/leonardobishop/quests/quest/Category.java deleted file mode 100644 index d09143dc..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/Category.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.leonardobishop.quests.quest; - -import org.bukkit.ChatColor; -import org.bukkit.inventory.ItemStack; - -import java.util.ArrayList; -import java.util.List; - -public class Category { - - private final String id; - private final ItemStack displayItem; - private final boolean permissionRequired; - private final List registeredQuestIds = new ArrayList<>(); - - public Category(String id, ItemStack displayItem, boolean permissionRequired) { - this.id = id; - this.displayItem = displayItem; - this.permissionRequired = permissionRequired; - } - - public String getId() { - return id; - } - - public boolean isPermissionRequired() { - return permissionRequired; - } - - public ItemStack getDisplayItem() { - return displayItem; - } - - public void registerQuestId(String questid) { - registeredQuestIds.add(questid); - } - - public List getRegisteredQuestIds() { - return registeredQuestIds; - } - - - public String getDisplayNameStripped() { - return ChatColor.stripColor(this.displayItem.getItemMeta().getDisplayName()); - } -} diff --git a/src/main/java/com/leonardobishop/quests/quest/Quest.java b/src/main/java/com/leonardobishop/quests/quest/Quest.java deleted file mode 100644 index c286a45a..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/Quest.java +++ /dev/null @@ -1,133 +0,0 @@ -package com.leonardobishop.quests.quest; - -import com.leonardobishop.quests.menu.QItemStack; -import org.bukkit.ChatColor; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class Quest implements Comparable { - - private Map tasks = new HashMap<>(); - private final String id; - private final QItemStack displayItem; - private final List rewards; - private final List requirements; - private final List rewardString; - private final List startString; - private final boolean repeatable; - private final boolean cooldownEnabled; - private final int cooldown; - private final int sortOrder; - private final boolean permissionRequired; - private final Map placeholders; - private String categoryid; - - - public Quest(String id, QItemStack displayItem, List rewards, List requirements, boolean repeatable, boolean cooldownEnabled, int cooldown, boolean permissionRequired, List rewardString, List startString, Map placeholders, String categoryid, int sortOrder) { - this(id, displayItem, rewards, requirements, repeatable, cooldownEnabled, cooldown, permissionRequired, rewardString, startString, placeholders, sortOrder); - this.categoryid = categoryid; - } - - public Quest(String id, QItemStack displayItem, List rewards, List requirements, boolean repeatable, boolean cooldownEnabled, int cooldown, boolean permissionRequired, List rewardString, List startString, Map placeholders, int sortOrder) { - this.id = id; - this.displayItem = displayItem; - this.rewards = rewards; - this.requirements = requirements; - this.repeatable = repeatable; - this.cooldownEnabled = cooldownEnabled; - this.cooldown = cooldown; - this.permissionRequired = permissionRequired; - this.rewardString = rewardString; - this.startString = startString; - this.placeholders = placeholders; - this.sortOrder = sortOrder; - } - - public void registerTask(Task task) { - tasks.put(task.getId(), task); - } - - public Collection getTasks() { - return tasks.values(); - } - - public Task getTaskById(String id) { - return tasks.get(id); - } - - public List getTasksOfType(String type) { - List tasks = new ArrayList<>(); - for (Task task : getTasks()) { - if (task.getType().equals(type)) { - tasks.add(task); - } - } - return tasks; - } - - - public boolean isPermissionRequired() { - return permissionRequired; - } - - public List getRewardString() { - return rewardString; - } - - public List getStartString() { - return startString; - } - - public String getId() { - return id; - } - - public QItemStack getDisplayItem() { - return displayItem; - } - - public List getRewards() { - return rewards; - } - - public List getRequirements() { - return requirements; - } - - public boolean isRepeatable() { - return repeatable; - } - - public boolean isCooldownEnabled() { - return cooldownEnabled; - } - - public int getCooldown() { - return cooldown; - } - - public String getCategoryId() { - return categoryid; - } - - public String getDisplayNameStripped() { - return ChatColor.stripColor(this.displayItem.getName()); - } - - public Map getPlaceholders() { - return placeholders; - } - - public int getSortOrder() { - return sortOrder; - } - - @Override - public int compareTo(Quest quest) { - return (sortOrder - quest.sortOrder); - } -} diff --git a/src/main/java/com/leonardobishop/quests/quest/QuestManager.java b/src/main/java/com/leonardobishop/quests/quest/QuestManager.java deleted file mode 100644 index 2aaea571..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/QuestManager.java +++ /dev/null @@ -1,49 +0,0 @@ -package com.leonardobishop.quests.quest; - -import com.leonardobishop.quests.Quests; - -import java.util.ArrayList; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; - -public class QuestManager { - - private final Quests plugin; - - public QuestManager(Quests plugin) { - this.plugin = plugin; - } - - private Map quests = new LinkedHashMap<>(); - private List categories = new ArrayList<>(); - - public void registerQuest(Quest quest) { - quests.put(quest.getId(), quest); - } - - public Quest getQuestById(String id) { - return quests.get(id); - } - - public Map getQuests() { - return quests; - } - - public void registerCategory(Category category) { categories.add(category); } - - public List getCategories() { - return categories; - } - - public Category getCategoryById(String id) { - for (Category category : categories) { - if (category.getId().equals(id)) return category; - } - return null; - } - - public Quests getPlugin() { - return this.plugin; - } -} diff --git a/src/main/java/com/leonardobishop/quests/quest/Task.java b/src/main/java/com/leonardobishop/quests/quest/Task.java deleted file mode 100644 index edac070d..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/Task.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.leonardobishop.quests.quest; - -import java.util.HashMap; -import java.util.Map; - -public class Task { - - private final Map configValues = new HashMap<>(); - private final String id; - private final String type; - - public Task(String id, String type) { - this.id = id; - this.type = type; - } - - public String getId() { - return id; - } - - public String getType() { - return type; - } - - public Object getConfigValue(String key) { - return configValues.getOrDefault(key, null); //??? this will return null without the need of `OrDefault(key, null)` - } - - public Object getConfigValue(String key, Object def) { - return configValues.getOrDefault(key, def); - } - - public Map getConfigValues() { - return configValues; - } - - public void addConfigValue(String key, Object value) { - configValues.put(key, value); - } - -} diff --git a/src/main/java/com/leonardobishop/quests/quest/controller/DailyQuestController.java b/src/main/java/com/leonardobishop/quests/quest/controller/DailyQuestController.java deleted file mode 100644 index d2ffd192..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/controller/DailyQuestController.java +++ /dev/null @@ -1,186 +0,0 @@ -package com.leonardobishop.quests.quest.controller; - -import com.leonardobishop.quests.Quests; -import com.leonardobishop.quests.api.enums.QuestStartResult; -import com.leonardobishop.quests.api.events.PlayerFinishQuestEvent; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.util.Messages; -import com.leonardobishop.quests.util.Options; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; -import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.scheduler.BukkitTask; - -import java.util.ArrayList; -import java.util.List; -import java.util.Random; -import java.util.stream.Collectors; - -//TODO finish this -public class DailyQuestController implements QuestController { - - private int refreshTaskId = -1; - private long refreshTime; - private long startTime; - private Quests plugin; - private Random random; - private List quests; - - public DailyQuestController(Quests plugin) { - this.plugin = plugin; - refreshDailyQuests(); - scheduleNewTask(); - } - - public void cancel() { - Bukkit.getScheduler().cancelTask(refreshTaskId); - } - - public List getQuests() { - return quests; - } - - private void scheduleNewTask() { - long diff = refreshTime - System.currentTimeMillis(); - BukkitTask refreshTask; - if (diff <= 10000) { //10 sec - refreshTask = new DailyQuestRefreshTask(true).runTaskTimer(plugin, 1L, 1L); - plugin.getQuestsLogger().debug("DailyQuestRefreshTask set repeating (diff=" + diff + ")"); - } else { - long sleepTime = diff >> 6; - plugin.getQuestsLogger().debug("DailyQuestRefreshTask slept for " + sleepTime + " ticks (diff=" + diff + ")"); - refreshTask = new DailyQuestRefreshTask(false).runTaskLater(plugin, sleepTime); - } - refreshTaskId = refreshTask.getTaskId(); - } - - private void refreshDailyQuests() { -// refreshTime = ((System.currentTimeMillis() / (86400000)) + 1) * 86400000; - refreshTime = ((System.currentTimeMillis() / (300000)) + 1) * 300000; - startTime = (System.currentTimeMillis() / (300000)) * 300000; - random = new Random(refreshTime); - quests = new ArrayList<>(); - - List questIds = new ArrayList<>(plugin.getQuestManager().getQuests().keySet()); - for (int i = 0; i < 5; i++) { - int randInt = random.nextInt(questIds.size()); - quests.add(questIds.get(randInt)); - questIds = questIds.stream().filter(s -> !quests.contains(s)).collect(Collectors.toList()); - } - } - - @Override - public QuestStartResult startQuestForPlayer(QPlayer qPlayer, Quest quest) { - if (quests.contains(quest.getId())) { - return QuestStartResult.QUEST_ALREADY_STARTED; - } else { - return QuestStartResult.QUEST_LIMIT_REACHED; - } - } - - @Override - public QuestStartResult canPlayerStartQuest(QPlayer qPlayer, Quest quest) { - if (!quests.contains(quest.getId())) return QuestStartResult.OTHER; - long completionDate = qPlayer.getQuestProgressFile().getQuestProgress(quest).getCompletionDate(); - if (Options.QUEST_AUTOSTART.getBooleanValue()) { - if (completionDate > startTime && completionDate <= refreshTime) { - return QuestStartResult.QUEST_ALREADY_COMPLETED; - } - } else { - if (qPlayer.getQuestProgressFile().hasQuestProgress(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - if (questProgress.isStarted() && completionDate > startTime && completionDate <= refreshTime) { - return QuestStartResult.QUEST_ALREADY_STARTED; - } - } - } - return QuestStartResult.QUEST_SUCCESS; - } - - @Override - public boolean completeQuestForPlayer(QPlayer qPlayer, Quest quest) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - questProgress.setStarted(false); - for (TaskProgress taskProgress : questProgress.getTaskProgress()) { - taskProgress.setCompleted(false); - taskProgress.setProgress(null); - } - questProgress.setCompleted(true); - questProgress.setCompletedBefore(true); - questProgress.setCompletionDate(System.currentTimeMillis()); - - boolean trackedReset = quest.getId().equals(qPlayer.getPlayerPreferences().getTrackedQuestId()); - if (trackedReset) { - qPlayer.trackQuest(null); - } - - Player player = Bukkit.getPlayer(qPlayer.getPlayerUUID()); - if (player != null) { - String questFinishMessage = Messages.QUEST_COMPLETE.getMessage().replace("{quest}", quest.getDisplayNameStripped()); - // PlayerFinishQuestEvent -- start - PlayerFinishQuestEvent questFinishEvent = new PlayerFinishQuestEvent(player, qPlayer, questProgress, questFinishMessage); - Bukkit.getPluginManager().callEvent(questFinishEvent); - // PlayerFinishQuestEvent -- end - Bukkit.getServer().getScheduler().runTask(plugin, () -> { - for (String s : quest.getRewards()) { - Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), s.replace("{player}", player.getName())); //TODO PlaceholderAPI support - } - }); - if (questFinishEvent.getQuestFinishMessage() != null) - player.sendMessage(questFinishEvent.getQuestFinishMessage()); - if (Options.TITLES_ENABLED.getBooleanValue()) { - plugin.getTitleHandle().sendTitle(player, Messages.TITLE_QUEST_COMPLETE_TITLE.getMessage().replace("{quest}", quest - .getDisplayNameStripped()), Messages.TITLE_QUEST_COMPLETE_SUBTITLE.getMessage().replace("{quest}", quest - .getDisplayNameStripped())); - } - for (String s : quest.getRewardString()) { - player.sendMessage(ChatColor.translateAlternateColorCodes('&', s)); - } - } - if (Options.QUEST_AUTOTRACK.getBooleanValue() && trackedReset) { - for (String s : quests) { - Quest nextQuest = plugin.getQuestManager().getQuestById(s); - if (nextQuest != null && canPlayerStartQuest(qPlayer, nextQuest) == QuestStartResult.QUEST_SUCCESS) { - qPlayer.trackQuest(nextQuest); - break; - } - } - } - return true; - } - - @Override - public boolean hasPlayerStartedQuest(QPlayer qPlayer, Quest quest) { - return canPlayerStartQuest(qPlayer, quest) == QuestStartResult.QUEST_SUCCESS; - } - - @Override - public boolean cancelQuestForPlayer(QPlayer qPlayer, Quest quest) { - return false; - } - - public class DailyQuestRefreshTask extends BukkitRunnable { - - private final boolean repeating; - - public DailyQuestRefreshTask(boolean repeating) { - this.repeating = repeating; - } - - @Override - public void run() { - if (System.currentTimeMillis() >= refreshTime) { - this.cancel(); - refreshDailyQuests(); - } else { - if (repeating) return; - this.cancel(); - } - scheduleNewTask(); - } - } -} diff --git a/src/main/java/com/leonardobishop/quests/quest/controller/NormalQuestController.java b/src/main/java/com/leonardobishop/quests/quest/controller/NormalQuestController.java deleted file mode 100644 index 055bbf97..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/controller/NormalQuestController.java +++ /dev/null @@ -1,239 +0,0 @@ -package com.leonardobishop.quests.quest.controller; - -import com.leonardobishop.quests.Quests; -import com.leonardobishop.quests.api.enums.QuestStartResult; -import com.leonardobishop.quests.api.events.PlayerCancelQuestEvent; -import com.leonardobishop.quests.api.events.PlayerFinishQuestEvent; -import com.leonardobishop.quests.api.events.PlayerStartQuestEvent; -import com.leonardobishop.quests.api.events.PreStartQuestEvent; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.util.Messages; -import com.leonardobishop.quests.util.Options; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; - -import java.util.concurrent.TimeUnit; - -public class NormalQuestController implements QuestController { - - private final Quests plugin; - - public NormalQuestController(Quests plugin) { - this.plugin = plugin; - } - - @Override - public QuestStartResult startQuestForPlayer(QPlayer qPlayer, Quest quest) { - Player player = Bukkit.getPlayer(qPlayer.getPlayerUUID()); - QuestStartResult code = canPlayerStartQuest(qPlayer, quest); - if (player != null) { - String questResultMessage = null; - switch (code) { - case QUEST_SUCCESS: - // This one is hacky - break; - case QUEST_LIMIT_REACHED: - questResultMessage = Messages.QUEST_START_LIMIT.getMessage().replace("{limit}", String.valueOf(Options.QUESTS_START_LIMIT.getIntValue())); - break; - case QUEST_ALREADY_COMPLETED: - questResultMessage = Messages.QUEST_START_DISABLED.getMessage(); - break; - case QUEST_COOLDOWN: - long cooldown = qPlayer.getQuestProgressFile().getCooldownFor(quest); - questResultMessage = Messages.QUEST_START_COOLDOWN.getMessage().replace("{time}", String.valueOf(plugin.convertToFormat(TimeUnit.SECONDS.convert - (cooldown, TimeUnit.MILLISECONDS)))); - break; - case QUEST_LOCKED: - questResultMessage = Messages.QUEST_START_LOCKED.getMessage(); - break; - case QUEST_ALREADY_STARTED: - questResultMessage = Messages.QUEST_START_STARTED.getMessage(); - break; - case QUEST_NO_PERMISSION: - questResultMessage = Messages.QUEST_START_PERMISSION.getMessage(); - break; - case NO_PERMISSION_FOR_CATEGORY: - questResultMessage = Messages.QUEST_CATEGORY_QUEST_PERMISSION.getMessage(); - break; - } - // PreStartQuestEvent -- start - PreStartQuestEvent preStartQuestEvent = new PreStartQuestEvent(player, qPlayer, questResultMessage, code); - Bukkit.getPluginManager().callEvent(preStartQuestEvent); - // PreStartQuestEvent -- end - if (preStartQuestEvent.getQuestResultMessage() != null && code != QuestStartResult.QUEST_SUCCESS) - player.sendMessage(preStartQuestEvent.getQuestResultMessage()); - } - if (code == QuestStartResult.QUEST_SUCCESS) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - questProgress.setStarted(true); - for (TaskProgress taskProgress : questProgress.getTaskProgress()) { - taskProgress.setCompleted(false); - taskProgress.setProgress(null); - } - if (Options.ALLOW_QUEST_TRACK.getBooleanValue() && Options.QUEST_AUTOTRACK.getBooleanValue()) { - qPlayer.trackQuest(quest); - } - questProgress.setCompleted(false); - if (player != null) { - String questStartMessage = Messages.QUEST_START.getMessage().replace("{quest}", quest.getDisplayNameStripped()); - // PlayerStartQuestEvent -- start - PlayerStartQuestEvent questStartEvent = new PlayerStartQuestEvent(player, qPlayer, questProgress, questStartMessage); - Bukkit.getPluginManager().callEvent(questStartEvent); - // PlayerStartQuestEvent -- end - if (questStartEvent.getQuestStartMessage() != null) - player.sendMessage(questStartEvent.getQuestStartMessage()); //Don't send a message if the event message is null - if (Options.TITLES_ENABLED.getBooleanValue()) { - plugin.getTitleHandle().sendTitle(player, Messages.TITLE_QUEST_START_TITLE.getMessage().replace("{quest}", quest - .getDisplayNameStripped()), Messages.TITLE_QUEST_START_SUBTITLE.getMessage().replace("{quest}", quest - .getDisplayNameStripped())); - } - for (String s : quest.getStartString()) { - player.sendMessage(ChatColor.translateAlternateColorCodes('&', s)); - } - } - for (Task task : quest.getTasks()) { - try { - plugin.getTaskTypeManager().getTaskType(task.getType()).onStart(quest, task, qPlayer.getPlayerUUID()); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - return code; - } - - @Override - public QuestStartResult canPlayerStartQuest(QPlayer qPlayer, Quest quest) { - Player p = Bukkit.getPlayer(qPlayer.getPlayerUUID()); - if (qPlayer.getQuestProgressFile().getStartedQuests().size() >= Options.QUESTS_START_LIMIT.getIntValue() && !Options.QUEST_AUTOSTART.getBooleanValue()) { - return QuestStartResult.QUEST_LIMIT_REACHED; - } - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - if (!quest.isRepeatable() && questProgress.isCompletedBefore()) { - //if (playerUUID != null) { - // ??? - //} - return QuestStartResult.QUEST_ALREADY_COMPLETED; - } - long cooldown = qPlayer.getQuestProgressFile().getCooldownFor(quest); - if (cooldown > 0) { - return QuestStartResult.QUEST_COOLDOWN; - } - if (!qPlayer.getQuestProgressFile().hasMetRequirements(quest)) { - return QuestStartResult.QUEST_LOCKED; - } - if (questProgress.isStarted()) { - return QuestStartResult.QUEST_ALREADY_STARTED; - } - if (quest.isPermissionRequired()) { - if (p != null) { - if (!p.hasPermission("quests.quest." + quest.getId())) { - return QuestStartResult.QUEST_NO_PERMISSION; - } - } else { - return QuestStartResult.QUEST_NO_PERMISSION; - } - } - if (quest.getCategoryId() != null && plugin.getQuestManager().getCategoryById(quest.getCategoryId()) != null && plugin.getQuestManager() - .getCategoryById(quest.getCategoryId()).isPermissionRequired()) { - if (p != null) { - if (!p.hasPermission("quests.category." + quest.getCategoryId())) { - return QuestStartResult.NO_PERMISSION_FOR_CATEGORY; - } - } else { - return QuestStartResult.NO_PERMISSION_FOR_CATEGORY; - } - } - return QuestStartResult.QUEST_SUCCESS; - } - - @Override - public boolean completeQuestForPlayer(QPlayer qPlayer, Quest quest) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - questProgress.setStarted(false); - for (TaskProgress taskProgress : questProgress.getTaskProgress()) { - taskProgress.setCompleted(false); - taskProgress.setProgress(null); - } - questProgress.setCompleted(true); - questProgress.setCompletedBefore(true); - questProgress.setCompletionDate(System.currentTimeMillis()); - if (Options.ALLOW_QUEST_TRACK.getBooleanValue() && Options.QUEST_AUTOTRACK.getBooleanValue() && !(quest.isRepeatable() && !quest.isCooldownEnabled())) { - qPlayer.trackQuest(null); - } - Player player = Bukkit.getPlayer(qPlayer.getPlayerUUID()); - if (player != null) { - String questFinishMessage = Messages.QUEST_COMPLETE.getMessage().replace("{quest}", quest.getDisplayNameStripped()); - // PlayerFinishQuestEvent -- start - PlayerFinishQuestEvent questFinishEvent = new PlayerFinishQuestEvent(player, qPlayer, questProgress, questFinishMessage); - Bukkit.getPluginManager().callEvent(questFinishEvent); - // PlayerFinishQuestEvent -- end - Bukkit.getServer().getScheduler().runTask(plugin, () -> { - for (String s : quest.getRewards()) { - Bukkit.getServer().dispatchCommand(Bukkit.getConsoleSender(), s.replace("{player}", player.getName())); //TODO PlaceholderAPI support - } - }); - if (questFinishEvent.getQuestFinishMessage() != null) - player.sendMessage(questFinishEvent.getQuestFinishMessage()); - if (Options.TITLES_ENABLED.getBooleanValue()) { - plugin.getTitleHandle().sendTitle(player, Messages.TITLE_QUEST_COMPLETE_TITLE.getMessage().replace("{quest}", quest - .getDisplayNameStripped()), Messages.TITLE_QUEST_COMPLETE_SUBTITLE.getMessage().replace("{quest}", quest - .getDisplayNameStripped())); - } - for (String s : quest.getRewardString()) { - player.sendMessage(ChatColor.translateAlternateColorCodes('&', s)); - } - } - if ((Options.ALLOW_QUEST_TRACK.getBooleanValue() && Options.QUEST_AUTOTRACK.getBooleanValue() && !(quest.isRepeatable() && !quest.isCooldownEnabled())) - || (!Options.ALLOW_QUEST_TRACK.getBooleanValue() && Options.QUEST_AUTOTRACK.getBooleanValue())) { - Quest nextQuest; - if (qPlayer.getQuestProgressFile().getStartedQuests().size() > 0) { - nextQuest = qPlayer.getQuestProgressFile().getStartedQuests().get(0); - qPlayer.trackQuest(nextQuest); - } - } - return true; - } - - @Override - public boolean hasPlayerStartedQuest(QPlayer qPlayer, Quest quest) { - if (Options.QUEST_AUTOSTART.getBooleanValue()) { - QuestStartResult response = canPlayerStartQuest(qPlayer, quest); - return response == QuestStartResult.QUEST_SUCCESS || response == QuestStartResult.QUEST_ALREADY_STARTED; - } else { - return qPlayer.getQuestProgressFile().hasQuestProgress(quest) && qPlayer.getQuestProgressFile().getQuestProgress(quest).isStarted(); - } - } - - @Override - public boolean cancelQuestForPlayer(QPlayer qPlayer, Quest quest) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - Player player = Bukkit.getPlayer(qPlayer.getPlayerUUID()); - if (!questProgress.isStarted()) { - if (player != null) { - player.sendMessage(Messages.QUEST_CANCEL_NOTSTARTED.getMessage()); - } - return false; - } - questProgress.setStarted(false); - for (TaskProgress taskProgress : questProgress.getTaskProgress()) { - taskProgress.setProgress(null); - } - if (player != null) { - String questCancelMessage = Messages.QUEST_CANCEL.getMessage().replace("{quest}", quest.getDisplayNameStripped()); - // PlayerCancelQuestEvent -- start - PlayerCancelQuestEvent questCancelEvent = new PlayerCancelQuestEvent(player, qPlayer, questProgress, questCancelMessage); - Bukkit.getPluginManager().callEvent(questCancelEvent); - // PlayerCancelQuestEvent -- end - if (questCancelEvent.getQuestCancelMessage() != null) - player.sendMessage(questCancelEvent.getQuestCancelMessage()); - } - return true; - } - -} diff --git a/src/main/java/com/leonardobishop/quests/quest/controller/QuestController.java b/src/main/java/com/leonardobishop/quests/quest/controller/QuestController.java deleted file mode 100644 index b4b76baa..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/controller/QuestController.java +++ /dev/null @@ -1,15 +0,0 @@ -package com.leonardobishop.quests.quest.controller; - -import com.leonardobishop.quests.api.enums.QuestStartResult; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.quest.Quest; - -public interface QuestController { - - QuestStartResult startQuestForPlayer(QPlayer qPlayer, Quest quest); - QuestStartResult canPlayerStartQuest(QPlayer qPlayer, Quest quest); - boolean completeQuestForPlayer(QPlayer qPlayer, Quest quest); - boolean hasPlayerStartedQuest(QPlayer qPlayer, Quest quest); - boolean cancelQuestForPlayer(QPlayer qPlayer, Quest quest); - -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/ConfigValue.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/ConfigValue.java deleted file mode 100644 index 764e771c..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/ConfigValue.java +++ /dev/null @@ -1,35 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype; - -/** - * This is for the quest creator and is purely cosmetic. - */ -public final class ConfigValue { - - private final String key; - private final boolean required; - private final String description; - private final String[] requirementExceptions; - - public ConfigValue(String key, boolean required, String description, String... requirementExceptions) { - this.key = key; - this.required = required; - this.description = description; - this.requirementExceptions = requirementExceptions; - } - - public String getKey() { - return key; - } - - public boolean isRequired() { - return required; - } - - public String getDescription() { - return description; - } - - public String[] getRequirementExceptions() { - return requirementExceptions; - } -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/TaskType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/TaskType.java deleted file mode 100644 index fb7b8b61..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/TaskType.java +++ /dev/null @@ -1,116 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype; - -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import org.bukkit.event.Listener; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.UUID; - -/** - * A task type which can be used within Quests. A {@link Quest} - * will be registered to this if it contains at least 1 task - * which is of this type. This is so you do not have to - * iterate through every single quest. - */ -public abstract class TaskType implements Listener { - - private final List quests = new ArrayList<>(); - private final String type; - private String author; - private String description; - - /** - * @param type the name of the task type, should not contain spaces - * @param author the name of the person (or people) who wrote it - * @param description a short, simple description of the task type - */ - public TaskType(String type, String author, String description) { - this.type = type; - this.author = author; - this.description = description; - } - - /** - * @param type the name of the task type, should not contain spaces - */ - public TaskType(String type) { - this.type = type; - } - - /** - * Registers a {@link Quest} to this task type. This is usually done when - * all the quests are initially loaded. - * - * @param quest the {@link Quest} to register. - */ - public final void registerQuest(Quest quest) { - if (!quests.contains(quest)) { - quests.add(quest); - } - } - - /** - * Clears the list which contains the registered quests. - */ - public final void unregisterAll() { - quests.clear(); - } - - /** - * @return {@link List} of type {@link Quest} of all registered quests. - */ - public final List getRegisteredQuests() { - return quests; - } - - public final String getType() { - return type; - } - - public String getAuthor() { - return author; - } - - public String getDescription() { - return description; - } - - //TODO rework this - @Deprecated - public List getCreatorConfigValues() { - // not implemented here - return Collections.emptyList(); - } - - /** - * Called when Quests has finished registering all quests to the task type - * May be called several times if an operator uses /quests admin reload - */ - public void onReady() { - // not implemented here - } - - /** - * Called when a player starts a quest containing a task of this type - */ - public void onStart(Quest quest, Task task, UUID playerUUID) { - // not implemented here - } - - public void onDisable() { - // not implemented here - } - - /** - * Called when Quests reloads the configuration - used to detect errors in the configuration of your task type - */ - public List detectProblemsInConfig(String root, HashMap config) { - // not implemented here - return Collections.emptyList(); - } -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/TaskTypeManager.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/TaskTypeManager.java deleted file mode 100644 index 0b1fced9..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/TaskTypeManager.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype; - -import com.leonardobishop.quests.Quests; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import org.bukkit.Bukkit; - -import java.util.ArrayList; - -public class TaskTypeManager { - - private final Quests plugin; - private boolean allowRegistrations; - - public TaskTypeManager(Quests plugin) { - this.plugin = plugin; - allowRegistrations = true; - } - - public void closeRegistrations() { - allowRegistrations = false; - } - - public boolean areRegistrationsAccepted() { - return allowRegistrations; - } - - private ArrayList taskTypes = new ArrayList<>(); - - public ArrayList getTaskTypes() { - return taskTypes; - } - - public void resetTaskTypes() { - for (TaskType taskType : taskTypes) { - taskType.getRegisteredQuests().clear(); - } - } - - public void registerTaskType(TaskType taskType) { - if (!allowRegistrations) { - throw new IllegalStateException("No longer accepting new task types (must be done before quests are loaded)"); - } - Bukkit.getPluginManager().registerEvents(taskType, plugin); - plugin.getQuestsLogger().info("Task type " + taskType.getType() + " has been registered."); - taskTypes.add(taskType); - } - - public void registerQuestTasksWithTaskTypes(Quest quest) { - if (allowRegistrations) { - throw new IllegalStateException("Still accepting new task types (type registrations must be closed before registering quests)"); - } - for (Task task : quest.getTasks()) { - TaskType t; - if ((t = getTaskType(task.getType())) != null) { - t.registerQuest(quest); - } - } - } - - public TaskType getTaskType(String string) { - for (TaskType taskType : taskTypes) { - if (taskType.getType().equalsIgnoreCase(string)) { - return taskType; - } - } - return null; - } -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/TaskUtils.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/TaskUtils.java deleted file mode 100644 index 405db7ff..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/TaskUtils.java +++ /dev/null @@ -1,89 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype; - -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.quest.Task; -import org.bukkit.entity.Player; - -import java.util.List; - -public class TaskUtils { - - public static String TASK_ATTRIBUTION_STRING = ""; - - public static boolean validateWorld(Player player, Task task) { - return validateWorld(player.getLocation().getWorld().getName(), task.getConfigValue("worlds")); - } - - public static boolean validateWorld(String worldName, Task task) { - return validateWorld(worldName, task.getConfigValue("worlds")); - } - - public static boolean validateWorld(String worldName, Object configurationData) { - if (configurationData == null) { - return true; - } - - if (configurationData instanceof List) { - List allowedWorlds = (List) configurationData; - if (!allowedWorlds.isEmpty() && allowedWorlds.get(0) instanceof String) { - List allowedWorldNames = (List) allowedWorlds; - return allowedWorldNames.contains(worldName); - } - return true; - } - - if (configurationData instanceof String) { - String allowedWorld = (String) configurationData; - return worldName.equals(allowedWorld); - } - - return true; - } - - public static void configValidateInt(String path, Object object, List problems, boolean allowNull, boolean greaterThanZero, String... args) { - if (object == null) { - if (!allowNull) { - problems.add(new QuestsConfigLoader.ConfigProblem(QuestsConfigLoader.ConfigProblemType.ERROR, - String.format("Expected an integer for '%s', but got null instead", (Object[]) args), path)); - } - return; - } - - try { - Integer i = (Integer) object; - if (greaterThanZero && i <= 0) { - problems.add(new QuestsConfigLoader.ConfigProblem(QuestsConfigLoader.ConfigProblemType.ERROR, - String.format("Value for field '%s' must be greater than 0", (Object[]) args), path)); - } - } catch (ClassCastException ex) { - problems.add(new QuestsConfigLoader.ConfigProblem(QuestsConfigLoader.ConfigProblemType.ERROR, - String.format("Expected an integer for '%s', but got '" + object + "' instead", (Object[]) args), path)); - } - } - - public static void configValidateBoolean(String path, Object object, List problems, boolean allowNull, String... args) { - if (object == null) { - if (!allowNull) { - problems.add(new QuestsConfigLoader.ConfigProblem(QuestsConfigLoader.ConfigProblemType.ERROR, - String.format("Expected a boolean for '%s', but got null instead", (Object[]) args), path)); - } - return; - } - - try { - Boolean b = (Boolean) object; - } catch (ClassCastException ex) { - problems.add(new QuestsConfigLoader.ConfigProblem(QuestsConfigLoader.ConfigProblemType.ERROR, - String.format("Expected a boolean for '%s', but got '" + object + "' instead", (Object[]) args), path)); - } - } - - public static boolean configValidateExists(String path, Object object, List problems, String... args) { - if (object == null) { - problems.add(new QuestsConfigLoader.ConfigProblem(QuestsConfigLoader.ConfigProblemType.ERROR, - String.format(QuestsConfigLoader.ConfigProblemDescriptions.TASK_MISSING_FIELD.getDescription(args), (Object[]) args), path)); - return false; - } - return true; - } -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/BreedingTaskType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/BreedingTaskType.java deleted file mode 100644 index 501a6aa1..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/BreedingTaskType.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type; - -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.ConfigValue; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.entity.CreatureSpawnEvent; -import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public final class BreedingTaskType extends TaskType { - - private List creatorConfigValues = new ArrayList<>(); - - public BreedingTaskType() { - super("breeding", TaskUtils.TASK_ATTRIBUTION_STRING, "Breed a set amount of animals."); - this.creatorConfigValues.add(new ConfigValue("amount", true, "Amount of animals to be bred")); - this.creatorConfigValues.add(new ConfigValue("worlds", false, "Permitted worlds the player must be in.")); - } - - @Override - public List detectProblemsInConfig(String root, HashMap config) { - ArrayList problems = new ArrayList<>(); - if (TaskUtils.configValidateExists(root + ".amount", config.get("amount"), problems, "amount", super.getType())) - TaskUtils.configValidateInt(root + ".amount", config.get("amount"), problems, false, true, "amount"); - return problems; - } - - @Override - public List getCreatorConfigValues() { - return creatorConfigValues; - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBreed(CreatureSpawnEvent e) { - if (!e.getSpawnReason().equals(SpawnReason.BREEDING)) { - return; - } - - Entity ent = e.getEntity(); - List entList = ent.getNearbyEntities(10, 10, 10); - - if (entList.isEmpty()) { - return; - } - // Check if there is a player in the list, otherwise: return. - for (Entity current : entList) { - if (current instanceof Player && !current.hasMetadata("NPC")) { - Player player = (Player) current; - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(player.getUniqueId()); - if (qPlayer == null) { - continue; - } - - for (Quest quest : super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(super.getType())) { - if (!TaskUtils.validateWorld(player, task)) continue; - - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - if (taskProgress.isCompleted()) { - continue; - } - - int breedingNeeded = (int) task.getConfigValue("amount"); - int breedingProgress; - - if (taskProgress.getProgress() == null) { - breedingProgress = 0; - } else { - breedingProgress = (int) taskProgress.getProgress(); - } - - taskProgress.setProgress(breedingProgress + 1); - - if (((int) taskProgress.getProgress()) >= breedingNeeded) { - taskProgress.setCompleted(true); - } - } - } - } - } - } - } -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/BrewingCertainTaskType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/BrewingCertainTaskType.java deleted file mode 100644 index 2c36f55a..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/BrewingCertainTaskType.java +++ /dev/null @@ -1,114 +0,0 @@ -// TODO: fix -// -//package me.fatpigsarefat.quests.quests.tasktypes.types; -// -//import Quests; -//import QPlayer; -//import QuestProgress; -//import QuestProgressFile; -//import TaskProgress; -//import Quest; -//import Task; -//import ConfigValue; -//import TaskType; -//import org.bukkit.Bukkit; -//import org.bukkit.Location; -//import org.bukkit.Material; -//import org.bukkit.entity.Player; -//import org.bukkit.event.EventHandler; -//import org.bukkit.event.EventPriority; -//import org.bukkit.event.block.Action; -//import org.bukkit.event.inventory.BrewEvent; -//import org.bukkit.event.player.PlayerInteractEvent; -//import org.bukkit.inventory.ItemStack; -// -//import java.util.ArrayList; -//import java.util.HashMap; -//import java.util.List; -//import java.util.UUID; -// -//public final class BrewingCertainTaskType extends TaskType { -// -// private List creatorConfigValues = new ArrayList<>(); -// private HashMap brewingStands = new HashMap<>(); -// -// public BrewingCertainTaskType() { -// super("brewingcertain", "fatpigsarefat", "Brew a certain type of potion."); -// this.creatorConfigValues.add(new ConfigValue("amount", true, "Amount of potions to be brewed.")); -// this.creatorConfigValues.add(new ConfigValue("potion", true, "ID of potion to be brewed.")); -// } -// -// @Override -// public List getCreatorConfigValues() { -// return creatorConfigValues; -// } -// -// @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) -// public void onBlockPlace(PlayerInteractEvent event) { -// if (event.getAction() == Action.RIGHT_CLICK_BLOCK) { -// if (event.getClickedBlock().getType() == Material.BREWING_STAND) { -// brewingStands.put(event.getClickedBlock().getLocation(), event.getPlayer().getUniqueId()); -// } -// } -// } -// -// @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) -// public void onBlockPlace(BrewEvent event) { -// UUID uuid; -// if ((uuid = brewingStands.get(event.getBlock().getLocation())) != null) { -// Player player = Bukkit.getPlayer(uuid); -// -// if (player == null) { -// return; -// } -// -// QPlayer qPlayer = Quests.getPlayerManager().getPlayer(player.getUniqueId()); -// QuestProgressFile questProgressFile = qPlayer.getQuestProgressFile(); -// -// for (Quest quest : super.getRegisteredQuests()) { -// if (questProgressFile.hasStartedQuest(quest)) { -// QuestProgress questProgress = questProgressFile.getQuestProgress(quest); -// -// for (Task task : quest.getTasksOfType(super.getType())) { -// TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); -// -// if (taskProgress.isCompleted()) { -// continue; -// } -// -// int potionsNeeded = (int) task.getConfigValue("amount"); -// -// int progress; -// if (taskProgress.getProgress() == null) { -// progress = 0; -// } else { -// progress = (int) taskProgress.getProgress(); -// } -// -// int potionType = (int) task.getConfigValue("potion"); -// -// ItemStack potion1 = event.getContents().getItem(0); -// if (potion1.getDurability() != potionType) { -// potion1 = null; -// } -// ItemStack potion2 = event.getContents().getItem(1); -// if (potion2.getDurability() != potionType) { -// potion2 = null; -// } -// ItemStack potion3 = event.getContents().getItem(2); -// if (potion3.getDurability() != potionType) { -// potion3 = null; -// } -// -// taskProgress.setProgress(progress + (potion1 == null ? 0 : 1) + (potion2 == null ? 0 : 1) + (potion3 == null ? 0 : 1)); -// -// if (((int) taskProgress.getProgress()) >= potionsNeeded) { -// taskProgress.setCompleted(true); -// } -// } -// } -// } -// } -// } -// -//} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/BrewingTaskType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/BrewingTaskType.java deleted file mode 100644 index 7a0da7de..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/BrewingTaskType.java +++ /dev/null @@ -1,114 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type; - -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.ConfigValue; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.block.Action; -import org.bukkit.event.inventory.BrewEvent; -import org.bukkit.event.player.PlayerInteractEvent; -import org.bukkit.inventory.ItemStack; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.UUID; - -public final class BrewingTaskType extends TaskType { - - private List creatorConfigValues = new ArrayList<>(); - private HashMap brewingStands = new HashMap<>(); - - public BrewingTaskType() { - super("brewing", TaskUtils.TASK_ATTRIBUTION_STRING, "Brew a potion."); - this.creatorConfigValues.add(new ConfigValue("amount", true, "Amount of potions to be brewed.")); - this.creatorConfigValues.add(new ConfigValue("worlds", false, "Permitted worlds the player must be in.")); - } - - @Override - public List detectProblemsInConfig(String root, HashMap config) { - ArrayList problems = new ArrayList<>(); - if (TaskUtils.configValidateExists(root + ".amount", config.get("amount"), problems, "amount", super.getType())) - TaskUtils.configValidateInt(root + ".amount", config.get("amount"), problems, false, true, "amount"); - return problems; - } - - @Override - public List getCreatorConfigValues() { - return creatorConfigValues; - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockPlace(PlayerInteractEvent event) { - if (event.getAction() == Action.RIGHT_CLICK_BLOCK) { - if (event.getClickedBlock().getType() == Material.BREWING_STAND) { - brewingStands.put(event.getClickedBlock().getLocation(), event.getPlayer().getUniqueId()); - } - } - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockPlace(BrewEvent event) { - UUID uuid; - if ((uuid = brewingStands.get(event.getBlock().getLocation())) != null) { - Player player = Bukkit.getPlayer(uuid); - - if (player == null || player.hasMetadata("NPC")) { - return; - } - - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(player.getUniqueId()); - if (qPlayer == null) { - return; - } - - for (Quest quest : super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(super.getType())) { - if (!TaskUtils.validateWorld(player, task)) continue; - - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - if (taskProgress.isCompleted()) { - continue; - } - - int potionsNeeded = (int) task.getConfigValue("amount"); - - int progress; - if (taskProgress.getProgress() == null) { - progress = 0; - } else { - progress = (int) taskProgress.getProgress(); - } - - ItemStack potion1 = event.getContents().getItem(0); - ItemStack potion2 = event.getContents().getItem(1); - ItemStack potion3 = event.getContents().getItem(2); - - taskProgress.setProgress(progress + (potion1 == null ? 0 : 1) + (potion2 == null ? 0 : 1) + (potion3 == null ? 0 : 1)); - - if (((int) taskProgress.getProgress()) >= potionsNeeded) { - taskProgress.setCompleted(true); - } - } - } - } - } - } - -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/BuildingCertainTaskType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/BuildingCertainTaskType.java deleted file mode 100644 index 1e97de3f..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/BuildingCertainTaskType.java +++ /dev/null @@ -1,197 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type; - -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.ConfigValue; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockPlaceEvent; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public final class BuildingCertainTaskType extends TaskType { - - private List creatorConfigValues = new ArrayList<>(); - - public BuildingCertainTaskType() { - super("blockplacecertain", TaskUtils.TASK_ATTRIBUTION_STRING, "Place a set amount of a specific block."); - this.creatorConfigValues.add(new ConfigValue("amount", true, "Amount of blocks to be placed.")); - this.creatorConfigValues.add(new ConfigValue("block", true, "Name or ID of block.")); - this.creatorConfigValues.add(new ConfigValue("data", false, "Data code for block.")); - this.creatorConfigValues.add(new ConfigValue("reverse-if-broken", false, "Will reverse progression if block of same type is broken.")); - this.creatorConfigValues.add(new ConfigValue("use-similar-blocks", false, "(Deprecated) If true, this will ignore orientation of doors, logs etc.")); - this.creatorConfigValues.add(new ConfigValue("worlds", false, "Permitted worlds the player must be in.")); - } - - @Override - public List detectProblemsInConfig(String root, HashMap config) { - ArrayList problems = new ArrayList<>(); - if (TaskUtils.configValidateExists(root + ".amount", config.get("amount"), problems, "amount", super.getType())) - TaskUtils.configValidateInt(root + ".amount", config.get("amount"), problems, false, true, "amount"); - if (config.get("block") == null && config.get("blocks") == null) { - TaskUtils.configValidateExists(root + ".block", config.get("block"), problems, "block", super.getType()); - } else { - Object configBlock; - String source; - if (config.containsKey("block")) { - source = "block"; - } else { - source = "blocks"; - } - configBlock = config.get(source); - List checkBlocks = new ArrayList<>(); - if (configBlock instanceof List) { - checkBlocks.addAll((List) configBlock); - } else { - checkBlocks.add(String.valueOf(configBlock)); - } - - for (String materialName : checkBlocks) { - String[] split = materialName.split(":"); - if (Material.getMaterial(String.valueOf(split[0])) == null) { - problems.add(new QuestsConfigLoader.ConfigProblem(QuestsConfigLoader.ConfigProblemType.WARNING, - QuestsConfigLoader.ConfigProblemDescriptions.UNKNOWN_MATERIAL.getDescription(materialName), root + "." + source)); - } - } - } - TaskUtils.configValidateBoolean(root + ".reverse-if-broken", config.get("reverse-if-broken"), problems, true,"reverse-if-broken"); - TaskUtils.configValidateBoolean(root + ".use-similar-blocks", config.get("use-similar-blocks"), problems, true,"use-similar-blocks"); - TaskUtils.configValidateInt(root + ".data", config.get("data"), problems, true,true, "data"); - return problems; - } - - @Override - public List getCreatorConfigValues() { - return creatorConfigValues; - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockPlace(BlockPlaceEvent event) { - if (event.getPlayer().hasMetadata("NPC")) return; - - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(event.getPlayer().getUniqueId()); - if (qPlayer == null) { - return; - } - - for (Quest quest : super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(super.getType())) { - if (!TaskUtils.validateWorld(event.getPlayer(), task)) continue; - - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - if (taskProgress.isCompleted()) { - continue; - } - - if (matchBlock(task, event.getBlock())) { - increment(task, taskProgress, 1); - } - } - } - } - } - - // subtract if enabled - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockBreak(BlockBreakEvent event) { - if (event.getPlayer().hasMetadata("NPC")) return; - - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(event.getPlayer().getUniqueId()); - if (qPlayer == null) { - return; - } - - for (Quest quest : super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(super.getType())) { - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - if (taskProgress.isCompleted()) { - continue; - } - - if (task.getConfigValue("reverse-if-placed") != null && ((boolean) task.getConfigValue("reverse-if-placed"))) { - if (matchBlock(task, event.getBlock())) { - increment(task, taskProgress, -1); - } - } - } - } - } - } - - @SuppressWarnings("deprecation") - private boolean matchBlock(Task task, Block block) { - Material material; - - Object configBlock = task.getConfigValues().containsKey("block") ? task.getConfigValue("block") : task.getConfigValue("blocks"); - Object configData = task.getConfigValue("data"); - Object configSimilarBlocks = task.getConfigValue("use-similar-blocks"); - - List checkBlocks = new ArrayList<>(); - if (configBlock instanceof List) { - checkBlocks.addAll((List) configBlock); - } else { - checkBlocks.add(String.valueOf(configBlock)); - } - - for (String materialName : checkBlocks) { - // LOG:1 LOG:2 LOG should all be supported with this - String[] split = materialName.split(":"); - int comparableData = 0; - if (configData != null) { - comparableData = (int) configData; - } - if (split.length > 1) { - comparableData = Integer.parseInt(split[1]); - } - - material = Material.getMaterial(String.valueOf(split[0])); - Material blockType = block.getType(); - - short blockData = block.getData(); - - if (blockType == material) { - if (((split.length == 1 && configData == null) || ((int) blockData) == comparableData)) - return true; - } - } - return false; - } - - private void increment(Task task, TaskProgress taskProgress, int amount) { - int brokenBlocksNeeded = (int) task.getConfigValue("amount"); - - int progressBlocksBroken; - if (taskProgress.getProgress() == null) { - progressBlocksBroken = 0; - } else { - progressBlocksBroken = (int) taskProgress.getProgress(); - } - - taskProgress.setProgress(progressBlocksBroken + amount); - - if (((int) taskProgress.getProgress()) >= brokenBlocksNeeded) { - taskProgress.setCompleted(true); - } - } - -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/BuildingTaskType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/BuildingTaskType.java deleted file mode 100644 index 851c152e..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/BuildingTaskType.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type; - -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.ConfigValue; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.block.BlockPlaceEvent; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public final class BuildingTaskType extends TaskType { - - private List creatorConfigValues = new ArrayList<>(); - - public BuildingTaskType() { - super("blockplace", TaskUtils.TASK_ATTRIBUTION_STRING, "Place a set amount of blocks."); - this.creatorConfigValues.add(new ConfigValue("amount", true, "Amount of blocks to be placed.")); - this.creatorConfigValues.add(new ConfigValue("worlds", false, "Permitted worlds the player must be in.")); - } - - @Override - public List detectProblemsInConfig(String root, HashMap config) { - ArrayList problems = new ArrayList<>(); - if (TaskUtils.configValidateExists(root + ".amount", config.get("amount"), problems, "amount", super.getType())) - TaskUtils.configValidateInt(root + ".amount", config.get("amount"), problems, false, true, "amount"); - return problems; - } - - @Override - public List getCreatorConfigValues() { - return creatorConfigValues; - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockPlace(BlockPlaceEvent event) { - if (event.getPlayer().hasMetadata("NPC")) return; - - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(event.getPlayer().getUniqueId()); - if (qPlayer == null) { - return; - } - - for (Quest quest : super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(super.getType())) { - if (!TaskUtils.validateWorld(event.getPlayer(), task)) continue; - - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - if (taskProgress.isCompleted()) { - continue; - } - - int brokenBlocksNeeded = (int) task.getConfigValue("amount"); - - int progressBlocksBroken; - if (taskProgress.getProgress() == null) { - progressBlocksBroken = 0; - } else { - progressBlocksBroken = (int) taskProgress.getProgress(); - } - - taskProgress.setProgress(progressBlocksBroken + 1); - - if (((int) taskProgress.getProgress()) >= brokenBlocksNeeded) { - taskProgress.setCompleted(true); - } - } - } - } - } - -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/CommandTaskType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/CommandTaskType.java deleted file mode 100644 index 5e1522fe..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/CommandTaskType.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type; - -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.ConfigValue; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.player.PlayerCommandPreprocessEvent; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public final class CommandTaskType extends TaskType { - - private List creatorConfigValues = new ArrayList<>(); - - public CommandTaskType() { - super("command", TaskUtils.TASK_ATTRIBUTION_STRING, "Execute a certain command."); - this.creatorConfigValues.add(new ConfigValue("command", true, "The command to execute.")); - this.creatorConfigValues.add(new ConfigValue("ignore-case", false, "Ignore the casing of the command.")); - this.creatorConfigValues.add(new ConfigValue("worlds", false, "Permitted worlds the player must be in.")); - } - - @Override - public List detectProblemsInConfig(String root, HashMap config) { - ArrayList problems = new ArrayList<>(); - TaskUtils.configValidateExists(root + ".command", config.get("command"), problems, "command", super.getType()); - TaskUtils.configValidateBoolean(root + ".ignore-case", config.get("ignore-case"), problems, true, "ignore-case", super.getType()); - return problems; - } - - @Override - public List getCreatorConfigValues() { - return creatorConfigValues; - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onCommand(PlayerCommandPreprocessEvent e) { - if (e.getPlayer().hasMetadata("NPC")) return; - - Player player = e.getPlayer(); - - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(player.getUniqueId()); - if (qPlayer == null) { - return; - } - - for (Quest quest : super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(super.getType())) { - if (!TaskUtils.validateWorld(player, task)) continue; - - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - if (taskProgress.isCompleted()) { - continue; - } - Object configCommand = task.getConfigValue("command"); - Object configIgnoreCase = task.getConfigValue("ignore-case"); - - List commands = new ArrayList<>(); - if (configCommand instanceof List) { - commands.addAll((List) configCommand); - } else { - commands.add(String.valueOf(configCommand)); - } - - boolean ignoreCasing = false; - if (configIgnoreCase != null) { - ignoreCasing = (boolean) task.getConfigValue("ignore-case"); - } - String message = e.getMessage(); - if (message.length() >= 1) { - message = message.substring(1); - } - - for (String command : commands) { - if (ignoreCasing && command.equalsIgnoreCase(message)) { - taskProgress.setCompleted(true); - } else if (!ignoreCasing && command.equals(message)) { - taskProgress.setCompleted(true); - } - } - } - } - } - } -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/DealDamageTaskType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/DealDamageTaskType.java deleted file mode 100644 index 6affa258..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/DealDamageTaskType.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type; - -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.ConfigValue; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.entity.EntityDamageByEntityEvent; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public final class DealDamageTaskType extends TaskType { - - private List creatorConfigValues = new ArrayList<>(); - - public DealDamageTaskType() { - super("dealdamage", TaskUtils.TASK_ATTRIBUTION_STRING, "Deal a certain amount of damage."); - this.creatorConfigValues.add(new ConfigValue("amount", true, "Amount of damage you need to deal")); - this.creatorConfigValues.add(new ConfigValue("worlds", false, "Permitted worlds the player must be in.")); - } - - @Override - public List detectProblemsInConfig(String root, HashMap config) { - ArrayList problems = new ArrayList<>(); - if (TaskUtils.configValidateExists(root + ".amount", config.get("amount"), problems, "amount", super.getType())) - TaskUtils.configValidateInt(root + ".amount", config.get("amount"), problems, false, true, "amount"); - return problems; - } - - @Override - public List getCreatorConfigValues() { - return creatorConfigValues; - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onDamage(EntityDamageByEntityEvent e) { - if (!(e.getDamager() instanceof Player)) { - return; - } - - Player player = (Player) e.getDamager(); - double damage = e.getDamage(); - - if (player.hasMetadata("NPC")) return; - - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(player.getUniqueId()); - if (qPlayer == null) { - return; - } - - for (Quest quest : super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(super.getType())) { - if (!TaskUtils.validateWorld(player, task)) continue; - - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - if (taskProgress.isCompleted()) { - continue; - } - - double progressDamage; - int damageNeeded = (int) task.getConfigValue("amount"); - - if (taskProgress.getProgress() == null) { - progressDamage = 0.0; - } else { - progressDamage = (double) taskProgress.getProgress(); - } - - taskProgress.setProgress(progressDamage + damage); - - if (((double) taskProgress.getProgress()) >= (double) damageNeeded) { - taskProgress.setProgress(damageNeeded); - taskProgress.setCompleted(true); - } - } - } - } - } -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/DistancefromTaskType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/DistancefromTaskType.java deleted file mode 100644 index 604ea556..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/DistancefromTaskType.java +++ /dev/null @@ -1,118 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type; - -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.ConfigValue; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.player.PlayerMoveEvent; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public final class DistancefromTaskType extends TaskType { - - private List creatorConfigValues = new ArrayList<>(); - - public DistancefromTaskType() { - super("distancefrom", TaskUtils.TASK_ATTRIBUTION_STRING, "Distance yourself from a set of co-ordinates."); - this.creatorConfigValues.add(new ConfigValue("x", true, "X position.")); - this.creatorConfigValues.add(new ConfigValue("y", true, "Y position.")); - this.creatorConfigValues.add(new ConfigValue("z", true, "Z position.")); - this.creatorConfigValues.add(new ConfigValue("world", true, "Name of world.")); - this.creatorConfigValues.add(new ConfigValue("distance", true, "Distance the player needs to be from the co-ordinates.")); - } - - @Override - public List detectProblemsInConfig(String root, HashMap config) { - ArrayList problems = new ArrayList<>(); - if (TaskUtils.configValidateExists(root + ".x", config.get("x"), problems, "x", super.getType())) - TaskUtils.configValidateInt(root + ".x", config.get("x"), problems, false, false, "x"); - if (TaskUtils.configValidateExists(root + ".y", config.get("y"), problems, "y", super.getType())) - TaskUtils.configValidateInt(root + ".y", config.get("y"), problems, false, false, "y"); - if (TaskUtils.configValidateExists(root + ".z", config.get("z"), problems, "z", super.getType())) - TaskUtils.configValidateInt(root + ".z", config.get("z"), problems, false, false, "z"); - if (TaskUtils.configValidateExists(root + ".distance", config.get("distance"), problems, "distance", super.getType())) - TaskUtils.configValidateInt(root + ".distance", config.get("distance"), problems, false, true, "distance"); - return problems; - } - - @Override - public List getCreatorConfigValues() { - return creatorConfigValues; - } - -// private HashMap> distanceSquaredCache = new HashMap<>(); -// -// @Override -// public void onReady() { -// distanceSquaredCache.clear(); -// for (Quest quest : super.getRegisteredQuests()) { -// HashMap squaredDistances = new HashMap<>(); -// for (Task task : quest.getTasksOfType(super.getType())) { -// int distance = (int) task.getConfigValue("distance"); -// squaredDistances.put(task.getId(), distance); -// } -// distanceSquaredCache.put(quest.getId(), squaredDistances); -// } -// } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMove(PlayerMoveEvent event) { - if (event.getFrom().getBlockX() == event.getTo().getBlockX() && event.getFrom().getBlockZ() == event.getTo().getBlockZ()) { - return; - } - - if (event.getPlayer().hasMetadata("NPC")) return; - Player player = event.getPlayer(); - - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(player.getUniqueId()); - if (qPlayer == null) { - return; - } - - for (Quest quest : super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(super.getType())) { - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - if (taskProgress.isCompleted()) { - continue; - } - - int x = (int) task.getConfigValue("x"); - int y = (int) task.getConfigValue("y"); - int z = (int) task.getConfigValue("z"); - String worldString = (String) task.getConfigValue("world"); - int distance = (int) task.getConfigValue("distance"); - int distanceSquared = distance * distance; - - World world = Bukkit.getWorld(worldString); - if (world == null) { - continue; - } - - Location location = new Location(world, x, y, z); - if (player.getWorld().equals(world) && player.getLocation().distanceSquared(location) > distanceSquared) { - taskProgress.setCompleted(true); - } - } - } - } - } - -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/EnchantingTaskType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/EnchantingTaskType.java deleted file mode 100644 index fc0b2421..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/EnchantingTaskType.java +++ /dev/null @@ -1,87 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type; - -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.ConfigValue; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.enchantment.EnchantItemEvent; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public final class EnchantingTaskType extends TaskType { - - private List creatorConfigValues = new ArrayList<>(); - - public EnchantingTaskType() { - super("enchanting", TaskUtils.TASK_ATTRIBUTION_STRING, "Enchant a certain amount of items."); - this.creatorConfigValues.add(new ConfigValue("amount", true, "Amount of items you need to enchant.")); - this.creatorConfigValues.add(new ConfigValue("worlds", false, "Permitted worlds the player must be in.")); - } - - @Override - public List detectProblemsInConfig(String root, HashMap config) { - ArrayList problems = new ArrayList<>(); - if (TaskUtils.configValidateExists(root + ".amount", config.get("amount"), problems, "amount", super.getType())) - TaskUtils.configValidateInt(root + ".amount", config.get("amount"), problems, false, true, "amount"); - return problems; - } - - @Override - public List getCreatorConfigValues() { - return creatorConfigValues; - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onEnchant(EnchantItemEvent e) { - if (e.getEnchanter().hasMetadata("NPC")) return; - - Player player = e.getEnchanter(); - - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(player.getUniqueId()); - if (qPlayer == null) { - return; - } - - for (Quest quest : super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(super.getType())) { - if (!TaskUtils.validateWorld(player, task)) continue; - - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - if (taskProgress.isCompleted()) { - continue; - } - - int enchantsNeeded = (int) task.getConfigValue("amount"); - - int progressEnchant; - if (taskProgress.getProgress() == null) { - progressEnchant = 0; - } else { - progressEnchant = (int) taskProgress.getProgress(); - } - - taskProgress.setProgress(progressEnchant + 1); - - if (((int) taskProgress.getProgress()) >= enchantsNeeded) { - taskProgress.setCompleted(true); - } - } - } - } - } -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/ExpEarnTaskType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/ExpEarnTaskType.java deleted file mode 100644 index d99688c8..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/ExpEarnTaskType.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type; - -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.ConfigValue; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.player.PlayerExpChangeEvent; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public final class ExpEarnTaskType extends TaskType { - - private List creatorConfigValues = new ArrayList<>(); - - public ExpEarnTaskType() { - super("expearn", TaskUtils.TASK_ATTRIBUTION_STRING, "Earn a set amount of exp."); - this.creatorConfigValues.add(new ConfigValue("amount", true, "Amount of exp that needs to be earned.")); - this.creatorConfigValues.add(new ConfigValue("worlds", false, "Permitted worlds the player must be in.")); - } - - @Override - public List detectProblemsInConfig(String root, HashMap config) { - ArrayList problems = new ArrayList<>(); - if (TaskUtils.configValidateExists(root + ".amount", config.get("amount"), problems, "amount", super.getType())) - TaskUtils.configValidateInt(root + ".amount", config.get("amount"), problems, false, true, "amount"); - return problems; - } - - @Override - public List getCreatorConfigValues() { - return creatorConfigValues; - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onExpEarn(PlayerExpChangeEvent e) { - if (e.getPlayer().hasMetadata("NPC")) return; - - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(e.getPlayer().getUniqueId()); - if (qPlayer == null) { - return; - } - - - for (Quest quest : super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(super.getType())) { - if (!TaskUtils.validateWorld(e.getPlayer(), task)) continue; - - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - if (taskProgress.isCompleted()) { - continue; - } - int amount = e.getAmount(); - int expNeeded = (int) task.getConfigValue("amount"); - - int progressExp; - if (taskProgress.getProgress() == null) { - progressExp = 0; - } else { - progressExp = (int) taskProgress.getProgress(); - } - - taskProgress.setProgress(progressExp + amount); - - if (((int) taskProgress.getProgress()) >= expNeeded) { - taskProgress.setCompleted(true); - } - } - } - } - } -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/FarmingTaskType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/FarmingTaskType.java deleted file mode 100644 index 62223e6d..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/FarmingTaskType.java +++ /dev/null @@ -1,96 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type; - -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.ConfigValue; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import org.bukkit.Material; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.material.Crops; - -import java.util.ArrayList; -import java.util.List; - -public final class FarmingTaskType extends TaskType { - - private List creatorConfigValues = new ArrayList<>(); - - public FarmingTaskType() { - super("farming", TaskUtils.TASK_ATTRIBUTION_STRING, "Break a set amount of a crop."); - this.creatorConfigValues.add(new ConfigValue("amount", true, "Amount of crops to be broken.")); - this.creatorConfigValues.add(new ConfigValue("crop", true, "Name or ID of crop.")); - this.creatorConfigValues.add(new ConfigValue("worlds", false, "Permitted worlds the player must be in.")); - } - - @Override - public List getCreatorConfigValues() { - return creatorConfigValues; - } - - @SuppressWarnings("deprecation") - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockBreak(BlockBreakEvent event) { - //TODO: finish this - if (!(event.getBlock().getState() instanceof Crops)) { - return; - } - Crops crop = (Crops) event.getBlock().getState(); - - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(event.getPlayer().getUniqueId()); - if (qPlayer == null) { - return; - } - - for (Quest quest : super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(super.getType())) { - if (!TaskUtils.validateWorld(event.getPlayer(), task)) continue; - - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - if (taskProgress.isCompleted()) { - continue; - } - - Material material; - Object configBlock = task.getConfigValue("block"); - Object configData = task.getConfigValue("data"); - - material = Material.matchMaterial(String.valueOf(configBlock)); - - - if (material != null && event.getBlock().getType().equals(material)) { - - if (configData != null && (((int) event.getBlock().getData()) != ((int) configData))) { - continue; - } - int brokenBlocksNeeded = (int) task.getConfigValue("amount"); - - int progressBlocksBroken; - if (taskProgress.getProgress() == null) { - progressBlocksBroken = 0; - } else { - progressBlocksBroken = (int) taskProgress.getProgress(); - } - - taskProgress.setProgress(progressBlocksBroken + 1); - - if (((int) taskProgress.getProgress()) >= brokenBlocksNeeded) { - taskProgress.setCompleted(true); - } - } - } - } - } - } - -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/FishingTaskType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/FishingTaskType.java deleted file mode 100644 index c35044af..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/FishingTaskType.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type; - -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.ConfigValue; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.player.PlayerFishEvent; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public final class FishingTaskType extends TaskType { - - private List creatorConfigValues = new ArrayList<>(); - - public FishingTaskType() { - super("fishing", TaskUtils.TASK_ATTRIBUTION_STRING, "Catch a set amount of items from the sea."); - this.creatorConfigValues.add(new ConfigValue("amount", true, "Amount of fish to be caught.")); - this.creatorConfigValues.add(new ConfigValue("worlds", false, "Permitted worlds the player must be in.")); - } - - @Override - public List detectProblemsInConfig(String root, HashMap config) { - ArrayList problems = new ArrayList<>(); - if (TaskUtils.configValidateExists(root + ".amount", config.get("amount"), problems, "amount", super.getType())) - TaskUtils.configValidateInt(root + ".amount", config.get("amount"), problems, false, true, "amount"); - return problems; - } - - @Override - public List getCreatorConfigValues() { - return creatorConfigValues; - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onFishCaught(PlayerFishEvent event) { - if (event.getPlayer().hasMetadata("NPC")) return; - - if (event.getState() != PlayerFishEvent.State.CAUGHT_FISH) { - return; - } - -// Location hookLocation = event.getHook().getLocation().add(0, -1, 0); -// if (!(hookLocation.getBlock().getType() == Material.WATER)) { -// return; -// } - - Player player = event.getPlayer(); - - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(player.getUniqueId()); - if (qPlayer == null) { - return; - } - - for (Quest quest : super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(super.getType())) { - if (!TaskUtils.validateWorld(player, task)) continue; - - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - if (taskProgress.isCompleted()) { - continue; - } - - int catchesNeeded = (int) task.getConfigValue("amount"); - - int progressCatches; - if (taskProgress.getProgress() == null) { - progressCatches = 0; - } else { - progressCatches = (int) taskProgress.getProgress(); - } - - taskProgress.setProgress(progressCatches + 1); - - if (((int) taskProgress.getProgress()) >= catchesNeeded) { - taskProgress.setCompleted(true); - } - } - } - } - } - -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/InventoryTaskType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/InventoryTaskType.java deleted file mode 100644 index 4ee6e605..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/InventoryTaskType.java +++ /dev/null @@ -1,183 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type; - -import com.leonardobishop.quests.Quests; -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.ConfigValue; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import org.bukkit.Bukkit; -import org.bukkit.Material; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.inventory.InventoryCloseEvent; -import org.bukkit.event.player.PlayerPickupItemEvent; -import org.bukkit.inventory.ItemStack; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public final class InventoryTaskType extends TaskType { - - private List creatorConfigValues = new ArrayList<>(); - private final Quests plugin; - - public InventoryTaskType(Quests plugin) { - super("inventory", TaskUtils.TASK_ATTRIBUTION_STRING, "Obtain a set of items."); - this.plugin = plugin; - this.creatorConfigValues.add(new ConfigValue("amount", true, "Amount of item to retrieve.")); - this.creatorConfigValues.add(new ConfigValue("item", true, "Name or ID of item.")); - this.creatorConfigValues.add(new ConfigValue("data", false, "Data of item.")); - this.creatorConfigValues.add(new ConfigValue("remove-items-when-complete", false, "Take the items away from the player on completion (true/false, " + - "default = false).")); - this.creatorConfigValues.add(new ConfigValue("update-progress", false, "Update the displayed progress (if this causes lag then disable it).")); - this.creatorConfigValues.add(new ConfigValue("worlds", false, "Permitted worlds the player must be in.")); - } - - @Override - public List detectProblemsInConfig(String root, HashMap config) { - ArrayList problems = new ArrayList<>(); - if (TaskUtils.configValidateExists(root + ".item", config.get("item"), problems, "item", super.getType())) { - Object configBlock = config.get("item"); - if (configBlock instanceof ConfigurationSection) { - ConfigurationSection section = (ConfigurationSection) configBlock; - String itemloc = "item"; - if (!section.contains("item")) { - itemloc = "type"; - } - if (!section.contains(itemloc)) { - problems.add(new QuestsConfigLoader.ConfigProblem(QuestsConfigLoader.ConfigProblemType.WARNING, - QuestsConfigLoader.ConfigProblemDescriptions.UNKNOWN_MATERIAL.getDescription(""), root + ".item.type")); - } else { - String type = String.valueOf(section.get(itemloc)); - if (!plugin.getItemGetter().isValidMaterial(type)) { - problems.add(new QuestsConfigLoader.ConfigProblem(QuestsConfigLoader.ConfigProblemType.WARNING, - QuestsConfigLoader.ConfigProblemDescriptions.UNKNOWN_MATERIAL.getDescription(type), root + ".item." + itemloc)); - } - } - } else { - if (Material.getMaterial(String.valueOf(configBlock)) == null) { - problems.add(new QuestsConfigLoader.ConfigProblem(QuestsConfigLoader.ConfigProblemType.WARNING, - QuestsConfigLoader.ConfigProblemDescriptions.UNKNOWN_MATERIAL.getDescription(String.valueOf(configBlock)), root + ".item.item")); - } - } - } - if (TaskUtils.configValidateExists(root + ".amount", config.get("amount"), problems, "amount", super.getType())) - TaskUtils.configValidateInt(root + ".amount", config.get("amount"), problems, false, true, "amount"); - TaskUtils.configValidateInt(root + ".data", config.get("data"), problems, true, false, "data"); - TaskUtils.configValidateBoolean(root + ".remove-items-when-complete", config.get("remove-items-when-complete"), problems, true, "remove-items-when-complete", super.getType()); - TaskUtils.configValidateBoolean(root + ".update-progress", config.get("update-progress"), problems, true, "update-progress", super.getType()); - return problems; - } - - - @Override - public List getCreatorConfigValues() { - return creatorConfigValues; - } - - @SuppressWarnings("deprecation") - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onItemPickup(PlayerPickupItemEvent event) { - if (event.getPlayer().hasMetadata("NPC")) return; - - Bukkit.getScheduler().runTaskLater(plugin, () -> this.checkInventory(event.getPlayer()), 1L); - } - - @EventHandler(priority = EventPriority.MONITOR) - public void onInventoryClick(InventoryCloseEvent event) { - Bukkit.getScheduler().runTaskLater(plugin, () -> checkInventory((Player) event.getPlayer()), 1L); //Still some work to do as it doesn't really work - } - - @SuppressWarnings("deprecation") - private void checkInventory(Player player) { - if (player == null || !player.isOnline()) { - return; - } - - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(player.getUniqueId()); - if (qPlayer == null) { - return; - } - - for (Quest quest : super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(super.getType())) { - if (!TaskUtils.validateWorld(player, task)) continue; - - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - if (taskProgress.isCompleted()) { - continue; - } - - Material material; - int amount = (int) task.getConfigValue("amount"); - Object configBlock = task.getConfigValue("item"); - Object configData = task.getConfigValue("data"); - Object remove = task.getConfigValue("remove-items-when-complete"); - - ItemStack is; - if (configBlock instanceof ConfigurationSection) { - is = plugin.getItemStack("", (org.bukkit.configuration.ConfigurationSection) configBlock); - } else { - material = Material.getMaterial(String.valueOf(configBlock)); - - if (material == null) { - continue; - } - if (configData != null) { - is = new ItemStack(material, 1, ((Integer) configData).shortValue()); - } else { - is = new ItemStack(material, 1); - } - } - - if (task.getConfigValue("update-progress") != null - && (Boolean) task.getConfigValue("update-progress")) { - int inInv = getAmount(player, is, amount); - if (taskProgress.getProgress() != null && (int) taskProgress.getProgress() != inInv) { - taskProgress.setProgress(inInv); - } else if (taskProgress.getProgress() == null) { - taskProgress.setProgress(inInv); - } - } - - if (player.getInventory().containsAtLeast(is, amount)) { - is.setAmount(amount); - taskProgress.setCompleted(true); - - if (remove != null && ((Boolean) remove)) { - player.getInventory().removeItem(is); - } - } - } - } - } - } - - private int getAmount(Player player, ItemStack is, int max) { - if (is == null) { - return 0; - } - int amount = 0; - for (int i = 0; i < 36; i++) { - ItemStack slot = player.getInventory().getItem(i); - if (slot == null || !slot.isSimilar(is)) - continue; - amount += slot.getAmount(); - } - return Math.min(amount, max); - } - -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/MilkingTaskType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/MilkingTaskType.java deleted file mode 100644 index 0d883ac2..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/MilkingTaskType.java +++ /dev/null @@ -1,98 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type; - -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.QuestProgressFile; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.ConfigValue; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import org.bukkit.Material; -import org.bukkit.entity.Cow; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.player.PlayerInteractEntityEvent; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public final class MilkingTaskType extends TaskType { - - private List creatorConfigValues = new ArrayList<>(); - - public MilkingTaskType() { - super("milking", TaskUtils.TASK_ATTRIBUTION_STRING, "Milk a set amount of cows."); - this.creatorConfigValues.add(new ConfigValue("amount", true, "Amount of cows to be milked.")); - this.creatorConfigValues.add(new ConfigValue("worlds", false, "Permitted worlds the player must be in.")); - } - - @Override - public List detectProblemsInConfig(String root, HashMap config) { - ArrayList problems = new ArrayList<>(); - if (TaskUtils.configValidateExists(root + ".amount", config.get("amount"), problems, "amount", super.getType())) - TaskUtils.configValidateInt(root + ".amount", config.get("amount"), problems, false, true, "amount"); - return problems; - } - - @Override - public List getCreatorConfigValues() { - return creatorConfigValues; - } - - @SuppressWarnings("deprecation") - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMilk(PlayerInteractEntityEvent event) { - if (!(event.getRightClicked() instanceof Cow) || (event.getPlayer().getItemInHand().getType() != Material.BUCKET)) { - return; - } - - if (event.getPlayer().hasMetadata("NPC")) return; - - Player player = event.getPlayer(); - - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(player.getUniqueId()); - if (qPlayer == null) { - return; - } - - QuestProgressFile questProgressFile = qPlayer.getQuestProgressFile(); - - for (Quest quest : super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(super.getType())) { - if (!TaskUtils.validateWorld(player, task)) continue; - - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - if (taskProgress.isCompleted()) { - continue; - } - - int cowsNeeded = (int) task.getConfigValue("amount"); - - int progressMilked; - if (taskProgress.getProgress() == null) { - progressMilked = 0; - } else { - progressMilked = (int) taskProgress.getProgress(); - } - - taskProgress.setProgress(progressMilked + 1); - - if (((int) taskProgress.getProgress()) >= cowsNeeded) { - taskProgress.setCompleted(true); - } - } - } - } - } - -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/MiningCertainTaskType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/MiningCertainTaskType.java deleted file mode 100644 index 7639ad95..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/MiningCertainTaskType.java +++ /dev/null @@ -1,211 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type; - -import com.leonardobishop.quests.Quests; -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.ConfigValue; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import org.bukkit.Material; -import org.bukkit.block.Block; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.block.BlockBreakEvent; -import org.bukkit.event.block.BlockPlaceEvent; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public final class MiningCertainTaskType extends TaskType { - - private final Quests plugin; - private List creatorConfigValues = new ArrayList<>(); - - public MiningCertainTaskType(Quests plugin) { - super("blockbreakcertain", TaskUtils.TASK_ATTRIBUTION_STRING, "Break a set amount of a specific block."); - this.plugin = plugin; - this.creatorConfigValues.add(new ConfigValue("amount", true, "Amount of blocks to be broken.")); - this.creatorConfigValues.add(new ConfigValue("block", true, "Name or ID of block.", "block")); // Can use name:datacode - this.creatorConfigValues.add(new ConfigValue("blocks", true, "List of blocks (alias for block for config readability).", "block")); - this.creatorConfigValues.add(new ConfigValue("data", false, "Data code for block.")); // only used if no datacode provided in block or blocks - this.creatorConfigValues.add(new ConfigValue("reverse-if-placed", false, "Will reverse progression if block of same type is placed.")); - this.creatorConfigValues.add(new ConfigValue("check-coreprotect", false, "Use coreprotect to check for blocks placed by a player")); - this.creatorConfigValues.add(new ConfigValue("check-coreprotect-time", false, "Time period for coreprotect check")); - this.creatorConfigValues.add(new ConfigValue("use-similar-blocks", false, "(Deprecated) If true, this will ignore orientation of doors, logs etc.")); - this.creatorConfigValues.add(new ConfigValue("worlds", false, "Permitted worlds the player must be in.")); - } - - @Override - public List detectProblemsInConfig(String root, HashMap config) { - ArrayList problems = new ArrayList<>(); - if (TaskUtils.configValidateExists(root + ".amount", config.get("amount"), problems, "amount", super.getType())) - TaskUtils.configValidateInt(root + ".amount", config.get("amount"), problems, false, true, "amount"); - if (config.get("block") == null && config.get("blocks") == null) { - TaskUtils.configValidateExists(root + ".block", config.get("block"), problems, "block", super.getType()); - } else { - Object configBlock; - String source; - if (config.containsKey("block")) { - source = "block"; - } else { - source = "blocks"; - } - configBlock = config.get(source); - List checkBlocks = new ArrayList<>(); - if (configBlock instanceof List) { - checkBlocks.addAll((List) configBlock); - } else { - checkBlocks.add(String.valueOf(configBlock)); - } - - for (String materialName : checkBlocks) { - String[] split = materialName.split(":"); - if (Material.getMaterial(String.valueOf(split[0])) == null) { - problems.add(new QuestsConfigLoader.ConfigProblem(QuestsConfigLoader.ConfigProblemType.WARNING, - QuestsConfigLoader.ConfigProblemDescriptions.UNKNOWN_MATERIAL.getDescription(materialName), root + "." + source)); - } - } - } - TaskUtils.configValidateBoolean(root + ".reverse-if-broken", config.get("reverse-if-broken"), problems, true,"reverse-if-broken"); - TaskUtils.configValidateBoolean(root + ".check-coreprotect", config.get("check-coreprotect"), problems, true,"check-coreprotect"); - TaskUtils.configValidateInt(root + ".check-coreprotect-time", config.get("check-coreprotect-time"), problems, true,true, "check-coreprotect-time"); - TaskUtils.configValidateBoolean(root + ".use-similar-blocks", config.get("use-similar-blocks"), problems, true,"use-similar-blocks"); - TaskUtils.configValidateInt(root + ".data", config.get("data"), problems, true,true, "data"); - return problems; - } - - @Override - public List getCreatorConfigValues() { - return creatorConfigValues; - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockBreak(BlockBreakEvent event) { - if (event.getPlayer().hasMetadata("NPC")) return; - - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(event.getPlayer().getUniqueId()); - if (qPlayer == null) { - return; - } - - for (Quest quest : super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(super.getType())) { - if (!TaskUtils.validateWorld(event.getPlayer(), task)) continue; - - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - if (taskProgress.isCompleted()) { - continue; - } - - if (matchBlock(task, event.getBlock())) { - boolean coreProtectEnabled = (boolean) task.getConfigValue("check-coreprotect", false); - int coreProtectTime = (int) task.getConfigValue("check-coreprotect-time", 3600); - - if (coreProtectEnabled && plugin.getCoreProtectHook().checkBlock(event.getBlock(), coreProtectTime)) { - continue; - } - increment(task, taskProgress, 1); - } - } - } - } - } - - // subtract if enabled - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockPlace(BlockPlaceEvent event) { - if (event.getPlayer().hasMetadata("NPC")) return; - - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(event.getPlayer().getUniqueId()); - if (qPlayer == null) { - return; - } - - for (Quest quest : super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(super.getType())) { - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - if (taskProgress.isCompleted()) { - continue; - } - - if (task.getConfigValue("reverse-if-placed") != null && ((boolean) task.getConfigValue("reverse-if-placed"))) { - if (matchBlock(task, event.getBlock())) { - increment(task, taskProgress, -1); - } - } - } - } - } - } - - @SuppressWarnings("deprecation") - private boolean matchBlock(Task task, Block block) { - Material material; - - Object configBlock = task.getConfigValues().containsKey("block") ? task.getConfigValue("block") : task.getConfigValue("blocks"); - Object configData = task.getConfigValue("data"); - Object configSimilarBlocks = task.getConfigValue("use-similar-blocks"); - - List checkBlocks = new ArrayList<>(); - if (configBlock instanceof List) { - checkBlocks.addAll((List) configBlock); - } else { - checkBlocks.add(String.valueOf(configBlock)); - } - - for (String materialName : checkBlocks) { - // LOG:1 LOG:2 LOG should all be supported with this - String[] split = materialName.split(":"); - int comparableData = 0; - if (configData != null) { - comparableData = (int) configData; - } - if (split.length > 1) { - comparableData = Integer.parseInt(split[1]); - } - - material = Material.getMaterial(String.valueOf(split[0])); - Material blockType = block.getType(); - - short blockData = block.getData(); - - if (blockType == material) { - if (((split.length == 1 && configData == null) || ((int) blockData) == comparableData)) - return true; - } - } - return false; - } - - private void increment(Task task, TaskProgress taskProgress, int amount) { - int brokenBlocksNeeded = (int) task.getConfigValue("amount"); - - int progressBlocksBroken; - if (taskProgress.getProgress() == null) { - progressBlocksBroken = 0; - } else { - progressBlocksBroken = (int) taskProgress.getProgress(); - } - - taskProgress.setProgress(progressBlocksBroken + amount); - - if (((int) taskProgress.getProgress()) >= brokenBlocksNeeded) { - taskProgress.setCompleted(true); - } - } - -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/MiningTaskType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/MiningTaskType.java deleted file mode 100644 index e25adcff..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/MiningTaskType.java +++ /dev/null @@ -1,88 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type; - -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.ConfigValue; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.block.BlockBreakEvent; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public final class MiningTaskType extends TaskType { - - private List creatorConfigValues = new ArrayList<>(); - - public MiningTaskType() { - // type, author, description - super("blockbreak", TaskUtils.TASK_ATTRIBUTION_STRING, "Break a set amount of blocks."); - - // config values for the quest creator to use, if unspecified then the quest creator will not know what to put here (and will require users to - // go into the config and manually configure there) - this.creatorConfigValues.add(new ConfigValue("amount", true, "Amount of blocks to be broken.")); - } - - @Override - public List detectProblemsInConfig(String root, HashMap config) { - ArrayList problems = new ArrayList<>(); - if (TaskUtils.configValidateExists(root + ".amount", config.get("amount"), problems, "amount", super.getType())) - TaskUtils.configValidateInt(root + ".amount", config.get("amount"), problems, false, true, "amount"); - return problems; - } - - @Override - public List getCreatorConfigValues() { - return creatorConfigValues; - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onBlockBreak(BlockBreakEvent event) { - if (event.getPlayer().hasMetadata("NPC")) return; // citizens also causes these events to fire - - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(event.getPlayer().getUniqueId()); // get the qplayer so you can get their progress - if (qPlayer == null) { - return; - } - - for (Quest quest : super.getRegisteredQuests()) { // iterate through all quests which are registered to use this task type - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(super.getType())) { // get all tasks of this type - if (!TaskUtils.validateWorld(event.getPlayer(), task)) continue; - - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); // get the task progress and increment progress by 1 - - if (taskProgress.isCompleted()) { // dont need to increment a completed task - continue; - } - - int brokenBlocksNeeded = (int) task.getConfigValue("amount"); // this will retrieve a value from the config under the key "value" - - int progressBlocksBroken; - if (taskProgress.getProgress() == null) { // note: if the player has never progressed before, getProgress() will return null - progressBlocksBroken = 0; - } else { - progressBlocksBroken = (int) taskProgress.getProgress(); - } - - taskProgress.setProgress(progressBlocksBroken + 1); // the progress does not have to be an int, although must be serializable by the yaml provider - - if (((int) taskProgress.getProgress()) >= brokenBlocksNeeded) { // completion statement, if true the task is complete - taskProgress.setCompleted(true); - } - } - } - } - } - -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/MobkillingCertainTaskType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/MobkillingCertainTaskType.java deleted file mode 100644 index 86bd7fea..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/MobkillingCertainTaskType.java +++ /dev/null @@ -1,145 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type; - -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.ConfigValue; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import org.bukkit.ChatColor; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.entity.EntityDeathEvent; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public final class MobkillingCertainTaskType extends TaskType { - - private List creatorConfigValues = new ArrayList<>(); - - public MobkillingCertainTaskType() { - super("mobkillingcertain", TaskUtils.TASK_ATTRIBUTION_STRING, "Kill a set amount of a specific entity type."); - this.creatorConfigValues.add(new ConfigValue("amount", true, "Amount of mobs to be killed.")); - this.creatorConfigValues.add(new ConfigValue("mob", true, "Name of mob.")); - this.creatorConfigValues.add(new ConfigValue("name", false, "Only allow a specific name for mob (unspecified = any name allowed).")); - } - - @Override - public List detectProblemsInConfig(String root, HashMap config) { - ArrayList problems = new ArrayList<>(); - if (TaskUtils.configValidateExists(root + ".mob", config.get("mob"), problems, "mob", super.getType())) { - try { - EntityType.valueOf(String.valueOf(config.get("mob"))); - } catch (IllegalArgumentException ex) { - problems.add(new QuestsConfigLoader.ConfigProblem(QuestsConfigLoader.ConfigProblemType.WARNING, - QuestsConfigLoader.ConfigProblemDescriptions.UNKNOWN_ENTITY_TYPE.getDescription(String.valueOf(config.get("mob"))), root + ".mob")); - } - } - if (TaskUtils.configValidateExists(root + ".amount", config.get("amount"), problems, "amount", super.getType())) - TaskUtils.configValidateInt(root + ".amount", config.get("amount"), problems, false, true, "amount"); - return problems; - } - - - @Override - public List getCreatorConfigValues() { - return creatorConfigValues; - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMobKill(EntityDeathEvent event) { - Player killer = event.getEntity().getKiller(); - Entity mob = event.getEntity(); - - if (mob == null || mob instanceof Player) { - return; - } - - if (killer == null) { - return; - } - - if (killer.hasMetadata("NPC")) return; - - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(killer.getUniqueId()); - if (qPlayer == null) { - return; - } - - for (Quest quest : super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(super.getType())) { - if (!TaskUtils.validateWorld(killer, task)) continue; - - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - if (taskProgress.isCompleted()) { - continue; - } - - String configEntity = (String) task.getConfigValue("mob"); - - EntityType entity; - try { - entity = EntityType.valueOf(configEntity); - } catch (IllegalArgumentException ex) { - continue; - } - - Object configName = task.getConfigValues().containsKey("name") ? task.getConfigValue("name") : task.getConfigValue("names"); - - if (configName != null) { - List configNames = new ArrayList<>(); - if (configName instanceof List) { - configNames.addAll((List) configName); - } else { - configNames.add(String.valueOf(configName)); - } - - boolean validName = false; - for (String name : configNames) { - name = ChatColor.translateAlternateColorCodes('&', name); - if (mob.getCustomName() == null || !mob.getCustomName().equals(name)) { - validName = true; - break; - } - } - - if (!validName) continue; - } - - if (mob.getType() != entity) { - continue; - } - - int mobKillsNeeded = (int) task.getConfigValue("amount"); - - int progressKills; - if (taskProgress.getProgress() == null) { - progressKills = 0; - } else { - progressKills = (int) taskProgress.getProgress(); - } - - taskProgress.setProgress(progressKills + 1); - - if (((int) taskProgress.getProgress()) >= mobKillsNeeded) { - taskProgress.setCompleted(true); - } - } - } - } - } - -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/MobkillingTaskType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/MobkillingTaskType.java deleted file mode 100644 index dd43bd60..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/MobkillingTaskType.java +++ /dev/null @@ -1,116 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type; - -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.ConfigValue; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import org.bukkit.entity.Animals; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Monster; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.entity.EntityDeathEvent; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public final class MobkillingTaskType extends TaskType { - - private List creatorConfigValues = new ArrayList<>(); - - public MobkillingTaskType() { - super("mobkilling", TaskUtils.TASK_ATTRIBUTION_STRING, "Kill a set amount of entities."); - this.creatorConfigValues.add(new ConfigValue("amount", true, "Amount of mobs to be killed.")); - this.creatorConfigValues.add(new ConfigValue("hostile", false, "Only allow hostile or non-hostile mobs (unspecified = any type allowed).")); - } - - @Override - public List detectProblemsInConfig(String root, HashMap config) { - ArrayList problems = new ArrayList<>(); - if (TaskUtils.configValidateExists(root + ".amount", config.get("amount"), problems, "amount", super.getType())) - TaskUtils.configValidateInt(root + ".amount", config.get("amount"), problems, false, true, "amount"); - TaskUtils.configValidateBoolean(root + ".hostile", config.get("hostile"), problems, true, "hostile"); - return problems; - } - - @Override - public List getCreatorConfigValues() { - return creatorConfigValues; - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMobKill(EntityDeathEvent event) { - Player killer = event.getEntity().getKiller(); //The killer is a player - Entity mob = event.getEntity(); - - if (mob == null || mob instanceof Player) { - return; - } - - if (killer == null) { - return; - } - - if (killer.hasMetadata("NPC")) return; - - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(killer.getUniqueId()); - if (qPlayer == null) { - return; - } - - for (Quest quest : super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(super.getType())) { - if (!TaskUtils.validateWorld(killer, task)) continue; - - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - if (taskProgress.isCompleted()) { - continue; - } - - boolean hostilitySpecified = false; - boolean hostile = false; - if (task.getConfigValue("hostile") != null) { - hostilitySpecified = true; - hostile = (boolean) task.getConfigValue("hostile"); - } - - if (hostilitySpecified) { - if (!hostile && !(mob instanceof Animals)) { - continue; - } else if (hostile && !(mob instanceof Monster)) { - continue; - } - } - - int mobKillsNeeded = (int) task.getConfigValue("amount"); - - int progressKills; - if (taskProgress.getProgress() == null) { - progressKills = 0; - } else { - progressKills = (int) taskProgress.getProgress(); - } - - taskProgress.setProgress(progressKills + 1); - - if (((int) taskProgress.getProgress()) >= mobKillsNeeded) { - taskProgress.setCompleted(true); - } - } - } - } - } - -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/PermissionTaskType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/PermissionTaskType.java deleted file mode 100644 index 3043aeb0..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/PermissionTaskType.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type; - -import com.leonardobishop.quests.Quests; -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.ConfigValue; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.scheduler.BukkitTask; - -import java.util.ArrayList; -import java.util.List; - -public final class PermissionTaskType extends TaskType { - - private Quests plugin; - private BukkitTask poll; - private List creatorConfigValues = new ArrayList<>(); - - public PermissionTaskType(Quests plugin) { - super("permission", TaskUtils.TASK_ATTRIBUTION_STRING, "Test if a player has a permission"); - this.plugin = plugin; - this.creatorConfigValues.add(new ConfigValue("permission", true, "The required permission.")); - } - - @Override - public void onReady() { - this.poll = new BukkitRunnable() { - @Override - public void run() { - for (Player player : Bukkit.getOnlinePlayers()) { - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(player.getUniqueId()); - if (qPlayer == null) { - continue; - } - for (Quest quest : PermissionTaskType.super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - for (Task task : quest.getTasksOfType(PermissionTaskType.super.getType())) { - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - if (taskProgress.isCompleted()) { - continue; - } - String permission = (String) task.getConfigValue("permission"); - if (permission != null) { - if (player.hasPermission(permission)) { - taskProgress.setCompleted(true); - } - } - } - } - } - } - } - }.runTaskTimer(plugin, 30L, 30L); - } - - @Override - public void onDisable() { - if (this.poll != null) { - this.poll.cancel(); - } - } - - @Override - public List getCreatorConfigValues() { - return creatorConfigValues; - } -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/PlayerkillingTaskType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/PlayerkillingTaskType.java deleted file mode 100644 index 60bb1321..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/PlayerkillingTaskType.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type; - -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.ConfigValue; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.entity.EntityDeathEvent; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public final class PlayerkillingTaskType extends TaskType { - - private List creatorConfigValues = new ArrayList<>(); - - public PlayerkillingTaskType() { - super("playerkilling", TaskUtils.TASK_ATTRIBUTION_STRING, "Kill a set amount of players."); - this.creatorConfigValues.add(new ConfigValue("amount", true, "Amount of players to be killed.")); - } - - @Override - public List detectProblemsInConfig(String root, HashMap config) { - ArrayList problems = new ArrayList<>(); - if (TaskUtils.configValidateExists(root + ".amount", config.get("amount"), problems, "amount", super.getType())) - TaskUtils.configValidateInt(root + ".amount", config.get("amount"), problems, false, true, "amount"); - return problems; - } - - @Override - public List getCreatorConfigValues() { - return creatorConfigValues; - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMobKill(EntityDeathEvent event) { - Player killer = event.getEntity().getKiller(); - Entity mob = event.getEntity(); - - if (!(mob instanceof Player)) { - return; - } - - if (killer == null) { - return; - } - - if (killer.hasMetadata("NPC")) return; - - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(killer.getUniqueId()); - if (qPlayer == null) { - return; - } - - for (Quest quest : super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(super.getType())) { - if (!TaskUtils.validateWorld(killer, task)) continue; - - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - if (taskProgress.isCompleted()) { - continue; - } - - int playerKillsNeeded = (int) task.getConfigValue("amount"); - - int progressKills; - if (taskProgress.getProgress() == null) { - progressKills = 0; - } else { - progressKills = (int) taskProgress.getProgress(); - } - - taskProgress.setProgress(progressKills + 1); - - if (((int) taskProgress.getProgress()) >= playerKillsNeeded) { - taskProgress.setCompleted(true); - } - } - } - } - } - -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/PlaytimeTaskType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/PlaytimeTaskType.java deleted file mode 100644 index 450365cb..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/PlaytimeTaskType.java +++ /dev/null @@ -1,95 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type; - -import com.leonardobishop.quests.Quests; -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.ConfigValue; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.scheduler.BukkitTask; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public final class PlaytimeTaskType extends TaskType { - - private final Quests plugin; - private BukkitTask poll; - private List creatorConfigValues = new ArrayList<>(); - - public PlaytimeTaskType(Quests plugin) { - super("playtime", TaskUtils.TASK_ATTRIBUTION_STRING, "Track the amount of playing time a user has been on"); - this.plugin = plugin; - this.creatorConfigValues.add(new ConfigValue("minutes", true, "Time in minutes.")); - } - - @Override - public List detectProblemsInConfig(String root, HashMap config) { - ArrayList problems = new ArrayList<>(); - if (TaskUtils.configValidateExists(root + ".minutes", config.get("minutes"), problems, "minutes", super.getType())) - TaskUtils.configValidateInt(root + ".minutes", config.get("minutes"), problems, false, true, "minutes"); - return problems; - } - - - @Override - public void onReady() { - if (this.poll == null) { - this.poll = new BukkitRunnable() { - @Override - public void run() { - for (Player player : Bukkit.getOnlinePlayers()) { - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(player.getUniqueId()); - if (qPlayer == null) { - continue; - } - - for (Quest quest : PlaytimeTaskType.super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - for (Task task : quest.getTasksOfType(PlaytimeTaskType.super.getType())) { - if (!TaskUtils.validateWorld(player, task)) continue; - - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - if (taskProgress.isCompleted()) { - continue; - } - int minutes = (int) task.getConfigValue("minutes"); - if (taskProgress.getProgress() == null) { - taskProgress.setProgress(1); - } else { - taskProgress.setProgress((int) taskProgress.getProgress() + 1); - } - if (((int) taskProgress.getProgress()) >= minutes) { - taskProgress.setCompleted(true); - } - } - } - } - } - } - }.runTaskTimer(plugin, 1200L, 1200L); - } - } - - @Override - public void onDisable() { -// if (this.poll != null) { -// this.poll.cancel(); -// } - } - - @Override - public List getCreatorConfigValues() { - return creatorConfigValues; - } -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/PositionTaskType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/PositionTaskType.java deleted file mode 100644 index 546cdb10..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/PositionTaskType.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type; - -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.ConfigValue; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import org.bukkit.Bukkit; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.player.PlayerMoveEvent; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public final class PositionTaskType extends TaskType { - - private List creatorConfigValues = new ArrayList<>(); - - public PositionTaskType() { - super("position", TaskUtils.TASK_ATTRIBUTION_STRING, "Reach a set of co-ordinates."); - this.creatorConfigValues.add(new ConfigValue("x", true, "X position.")); - this.creatorConfigValues.add(new ConfigValue("y", true, "Y position.")); - this.creatorConfigValues.add(new ConfigValue("z", true, "Z position.")); - this.creatorConfigValues.add(new ConfigValue("world", true, "Name of world.")); - this.creatorConfigValues.add(new ConfigValue("distance-padding", false, "Padding zone in meters/blocks (default/unspecified = 0).")); - } - - @Override - public List detectProblemsInConfig(String root, HashMap config) { - ArrayList problems = new ArrayList<>(); - TaskUtils.configValidateExists(root + ".world", config.get("world"), problems, "world", super.getType()); - if (TaskUtils.configValidateExists(root + ".x", config.get("x"), problems, "x", super.getType())) - TaskUtils.configValidateInt(root + ".x", config.get("x"), problems, false, false, "x"); - if (TaskUtils.configValidateExists(root + ".y", config.get("y"), problems, "y", super.getType())) - TaskUtils.configValidateInt(root + ".y", config.get("y"), problems, false, false, "y"); - if (TaskUtils.configValidateExists(root + ".z", config.get("z"), problems, "z", super.getType())) - TaskUtils.configValidateInt(root + ".z", config.get("z"), problems, false, false, "z"); - TaskUtils.configValidateInt(root + ".distance-padding", config.get("distance-padding"), problems, true, true, "distance-padding"); - return problems; - } - - @Override - public List getCreatorConfigValues() { - return creatorConfigValues; - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMove(PlayerMoveEvent event) { - if (event.getFrom().getBlockX() == event.getTo().getBlockX() && event.getFrom().getBlockZ() == event.getTo().getBlockZ()) { - return; - } - - if (event.getPlayer().hasMetadata("NPC")) return; - - Player player = event.getPlayer(); - - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(player.getUniqueId()); - if (qPlayer == null) { - return; - } - - for (Quest quest : super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(super.getType())) { - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - if (taskProgress.isCompleted()) { - continue; - } - - int x = (int) task.getConfigValue("x"); - int y = (int) task.getConfigValue("y"); - int z = (int) task.getConfigValue("z"); - String worldString = (String) task.getConfigValue("world"); - int padding = 0; - if (task.getConfigValue("distance-padding") != null) { - padding = (int) task.getConfigValue("distance-padding"); - } - int paddingSquared = padding * padding; - World world = Bukkit.getWorld(worldString); - if (world == null) { - continue; - } - - Location location = new Location(world, x, y, z); - if (player.getWorld().equals(world) && player.getLocation().getBlockX() == location.getBlockX() && player.getLocation().getBlockY() == location.getBlockY() && player.getLocation().getBlockZ() == location.getBlockZ()) { - taskProgress.setCompleted(true); - } else if (padding != 0 && player.getWorld().equals(world) && player.getLocation().distanceSquared(location) < paddingSquared) { - taskProgress.setCompleted(true); - } - } - } - } - } - -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/ShearingTaskType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/ShearingTaskType.java deleted file mode 100644 index ca4856a4..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/ShearingTaskType.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type; - -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.ConfigValue; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import org.bukkit.entity.Player; -import org.bukkit.entity.Sheep; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.player.PlayerShearEntityEvent; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public final class ShearingTaskType extends TaskType { - - private List creatorConfigValues = new ArrayList<>(); - - public ShearingTaskType() { - super("shearing", TaskUtils.TASK_ATTRIBUTION_STRING, "Shear a set amount of sheep."); - this.creatorConfigValues.add(new ConfigValue("amount", true, "Amount of cows to be milked.")); - } - - @Override - public List detectProblemsInConfig(String root, HashMap config) { - ArrayList problems = new ArrayList<>(); - if (TaskUtils.configValidateExists(root + ".amount", config.get("amount"), problems, "amount", super.getType())) - TaskUtils.configValidateInt(root + ".amount", config.get("amount"), problems, false, true, "amount"); - return problems; - } - - - @Override - public List getCreatorConfigValues() { - return creatorConfigValues; - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onShear(PlayerShearEntityEvent event) { - if (!(event.getEntity() instanceof Sheep)) { - return; - } - - if (event.getPlayer().hasMetadata("NPC")) return; - - Player player = event.getPlayer(); - - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(player.getUniqueId()); - if (qPlayer == null) { - return; - } - - for (Quest quest : super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(super.getType())) { - if (!TaskUtils.validateWorld(player, task)) continue; - - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - if (taskProgress.isCompleted()) { - continue; - } - - int sheepNeeded = (int) task.getConfigValue("amount"); - - int progressSheared; - if (taskProgress.getProgress() == null) { - progressSheared = 0; - } else { - progressSheared = (int) taskProgress.getProgress(); - } - - taskProgress.setProgress(progressSheared + 1); - - if (((int) taskProgress.getProgress()) >= sheepNeeded) { - taskProgress.setCompleted(true); - } - } - } - } - } - -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/TamingTaskType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/TamingTaskType.java deleted file mode 100644 index 663ca403..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/TamingTaskType.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type; - -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.ConfigValue; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.entity.EntityTameEvent; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public final class TamingTaskType extends TaskType { - - private List creatorConfigValues = new ArrayList<>(); - - public TamingTaskType() { - super("taming", TaskUtils.TASK_ATTRIBUTION_STRING, "Tame a set amount of animals."); - this.creatorConfigValues.add(new ConfigValue("amount", true, "Amount of animals to be tamed.")); - } - - @Override - public List detectProblemsInConfig(String root, HashMap config) { - ArrayList problems = new ArrayList<>(); - if (TaskUtils.configValidateExists(root + ".amount", config.get("amount"), problems, "amount", super.getType())) - TaskUtils.configValidateInt(root + ".amount", config.get("amount"), problems, false, true, "amount"); - return problems; - } - - - @Override - public List getCreatorConfigValues() { - return creatorConfigValues; - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onTame(EntityTameEvent event) { - if (!(event.getOwner() instanceof Player)) { - return; - } - - Player player = (Player) event.getOwner(); - - if (player.hasMetadata("NPC")) return; - - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(player.getUniqueId()); - if (qPlayer == null) { - return; - } - - for (Quest quest : super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(super.getType())) { - if (!TaskUtils.validateWorld(player, task)) continue; - - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - if (taskProgress.isCompleted()) { - continue; - } - - int tamesNeeded = (int) task.getConfigValue("amount"); - - int progressTamed; - if (taskProgress.getProgress() == null) { - progressTamed = 0; - } else { - progressTamed = (int) taskProgress.getProgress(); - } - - taskProgress.setProgress(progressTamed + 1); - - if (((int) taskProgress.getProgress()) >= tamesNeeded) { - taskProgress.setCompleted(true); - } - } - } - } - } - -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/WalkingTaskType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/WalkingTaskType.java deleted file mode 100644 index 4faebdb0..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/WalkingTaskType.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type; - -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.ConfigValue; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.event.player.PlayerMoveEvent; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public final class WalkingTaskType extends TaskType { - - private List creatorConfigValues = new ArrayList<>(); - - public WalkingTaskType() { - super("walking", TaskUtils.TASK_ATTRIBUTION_STRING, "Walk a set distance."); - this.creatorConfigValues.add(new ConfigValue("distance", true, "Amount of meters (blocks) to be travelled.")); - } - - @Override - public List detectProblemsInConfig(String root, HashMap config) { - ArrayList problems = new ArrayList<>(); - if (TaskUtils.configValidateExists(root + ".distance", config.get("distance"), problems, "distance", super.getType())) - TaskUtils.configValidateInt(root + ".distance", config.get("distance"), problems, false, true, "distance"); - return problems; - } - - - @Override - public List getCreatorConfigValues() { - return creatorConfigValues; - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMove(PlayerMoveEvent event) { - if (event.getFrom().getBlockX() == event.getTo().getBlockX() && event.getFrom().getBlockZ() == event.getTo().getBlockZ()) { - return; - } - - Player player = event.getPlayer(); - - if (player.hasMetadata("NPC")) return; - - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(player.getUniqueId()); - if (qPlayer == null) { - return; - } - - for (Quest quest : super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(super.getType())) { - if (!TaskUtils.validateWorld(player, task)) continue; - - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - if (taskProgress.isCompleted()) { - continue; - } - - int distanceNeeded = (int) task.getConfigValue("distance"); - - int progressDistance; - if (taskProgress.getProgress() == null) { - progressDistance = 0; - } else { - progressDistance = (int) taskProgress.getProgress(); - } - - taskProgress.setProgress(progressDistance + 1); - - if (((int) taskProgress.getProgress()) >= distanceNeeded) { - taskProgress.setCompleted(true); - } - } - } - } - } - -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/ASkyBlockLevelType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/ASkyBlockLevelType.java deleted file mode 100644 index bd0aba60..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/ASkyBlockLevelType.java +++ /dev/null @@ -1,72 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type.dependent; - -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.ConfigValue; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import com.wasteofplastic.askyblock.events.IslandPostLevelEvent; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public final class ASkyBlockLevelType extends TaskType { - - private List creatorConfigValues = new ArrayList<>(); - - public ASkyBlockLevelType() { - super("askyblock_level", TaskUtils.TASK_ATTRIBUTION_STRING, "Reach a certain island level for ASkyBlock."); - this.creatorConfigValues.add(new ConfigValue("level", true, "Minimum island level needed.")); - } - - @Override - public List detectProblemsInConfig(String root, HashMap config) { - ArrayList problems = new ArrayList<>(); - if (TaskUtils.configValidateExists(root + ".level", config.get("level"), problems, "level", super.getType())) - TaskUtils.configValidateInt(root + ".level", config.get("level"), problems, false, false, "level"); - return problems; - } - - @Override - public List getCreatorConfigValues() { - return creatorConfigValues; - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onIslandLevel(IslandPostLevelEvent event) { - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(event.getPlayer()); - if (qPlayer == null) { - return; - } - - for (Quest quest : super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(super.getType())) { - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - if (taskProgress.isCompleted()) { - continue; - } - - long islandLevelNeeded = (long) (int) task.getConfigValue("level"); - - taskProgress.setProgress(event.getLongLevel()); - - if (((long) taskProgress.getProgress()) >= islandLevelNeeded) { - taskProgress.setCompleted(true); - } - } - } - } - } -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/BentoBoxLevelTaskType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/BentoBoxLevelTaskType.java deleted file mode 100644 index 00f4e12f..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/BentoBoxLevelTaskType.java +++ /dev/null @@ -1,105 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type.dependent; - -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.ConfigValue; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskTypeManager; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import org.bukkit.event.EventHandler; -import world.bentobox.bentobox.BentoBox; -import world.bentobox.bentobox.api.events.BentoBoxEvent; -import world.bentobox.bentobox.database.objects.Island; - -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicLong; - -public final class BentoBoxLevelTaskType extends TaskType { - - private List creatorConfigValues = new ArrayList<>(); - private Field levelField = null; - - public BentoBoxLevelTaskType() { - super("bentobox_level", TaskUtils.TASK_ATTRIBUTION_STRING, "Reach a certain island level in the level addon for BentoBox."); - this.creatorConfigValues.add(new ConfigValue("level", true, "Minimum island level needed.")); - } - - @Override - public List detectProblemsInConfig(String root, HashMap config) { - ArrayList problems = new ArrayList<>(); - if (TaskUtils.configValidateExists(root + ".level", config.get("level"), problems, "level", super.getType())) - TaskUtils.configValidateInt(root + ".level", config.get("level"), problems, false, false, "level"); - return problems; - } - - @Override - public List getCreatorConfigValues() { - return creatorConfigValues; - } - - public static void register(TaskTypeManager manager) { - if (BentoBox.getInstance().getAddonsManager().getAddonByName("Level").isPresent()) { - manager.registerTaskType(new BentoBoxLevelTaskType()); - } - } - - @EventHandler - public void onBentoBoxIslandLevelCalculated(BentoBoxEvent event) { - Map keyValues = event.getKeyValues(); - - if ("IslandLevelCalculatedEvent".equalsIgnoreCase(event.getEventName())) { - Island island = (Island) keyValues.get("island"); - - for (UUID member : island.getMemberSet()) { - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(member); - if (qPlayer == null) { - continue; - } - - for (Quest quest : super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(super.getType())) { - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - if (taskProgress.isCompleted()) { - continue; - } - - long islandLevelNeeded = (long) (int) task.getConfigValue("level"); - - Object results = keyValues.get("results"); - - try { - if (levelField == null) { - levelField = results.getClass().getDeclaredField("level"); - levelField.setAccessible(true); - } - - AtomicLong level = (AtomicLong) levelField.get(results); - taskProgress.setProgress(level.get()); - } catch (NoSuchFieldException | IllegalAccessException e) { - e.printStackTrace(); - } - - if (((long) taskProgress.getProgress()) >= islandLevelNeeded) { - taskProgress.setCompleted(true); - } - } - } - } - } - } - } -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/CitizensDeliverTaskType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/CitizensDeliverTaskType.java deleted file mode 100644 index 5110d51d..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/CitizensDeliverTaskType.java +++ /dev/null @@ -1,150 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type.dependent; - -import com.leonardobishop.quests.Quests; -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.ConfigValue; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import net.citizensnpcs.api.event.NPCRightClickEvent; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.Material; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import org.bukkit.inventory.ItemStack; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public final class CitizensDeliverTaskType extends TaskType { - - private final Quests plugin; - private List creatorConfigValues = new ArrayList<>(); - - public CitizensDeliverTaskType(Quests plugin) { - super("citizens_deliver", TaskUtils.TASK_ATTRIBUTION_STRING, "Deliver a set of items to a NPC."); - this.plugin = plugin; - this.creatorConfigValues.add(new ConfigValue("amount", true, "Amount of item to retrieve.")); - this.creatorConfigValues.add(new ConfigValue("item", true, "Name or ID of item.")); - this.creatorConfigValues.add(new ConfigValue("npc-name", true, "Name of the NPC.")); - this.creatorConfigValues.add(new ConfigValue("remove-items-when-complete", false, "Take the items away from the player on completion (true/false, " + - "default = false).")); - this.creatorConfigValues.add(new ConfigValue("worlds", false, "Permitted worlds the player must be in.")); - } - - @Override - public List detectProblemsInConfig(String root, HashMap config) { - ArrayList problems = new ArrayList<>(); - if (TaskUtils.configValidateExists(root + ".item", config.get("item"), problems, "item", super.getType())) { - Object configBlock = config.get("item"); - if (configBlock instanceof ConfigurationSection) { - ConfigurationSection section = (ConfigurationSection) configBlock; - String itemloc = "item"; - if (!section.contains("item")) { - itemloc = "type"; - } - if (!section.contains(itemloc)) { - problems.add(new QuestsConfigLoader.ConfigProblem(QuestsConfigLoader.ConfigProblemType.WARNING, - QuestsConfigLoader.ConfigProblemDescriptions.UNKNOWN_MATERIAL.getDescription(""), root + ".item.type")); - } else { - String type = String.valueOf(section.get(itemloc)); - if (!plugin.getItemGetter().isValidMaterial(type)) { - problems.add(new QuestsConfigLoader.ConfigProblem(QuestsConfigLoader.ConfigProblemType.WARNING, - QuestsConfigLoader.ConfigProblemDescriptions.UNKNOWN_MATERIAL.getDescription(type), root + ".item." + itemloc)); - } - } - } else { - if (Material.getMaterial(String.valueOf(configBlock)) == null) { - problems.add(new QuestsConfigLoader.ConfigProblem(QuestsConfigLoader.ConfigProblemType.WARNING, - QuestsConfigLoader.ConfigProblemDescriptions.UNKNOWN_MATERIAL.getDescription(String.valueOf(configBlock)), root + ".item.item")); - } - } - } - if (TaskUtils.configValidateExists(root + ".amount", config.get("amount"), problems, "amount", super.getType())) - TaskUtils.configValidateInt(root + ".amount", config.get("amount"), problems, false, true, "amount"); - TaskUtils.configValidateExists(root + ".npc-name", config.get("npc-name"), problems, "npc-name", super.getType()); - TaskUtils.configValidateBoolean(root + ".remove-items-when-complete", config.get("remove-items-when-complete"), problems, true, "remove-items-when-complete", super.getType()); - return problems; - } - - @Override - public List getCreatorConfigValues() { - return creatorConfigValues; - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onNPCClick(NPCRightClickEvent event) { - Bukkit.getScheduler().runTaskLater(plugin, () -> checkInventory(event.getClicker(), event.getNPC().getName()), 1L); - } - - @SuppressWarnings("deprecation") - private void checkInventory(Player player, String citizenName) { - if (player == null || !player.isOnline()) { - return; - } - QPlayer qPlayer = plugin.getPlayerManager().getPlayer(player.getUniqueId()); - if (qPlayer == null) { - return; - } - - for (Quest quest : super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(super.getType())) { - if (!ChatColor.stripColor(ChatColor.translateAlternateColorCodes('&', String.valueOf(task.getConfigValue("npc-name")))).equals(ChatColor - .stripColor(ChatColor.translateAlternateColorCodes('&', citizenName)))) { - return; - } - if (!TaskUtils.validateWorld(player, task)) continue; - - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - if (taskProgress.isCompleted()) { - continue; - } - - Material material; - int amount = (int) task.getConfigValue("amount"); - Object configBlock = task.getConfigValue("item"); - Object configData = task.getConfigValue("data"); - Object remove = task.getConfigValue("remove-items-when-complete"); - - ItemStack is; - if (configBlock instanceof ConfigurationSection) { - is = Quests.get().getItemStack("", (org.bukkit.configuration.ConfigurationSection) configBlock); - } else { - material = Material.getMaterial(String.valueOf(configBlock)); - - if (material == null) { - continue; - } - if (configData != null) { - is = new ItemStack(material, 1, ((Integer) configData).shortValue()); - } else { - is = new ItemStack(material, 1); - } - } - - if (player.getInventory().containsAtLeast(is, amount)) { - is.setAmount(amount); - taskProgress.setCompleted(true); - - if (remove != null && ((Boolean) remove)) { - player.getInventory().removeItem(is); - } - } - } - } - } - } - -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/CitizensInteractTaskType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/CitizensInteractTaskType.java deleted file mode 100644 index 08440b05..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/CitizensInteractTaskType.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type.dependent; - -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.ConfigValue; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import net.citizensnpcs.api.event.NPCRightClickEvent; -import org.bukkit.ChatColor; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public final class CitizensInteractTaskType extends TaskType { - - private List creatorConfigValues = new ArrayList<>(); - - public CitizensInteractTaskType() { - super("citizens_interact", TaskUtils.TASK_ATTRIBUTION_STRING, "Interact with an NPC to complete the quest."); - this.creatorConfigValues.add(new ConfigValue("npc-name", true, "Name of the NPC.")); - this.creatorConfigValues.add(new ConfigValue("worlds", false, "Permitted worlds the player must be in.")); - } - - @Override - public List detectProblemsInConfig(String root, HashMap config) { - ArrayList problems = new ArrayList<>(); - TaskUtils.configValidateExists(root + ".npc-name", config.get("npc-name"), problems, "npc-name", super.getType()); - TaskUtils.configValidateBoolean(root + ".remove-items-when-complete", config.get("remove-items-when-complete"), problems, true, "remove-items-when-complete", super.getType()); - return problems; - } - - - @Override - public List getCreatorConfigValues() { - return creatorConfigValues; - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onNPCClick(NPCRightClickEvent event) { - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(event.getClicker().getUniqueId()); - if (qPlayer == null) { - return; - } - - for (Quest quest : super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(super.getType())) { - if (!TaskUtils.validateWorld(event.getClicker(), task)) continue; - - if (!ChatColor.stripColor(ChatColor.translateAlternateColorCodes('&', String.valueOf(task.getConfigValue("npc-name")))).equals(ChatColor - .stripColor(ChatColor.translateAlternateColorCodes('&', event.getNPC().getName())))) { - return; - } - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - if (taskProgress.isCompleted()) { - continue; - } - - taskProgress.setCompleted(true); - } - } - } - } - -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/EssentialsBalanceTaskType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/EssentialsBalanceTaskType.java deleted file mode 100644 index eaf6ba13..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/EssentialsBalanceTaskType.java +++ /dev/null @@ -1,101 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type.dependent; - -import com.earth2me.essentials.Essentials; -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.QuestProgressFile; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.ConfigValue; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import net.ess3.api.events.UserBalanceUpdateEvent; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; - -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.UUID; - -public class EssentialsBalanceTaskType extends TaskType { - - private List creatorConfigValues = new ArrayList<>(); - - public EssentialsBalanceTaskType() { - super("essentials_balance", TaskUtils.TASK_ATTRIBUTION_STRING, "Reach a set amount of money."); - this.creatorConfigValues.add(new ConfigValue("amount", true, "Amount of money to reach.")); - } - - @Override - public List detectProblemsInConfig(String root, HashMap config) { - ArrayList problems = new ArrayList<>(); - if (TaskUtils.configValidateExists(root + ".amount", config.get("amount"), problems, "amount", super.getType())) - TaskUtils.configValidateInt(root + ".amount", config.get("amount"), problems, false, false, "amount"); - return problems; - } - - @Override - public void onStart(Quest quest, Task task, UUID playerUUID) { - Player player = Bukkit.getPlayer(playerUUID); - Essentials ess = (Essentials) Bukkit.getPluginManager().getPlugin("Essentials"); - if (player != null && player.isOnline() && ess != null) { - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(playerUUID); - if (qPlayer == null) { - return; - } - QuestProgressFile questProgressFile = qPlayer.getQuestProgressFile(); - QuestProgress questProgress = questProgressFile.getQuestProgress(quest); - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - int earningsNeeded = (int) task.getConfigValue("amount"); - BigDecimal money = ess.getUser(player).getMoney(); - taskProgress.setProgress(money); - if (money.compareTo(BigDecimal.valueOf(earningsNeeded)) > 0) { - taskProgress.setCompleted(true); - } - } - } - - @Override - public List getCreatorConfigValues() { - return creatorConfigValues; - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMoneyEarn(UserBalanceUpdateEvent event) { - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(event.getPlayer().getUniqueId()); - if (qPlayer == null) { - return; - } - - for (Quest quest : super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(super.getType())) { - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - if (taskProgress.isCompleted()) { - continue; - } - - int earningsNeeded = (int) task.getConfigValue("amount"); - - taskProgress.setProgress(event.getNewBalance()); - - if (event.getNewBalance().compareTo(BigDecimal.valueOf(earningsNeeded)) > 0) { - taskProgress.setCompleted(true); - } - } - } - } - } - -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/EssentialsMoneyEarnTaskType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/EssentialsMoneyEarnTaskType.java deleted file mode 100644 index 6b080f13..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/EssentialsMoneyEarnTaskType.java +++ /dev/null @@ -1,80 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type.dependent; - -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.ConfigValue; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import net.ess3.api.events.UserBalanceUpdateEvent; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; - -import java.math.BigDecimal; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public class EssentialsMoneyEarnTaskType extends TaskType { - - private List creatorConfigValues = new ArrayList<>(); - - public EssentialsMoneyEarnTaskType() { - super("essentials_moneyearn", TaskUtils.TASK_ATTRIBUTION_STRING, "Earn a set amount of money."); - this.creatorConfigValues.add(new ConfigValue("amount", true, "Amount of money to earn.")); - } - - @Override - public List detectProblemsInConfig(String root, HashMap config) { - ArrayList problems = new ArrayList<>(); - if (TaskUtils.configValidateExists(root + ".amount", config.get("amount"), problems, "amount", super.getType())) - TaskUtils.configValidateInt(root + ".amount", config.get("amount"), problems, false, false, "amount"); - return problems; - } - - - @Override - public List getCreatorConfigValues() { - return creatorConfigValues; - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMoneyEarn(UserBalanceUpdateEvent event) { - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(event.getPlayer().getUniqueId()); - if (qPlayer == null) { - return; - } - - for (Quest quest : super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(super.getType())) { - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - if (taskProgress.isCompleted()) { - continue; - } - - int earningsNeeded = (int) task.getConfigValue("amount"); - - BigDecimal current = (BigDecimal) taskProgress.getProgress(); - if (current == null) { - current = new BigDecimal(0); - } - BigDecimal newProgress = current.add(event.getNewBalance().subtract(event.getOldBalance())); - taskProgress.setProgress(newProgress); - - if (newProgress.compareTo(BigDecimal.valueOf(earningsNeeded)) > 0) { - taskProgress.setCompleted(true); - } - } - } - } - } - -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/IridiumSkyblockValueType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/IridiumSkyblockValueType.java deleted file mode 100644 index 3647a3e7..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/IridiumSkyblockValueType.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type.dependent; - -import com.iridium.iridiumskyblock.Island; -import com.iridium.iridiumskyblock.api.IslandWorthCalculatedEvent; -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.ConfigValue; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.UUID; - -public final class IridiumSkyblockValueType extends TaskType { - - private List creatorConfigValues = new ArrayList<>(); - - public IridiumSkyblockValueType() { - super("iridiumskyblock_value", TaskUtils.TASK_ATTRIBUTION_STRING, "Reach a certain island value for Iridium Skyblock."); - this.creatorConfigValues.add(new ConfigValue("value", true, "Minimum island value needed.")); - } - - @Override - public List detectProblemsInConfig(String root, HashMap config) { - ArrayList problems = new ArrayList<>(); - if (TaskUtils.configValidateExists(root + ".value", config.get("value"), problems, "value", super.getType())) - TaskUtils.configValidateInt(root + ".value", config.get("value"), problems, false, false, "value"); - return problems; - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onIslandLevel(IslandWorthCalculatedEvent event) { - Island island = event.getIsland(); - for (String player : island.members) { - UUID uuid; - try { - uuid = UUID.fromString(player); - } catch (Exception e) { - continue; - } - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(uuid); - if (qPlayer == null) { - continue; - } - - for (Quest quest : IridiumSkyblockValueType.super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(IridiumSkyblockValueType.super.getType())) { - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - if (taskProgress.isCompleted()) { - continue; - } - - int islandValueNeeded = (int) task.getConfigValue("value"); - - taskProgress.setProgress(event.getIslandWorth()); - - if (((double) taskProgress.getProgress()) >= islandValueNeeded) { - taskProgress.setCompleted(true); - } - } - } - } - } - - } - - @Override - public List getCreatorConfigValues() { - return creatorConfigValues; - } - -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/MythicMobsKillingType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/MythicMobsKillingType.java deleted file mode 100644 index 47245665..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/MythicMobsKillingType.java +++ /dev/null @@ -1,115 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type.dependent; - -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.ConfigValue; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import io.lumine.xikage.mythicmobs.api.bukkit.events.MythicMobDeathEvent; -import org.bukkit.entity.Entity; -import org.bukkit.entity.Player; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public final class MythicMobsKillingType extends TaskType { - - private List creatorConfigValues = new ArrayList<>(); - - public MythicMobsKillingType() { - super("mythicmobs_killing", TaskUtils.TASK_ATTRIBUTION_STRING, "Kill a set amount of a MythicMobs entity."); - this.creatorConfigValues.add(new ConfigValue("amount", true, "Amount of mobs to be killed.")); - this.creatorConfigValues.add(new ConfigValue("name", true, "The 'internal name' of the MythicMob.")); - this.creatorConfigValues.add(new ConfigValue("min-level", true, "The minimum level for the MythicMob.")); - } - - @Override - public List detectProblemsInConfig(String root, HashMap config) { - ArrayList problems = new ArrayList<>(); - TaskUtils.configValidateExists(root + ".name", config.get("name"), problems, "name", super.getType()); - if (TaskUtils.configValidateExists(root + ".amount", config.get("amount"), problems, "amount", super.getType())) - TaskUtils.configValidateInt(root + ".amount", config.get("amount"), problems, false, true, "amount"); - TaskUtils.configValidateInt(root + ".level", config.get("level"), problems, true, true, "level"); - TaskUtils.configValidateInt(root + ".min-level", config.get("min-level"), problems, true, true, "min-level"); - return problems; - } - - @Override - public List getCreatorConfigValues() { - return creatorConfigValues; - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMobKill(MythicMobDeathEvent event) { - Entity killer = event.getKiller(); - Entity mob = event.getEntity(); - - if (mob == null || mob instanceof Player) { - return; - } - - if (killer == null) { - return; - } - - String mobName = event.getMobType().getInternalName(); - double level = event.getMobLevel(); - - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(killer.getUniqueId()); - if (qPlayer == null) { - return; - } - - for (Quest quest : super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(super.getType())) { - if (!TaskUtils.validateWorld(killer.getWorld().getName(), task)) continue; - - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - if (taskProgress.isCompleted()) { - continue; - } - - String configName = (String) task.getConfigValue("name"); - int minMobLevel = (int) task.getConfigValue("min-level", -1); - int requiredLevel = (int) task.getConfigValue("level", -1); - - if (!mobName.equals(configName) || level < minMobLevel) { - return; - } - - if (requiredLevel != -1 && level != requiredLevel) { - return; - } - - int mobKillsNeeded = (int) task.getConfigValue("amount"); - - int progressKills; - if (taskProgress.getProgress() == null) { - progressKills = 0; - } else { - progressKills = (int) taskProgress.getProgress(); - } - - taskProgress.setProgress(progressKills + 1); - - if (((int) taskProgress.getProgress()) >= mobKillsNeeded) { - taskProgress.setCompleted(true); - } - } - } - } - } - -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/PlaceholderAPIEvaluateTaskType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/PlaceholderAPIEvaluateTaskType.java deleted file mode 100644 index 137844d5..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/PlaceholderAPIEvaluateTaskType.java +++ /dev/null @@ -1,162 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type.dependent; - -import com.leonardobishop.quests.Quests; -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.ConfigValue; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import me.clip.placeholderapi.PlaceholderAPI; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.scheduler.BukkitRunnable; -import org.bukkit.scheduler.BukkitTask; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public final class PlaceholderAPIEvaluateTaskType extends TaskType { - - private final Quests plugin; - private BukkitTask poll; - private List creatorConfigValues = new ArrayList<>(); - - public PlaceholderAPIEvaluateTaskType(Quests plugin) { - super("placeholderapi_evaluate", TaskUtils.TASK_ATTRIBUTION_STRING, "Evaluate the result of a placeholder"); - this.plugin = plugin; - this.creatorConfigValues.add(new ConfigValue("placeholder", true, "The placeholder string (including %%).")); - this.creatorConfigValues.add(new ConfigValue("evaluates", true, "What it should evaluate to be marked as complete.")); - this.creatorConfigValues.add(new ConfigValue("operator", false, "Comparison method.")); - } - - @Override - public List detectProblemsInConfig(String root, HashMap config) { - ArrayList problems = new ArrayList<>(); - TaskUtils.configValidateExists(root + ".placeholder", config.get("placeholder"), problems, "placeholder", super.getType()); - boolean evalExists = TaskUtils.configValidateExists(root + ".evaluates", config.get("evaluates"), problems, "evaluates", super.getType()); - - if (config.containsKey("operator")) { - String operatorStr = (String) config.get("operator"); - Operator operator = null; - try { - operator = Operator.valueOf(operatorStr); - } catch (IllegalArgumentException ex) { - problems.add(new QuestsConfigLoader.ConfigProblem(QuestsConfigLoader.ConfigProblemType.WARNING, - "Operator '" + operatorStr + "' does not exist.", root + ".operator")); - } - if (operator != null && evalExists) { - String evalStr = String.valueOf(config.get("evaluates")); - try { - Double.parseDouble(evalStr); - } catch (IllegalArgumentException ex) { - problems.add(new QuestsConfigLoader.ConfigProblem(QuestsConfigLoader.ConfigProblemType.WARNING, - "Numeric operator specified, but placeholder evaluation '" + evalStr + "' is not numeric.", root + ".evaluates")); - } - } - } - return problems; - } - - @Override - public void onReady() { - this.poll = new BukkitRunnable() { - @Override - public void run() { - for (Player player : Bukkit.getOnlinePlayers()) { - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(player.getUniqueId()); - if (qPlayer == null) { - continue; - } - - for (Quest quest : PlaceholderAPIEvaluateTaskType.super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - for (Task task : quest.getTasksOfType(PlaceholderAPIEvaluateTaskType.super.getType())) { - if (!TaskUtils.validateWorld(player, task)) continue; - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - if (taskProgress.isCompleted()) { - continue; - } - String placeholder = (String) task.getConfigValue("placeholder"); - String evaluates = String.valueOf(task.getConfigValue("evaluates")); - String configOperator = (String) task.getConfigValue("operator"); - Operator operator = null; - if (configOperator != null) { - try { - operator = Operator.valueOf(configOperator); - } catch (IllegalArgumentException ignored) { } - } - if (placeholder != null && evaluates != null) { - double numericEvaluates = 0; - if (operator != null) { - try { - numericEvaluates = Double.parseDouble(evaluates); - } catch (NumberFormatException ex) { - continue; - } - } - - String evaluated = PlaceholderAPI.setPlaceholders(player, placeholder); - if (operator == null && evaluated.equals(evaluates)) { - taskProgress.setCompleted(true); - } else if (operator != null) { - double numericEvaluated; - try { - numericEvaluated = Double.parseDouble(evaluated); - } catch (NumberFormatException ex) { - continue; - } - switch (operator) { - case GREATER_THAN: - if (numericEvaluated > numericEvaluates) - taskProgress.setCompleted(true); - continue; - case LESS_THAN: - if (numericEvaluated < numericEvaluates) - taskProgress.setCompleted(true); - continue; - case GREATER_THAN_OR_EQUAL_TO: - if (numericEvaluated >= numericEvaluates) - taskProgress.setCompleted(true); - continue; - case LESS_THAN_OR_EQUAL_TO: - if (numericEvaluated <= numericEvaluates) - taskProgress.setCompleted(true); - continue; - } - } - } - - } - } - } - } - } - }.runTaskTimer(plugin, 30L, 30L); - } - - @Override - public void onDisable() { - if (this.poll != null) { - this.poll.cancel(); - } - } - - @Override - public List getCreatorConfigValues() { - return creatorConfigValues; - } - - enum Operator { - GREATER_THAN, - LESS_THAN, - GREATER_THAN_OR_EQUAL_TO, - LESS_THAN_OR_EQUAL_TO; - } -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/ShopGUIPlusBuyCertainTaskType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/ShopGUIPlusBuyCertainTaskType.java deleted file mode 100644 index 664c0ab6..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/ShopGUIPlusBuyCertainTaskType.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type.dependent; - -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import net.brcdev.shopgui.event.ShopPreTransactionEvent; -import net.brcdev.shopgui.shop.ShopManager; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public class ShopGUIPlusBuyCertainTaskType extends TaskType { - - public ShopGUIPlusBuyCertainTaskType() { - super("shopguiplus_buycertain", TaskUtils.TASK_ATTRIBUTION_STRING, "Purchase a given item from a ShopGUI+ shop"); - } - - @Override - public List detectProblemsInConfig(String root, HashMap config) { - ArrayList problems = new ArrayList<>(); - if (TaskUtils.configValidateExists(root + ".amount", config.get("amount"), problems, "amount", super.getType())) - TaskUtils.configValidateInt(root + ".amount", config.get("amount"), problems, false, false, "amount"); - TaskUtils.configValidateExists(root + ".id", config.get("id"), problems, "id", super.getType()); - return problems; - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMobKill(ShopPreTransactionEvent event) { - if (event.getShopAction() != ShopManager.ShopAction.BUY) return; - - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(event.getPlayer().getUniqueId()); - if (qPlayer == null) { - return; - } - - for (Quest quest : super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(super.getType())) { - if (!TaskUtils.validateWorld(event.getPlayer().getWorld().getName(), task)) continue; - - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - if (taskProgress.isCompleted()) { - continue; - } - - String configName = (String) task.getConfigValue("id"); - - if (!event.getShopItem().getId().equals(configName)) { - return; - } - - int amountNeeded = (int) task.getConfigValue("amount"); - - int progressAmount; - if (taskProgress.getProgress() == null) { - progressAmount = 0; - } else { - progressAmount = (int) taskProgress.getProgress(); - } - - taskProgress.setProgress(progressAmount + event.getAmount()); - - if (((int) taskProgress.getProgress()) >= amountNeeded) { - taskProgress.setCompleted(true); - } - } - } - } - } -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/ShopGUIPlusSellCertainTaskType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/ShopGUIPlusSellCertainTaskType.java deleted file mode 100644 index 441c306d..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/ShopGUIPlusSellCertainTaskType.java +++ /dev/null @@ -1,82 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type.dependent; - -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import net.brcdev.shopgui.event.ShopPreTransactionEvent; -import net.brcdev.shopgui.shop.ShopManager; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public class ShopGUIPlusSellCertainTaskType extends TaskType { - - public ShopGUIPlusSellCertainTaskType() { - super("shopguiplus_sellcertain", TaskUtils.TASK_ATTRIBUTION_STRING, "Sell a given item from to a ShopGUI+ shop"); - } - - @Override - public List detectProblemsInConfig(String root, HashMap config) { - ArrayList problems = new ArrayList<>(); - if (TaskUtils.configValidateExists(root + ".amount", config.get("amount"), problems, "amount", super.getType())) - TaskUtils.configValidateInt(root + ".amount", config.get("amount"), problems, false, false, "amount"); - TaskUtils.configValidateExists(root + ".id", config.get("id"), problems, "id", super.getType()); - return problems; - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onMobKill(ShopPreTransactionEvent event) { - if (event.getShopAction() != ShopManager.ShopAction.SELL || event.getShopAction() != ShopManager.ShopAction.SELL_ALL) return; - - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(event.getPlayer().getUniqueId()); - if (qPlayer == null) { - return; - } - - for (Quest quest : super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(super.getType())) { - if (!TaskUtils.validateWorld(event.getPlayer().getWorld().getName(), task)) continue; - - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - if (taskProgress.isCompleted()) { - continue; - } - - String configName = (String) task.getConfigValue("id"); - - if (!event.getShopItem().getId().equals(configName)) { - return; - } - - int amountNeeded = (int) task.getConfigValue("amount"); - - int progressAmount; - if (taskProgress.getProgress() == null) { - progressAmount = 0; - } else { - progressAmount = (int) taskProgress.getProgress(); - } - - taskProgress.setProgress(progressAmount + event.getAmount()); - - if (((int) taskProgress.getProgress()) >= amountNeeded) { - taskProgress.setCompleted(true); - } - } - } - } - } -} diff --git a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/uSkyBlockLevelType.java b/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/uSkyBlockLevelType.java deleted file mode 100644 index a88ca6dc..00000000 --- a/src/main/java/com/leonardobishop/quests/quest/tasktype/type/dependent/uSkyBlockLevelType.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.leonardobishop.quests.quest.tasktype.type.dependent; - -import com.leonardobishop.quests.util.QuestsConfigLoader; -import com.leonardobishop.quests.api.QuestsAPI; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.ConfigValue; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import com.leonardobishop.quests.quest.tasktype.TaskUtils; -import org.bukkit.event.EventHandler; -import org.bukkit.event.EventPriority; -import us.talabrek.ultimateskyblock.api.event.uSkyBlockScoreChangedEvent; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; - -public final class uSkyBlockLevelType extends TaskType { - - private List creatorConfigValues = new ArrayList<>(); - - public uSkyBlockLevelType() { - super("uskyblock_level", TaskUtils.TASK_ATTRIBUTION_STRING, "Reach a certain island level for uSkyBlock."); - this.creatorConfigValues.add(new ConfigValue("level", true, "Minimum island level needed.")); - } - - @Override - public List detectProblemsInConfig(String root, HashMap config) { - ArrayList problems = new ArrayList<>(); - if (TaskUtils.configValidateExists(root + ".level", config.get("level"), problems, "level", super.getType())) - TaskUtils.configValidateInt(root + ".level", config.get("level"), problems, false, false, "level"); - return problems; - } - - - @Override - public List getCreatorConfigValues() { - return creatorConfigValues; - } - - @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) - public void onIslandLevel(uSkyBlockScoreChangedEvent event) { - QPlayer qPlayer = QuestsAPI.getPlayerManager().getPlayer(event.getPlayer().getUniqueId()); - if (qPlayer == null) { - return; - } - - for (Quest quest : super.getRegisteredQuests()) { - if (qPlayer.hasStartedQuest(quest)) { - QuestProgress questProgress = qPlayer.getQuestProgressFile().getQuestProgress(quest); - - for (Task task : quest.getTasksOfType(super.getType())) { - TaskProgress taskProgress = questProgress.getTaskProgress(task.getId()); - - if (taskProgress.isCompleted()) { - continue; - } - - double islandLevelNeeded = (double) (int) task.getConfigValue("level"); - - taskProgress.setProgress(event.getScore().getScore()); - - if (((double) taskProgress.getProgress()) >= islandLevelNeeded) { - taskProgress.setCompleted(true); - } - } - } - } - } - -} diff --git a/src/main/java/com/leonardobishop/quests/storage/MySqlStorageProvider.java b/src/main/java/com/leonardobishop/quests/storage/MySqlStorageProvider.java deleted file mode 100644 index 02692919..00000000 --- a/src/main/java/com/leonardobishop/quests/storage/MySqlStorageProvider.java +++ /dev/null @@ -1,278 +0,0 @@ -package com.leonardobishop.quests.storage; - -import com.leonardobishop.quests.Quests; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.QuestProgressFile; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.util.Options; -import com.zaxxer.hikari.HikariConfig; -import com.zaxxer.hikari.HikariDataSource; -import org.bukkit.configuration.ConfigurationSection; -import org.bukkit.configuration.file.YamlConfiguration; - -import java.sql.Connection; -import java.sql.PreparedStatement; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.function.Function; - -public class MySqlStorageProvider implements StorageProvider { - - private static final String CREATE_TABLE_QUEST_PROGRESS = - "CREATE TABLE IF NOT EXISTS `{prefix}quest_progress` (" + - " `uuid` VARCHAR(36) NOT NULL," + - " `quest_id` VARCHAR(50) NOT NULL," + - " `started` BOOL NOT NULL," + - " `completed` BOOL NOT NULL," + - " `completed_before` BOOL NOT NULL," + - " `completion_date` BIGINT NOT NULL," + - " PRIMARY KEY (`uuid`, `quest_id`));"; - private static final String CREATE_TABLE_TASK_PROGRESS = - "CREATE TABLE IF NOT EXISTS `{prefix}task_progress` (" + - " `uuid` VARCHAR(36) NOT NULL," + - " `quest_id` VARCHAR(50) NOT NULL," + - " `task_id` VARCHAR(50) NOT NULL," + - " `completed` BOOL NOT NULL," + - " `progress` VARCHAR(64) NULL," + - " `data_type` VARCHAR(10) NULL," + - " PRIMARY KEY (`uuid`, `quest_id`, `task_id`));"; - private static final String SELECT_PLAYER_QUEST_PROGRESS = - "SELECT quest_id, started, completed, completed_before, completion_date FROM `{prefix}quest_progress` WHERE uuid=?;"; - private static final String SELECT_PLAYER_TASK_PROGRESS = - "SELECT quest_id, task_id, completed, progress, data_type FROM `{prefix}task_progress` WHERE uuid=?;"; - private static final String SELECT_KNOWN_PLAYER_QUEST_PROGRESS = - "SELECT quest_id FROM `{prefix}quest_progress` WHERE uuid=?;"; - private static final String SELECT_KNOWN_PLAYER_TASK_PROGRESS = - "SELECT quest_id, task_id FROM `{prefix}task_progress` WHERE uuid=?;"; - private static final String WRITE_PLAYER_QUEST_PROGRESS = - "INSERT INTO `{prefix}quest_progress` (uuid, quest_id, started, completed, completed_before, completion_date) VALUES (?,?,?,?,?,?) ON DUPLICATE KEY UPDATE started=?, completed=?, completed_before=?, completion_date=?"; - private static final String WRITE_PLAYER_TASK_PROGRESS = - "INSERT INTO `{prefix}task_progress` (uuid, quest_id, task_id, completed, progress, data_type) VALUES (?,?,?,?,?,?) ON DUPLICATE KEY UPDATE completed=?, progress=?, data_type=?"; - - private final ConfigurationSection configuration; - private final Quests plugin; - private HikariDataSource hikari; - private String prefix; - private Function statementProcessor; - private boolean fault; - - public MySqlStorageProvider(Quests plugin, ConfigurationSection configuration) { - this.plugin = plugin; - if (configuration == null) { - configuration = new YamlConfiguration(); - } - this.configuration = configuration; - } - - @Override - public void init() { - String address = configuration.getString("network.address", "localhost:3306"); - String database = configuration.getString("network.database", "minecraft"); - String url = "jdbc:mysql://" + address + "/" + database; - - HikariConfig config = new HikariConfig(); - config.setPoolName("quests-hikari"); - - config.setUsername(configuration.getString("network.username", "root")); - config.setPassword(configuration.getString("network.password", "")); - config.setJdbcUrl(url); - config.setMaximumPoolSize(configuration.getInt("connection-pool-settings.maximum-pool-size", 8)); - config.setMinimumIdle(configuration.getInt("connection-pool-settings.minimum-idle", 8)); - config.setMaxLifetime(configuration.getInt("connection-pool-settings.maximum-lifetime", 1800000)); - config.setConnectionTimeout(configuration.getInt("connection-pool-settings.connection-timeout", 5000)); - - config.addDataSourceProperty("cachePrepStmts", true); - config.addDataSourceProperty("prepStmtCacheSize", 250); - config.addDataSourceProperty("prepStmtCacheSqlLimit", 2048); - config.addDataSourceProperty("useServerPrepStmts", true); - config.addDataSourceProperty("useLocalSessionState", true); - config.addDataSourceProperty("rewriteBatchedStatements", true); - config.addDataSourceProperty("cacheResultSetMetadata", true); - config.addDataSourceProperty("cacheServerConfiguration", true); - config.addDataSourceProperty("elideSetAutoCommits", true); - config.addDataSourceProperty("maintainTimeStats", false); - - try { - this.hikari = new HikariDataSource(config); - } catch (Exception e) { - e.printStackTrace(); - fault = true; - } - this.prefix = configuration.getString("database-settings.table-prefix", "quests_"); - this.statementProcessor = s -> s.replace("{prefix}", prefix); - try (Connection connection = hikari.getConnection()) { - try (Statement s = connection.createStatement()) { - plugin.getQuestsLogger().debug("Creating default tables"); - s.addBatch(this.statementProcessor.apply(CREATE_TABLE_QUEST_PROGRESS)); - s.addBatch(this.statementProcessor.apply(CREATE_TABLE_TASK_PROGRESS)); - - s.executeBatch(); - } - } catch (SQLException e) { - e.printStackTrace(); - } - } - - @Override - public void shutdown() { - if (hikari != null) hikari.close(); - } - - @Override - public QuestProgressFile loadProgressFile(UUID uuid) { - if (fault) return null; - QuestProgressFile questProgressFile = new QuestProgressFile(uuid, plugin); - try (Connection connection = hikari.getConnection()) { - plugin.getQuestsLogger().debug("Querying player " + uuid); - Map questProgressMap = new HashMap<>(); - try (PreparedStatement ps = connection.prepareStatement(this.statementProcessor.apply(SELECT_PLAYER_QUEST_PROGRESS))) { - ps.setString(1, uuid.toString()); - - try (ResultSet rs = ps.executeQuery()) { - while (rs.next()) { - String questId = rs.getString(1); - boolean started = rs.getBoolean(2); - boolean completed = rs.getBoolean(3); - boolean completedBefore = rs.getBoolean(4); - long completionDate = rs.getLong(5); - - QuestProgress questProgress = new QuestProgress(plugin, questId, completed, completedBefore, completionDate, uuid, started); - questProgressMap.put(questId, questProgress); - } - } - } - try (PreparedStatement ps = connection.prepareStatement(this.statementProcessor.apply(SELECT_PLAYER_TASK_PROGRESS))) { - ps.setString(1, uuid.toString()); - - try (ResultSet rs = ps.executeQuery()) { - while (rs.next()) { - String questId = rs.getString(1); - String taskId = rs.getString(2); - boolean completed = rs.getBoolean(3); - String encodedProgress = rs.getString(4); - String type = rs.getString(5); - Object progress; - try { - if (type == null) { - progress = null; - } else if (type.equals("double")) { - progress = Double.valueOf(encodedProgress); - } else if (type.equals("float")) { - progress = Float.valueOf(encodedProgress); - } else if (type.equals("int")) { - progress = Integer.valueOf(encodedProgress); - } else { - throw new RuntimeException("unknown data type '" + type + "'"); - } - } catch (NumberFormatException ex) { - plugin.getQuestsLogger().warning("Cannot retrieve progress for task '" - + taskId + "' in quest '" + questId + "' for player " + uuid - + " since data is malformed!"); - continue; - } catch (RuntimeException ex) { - if (ex.getMessage().startsWith("unknown data type ")) { - plugin.getQuestsLogger().warning("Cannot retrieve progress for task '" - + taskId + "' in quest '" + questId + "' for player " + uuid - + ": " + ex.getMessage()); - continue; - } else { - throw ex; - } - } - - QuestProgress linkedQuestProgress = questProgressMap.get(questId); - if (linkedQuestProgress == null) continue; // lost quest progress ? - TaskProgress questProgress = new TaskProgress(linkedQuestProgress, taskId, progress, uuid, completed); - linkedQuestProgress.addTaskProgress(questProgress); - } - } - } - for (QuestProgress questProgress : questProgressMap.values()) { - questProgressFile.addQuestProgress(questProgress); - } - } catch (SQLException e) { - plugin.getQuestsLogger().severe("Failed to load player: " + uuid + "!"); - e.printStackTrace(); - return null; - } - return questProgressFile; - } - - @Override - public void saveProgressFile(UUID uuid, QuestProgressFile questProgressFile) { - if (fault) return; - try (Connection connection = hikari.getConnection()) { - try (PreparedStatement writeQuestProgress = connection.prepareStatement(this.statementProcessor.apply(WRITE_PLAYER_QUEST_PROGRESS)); - PreparedStatement writeTaskProgress = connection.prepareStatement(this.statementProcessor.apply(WRITE_PLAYER_TASK_PROGRESS))) { - - List questProgressValues = new ArrayList<>(questProgressFile.getAllQuestProgress()); - for (QuestProgress questProgress : questProgressValues) { - if (!questProgress.isModified()) continue; - - String questId = questProgress.getQuestId(); - writeQuestProgress.setString(1, uuid.toString()); - writeQuestProgress.setString(2, questProgress.getQuestId()); - writeQuestProgress.setBoolean(3, questProgress.isStarted()); - writeQuestProgress.setBoolean(4, questProgress.isCompleted()); - writeQuestProgress.setBoolean(5, questProgress.isCompletedBefore()); - writeQuestProgress.setLong(6, questProgress.getCompletionDate()); - writeQuestProgress.setBoolean(7, questProgress.isStarted()); - writeQuestProgress.setBoolean(8, questProgress.isCompleted()); - writeQuestProgress.setBoolean(9, questProgress.isCompletedBefore()); - writeQuestProgress.setLong(10, questProgress.getCompletionDate()); - writeQuestProgress.addBatch(); - - for (TaskProgress taskProgress : questProgress.getTaskProgress()) { - String taskId = taskProgress.getTaskId(); - - String encodedProgress; - Object progress = taskProgress.getProgress(); - String type; - if (progress == null) { - type = null; - encodedProgress = null; - } else if (progress instanceof Double) { - type = "double"; - encodedProgress = String.valueOf(progress); - } else if (progress instanceof Integer) { - type = "int"; - encodedProgress = String.valueOf(progress); - } else if (progress instanceof Float) { - type = "float"; - encodedProgress = String.valueOf(progress); - } else { - plugin.getQuestsLogger().warning("Cannot store progress for task '" - + taskId + "' in quest '" + questId + "' for player " + uuid - + " since type " + progress.getClass().getName() + " cannot be encoded!"); - continue; - } - writeTaskProgress.setString(1, uuid.toString()); - writeTaskProgress.setString(2, questId); - writeTaskProgress.setString(3, taskProgress.getTaskId()); - writeTaskProgress.setBoolean(4, taskProgress.isCompleted()); - writeTaskProgress.setString(5, encodedProgress); - writeTaskProgress.setString(6, type); - writeTaskProgress.setBoolean(7, taskProgress.isCompleted()); - writeTaskProgress.setString(8, encodedProgress); - writeTaskProgress.setString(9, type); - writeTaskProgress.addBatch(); - } - } - - writeQuestProgress.executeBatch(); - writeTaskProgress.executeBatch(); - } - } catch (SQLException e) { - plugin.getQuestsLogger().severe("Failed to save player: " + uuid + "!"); - e.printStackTrace(); - } - } -} diff --git a/src/main/java/com/leonardobishop/quests/storage/StorageProvider.java b/src/main/java/com/leonardobishop/quests/storage/StorageProvider.java deleted file mode 100644 index f1d00203..00000000 --- a/src/main/java/com/leonardobishop/quests/storage/StorageProvider.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.leonardobishop.quests.storage; - -import com.leonardobishop.quests.player.questprogressfile.QuestProgressFile; - -import java.util.UUID; - -public interface StorageProvider { - - void init(); - void shutdown(); - QuestProgressFile loadProgressFile(UUID uuid); - void saveProgressFile(UUID uuid, QuestProgressFile questProgressFile); - -} diff --git a/src/main/java/com/leonardobishop/quests/storage/YamlStorageProvider.java b/src/main/java/com/leonardobishop/quests/storage/YamlStorageProvider.java deleted file mode 100644 index 8ba30a4e..00000000 --- a/src/main/java/com/leonardobishop/quests/storage/YamlStorageProvider.java +++ /dev/null @@ -1,137 +0,0 @@ -package com.leonardobishop.quests.storage; - -import com.leonardobishop.quests.Quests; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.QuestProgressFile; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import org.bukkit.configuration.file.YamlConfiguration; - -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.locks.ReentrantLock; - -public class YamlStorageProvider implements StorageProvider { - - private final Map locks = new ConcurrentHashMap<>(); - private Quests plugin; - - public YamlStorageProvider(Quests plugin) { - this.plugin = plugin; - } - - private ReentrantLock lock(UUID uuid) { - locks.putIfAbsent(uuid, new ReentrantLock()); - ReentrantLock lock = locks.get(uuid); - lock.lock(); - return lock; - } - - @Override - public void init() { - File directory = new File(plugin.getDataFolder() + File.separator + "playerdata"); - directory.mkdirs(); - } - - @Override - public void shutdown() { - // no impl - } - - public QuestProgressFile loadProgressFile(UUID uuid) { - ReentrantLock lock = lock(uuid); - QuestProgressFile questProgressFile = new QuestProgressFile(uuid, plugin); - try { - File directory = new File(plugin.getDataFolder() + File.separator + "playerdata"); - if (directory.exists() && directory.isDirectory()) { - File file = new File(plugin.getDataFolder() + File.separator + "playerdata" + File.separator + uuid.toString() + ".yml"); - if (file.exists()) { - YamlConfiguration data = YamlConfiguration.loadConfiguration(file); - plugin.getQuestsLogger().debug("Player " + uuid + " has a valid quest progress file."); - if (data.isConfigurationSection("quest-progress")) { //Same job as "isSet" + it checks if is CfgSection - for (String id : data.getConfigurationSection("quest-progress").getKeys(false)) { - boolean started = data.getBoolean("quest-progress." + id + ".started"); - boolean completed = data.getBoolean("quest-progress." + id + ".completed"); - boolean completedBefore = data.getBoolean("quest-progress." + id + ".completed-before"); - long completionDate = data.getLong("quest-progress." + id + ".completion-date"); - - QuestProgress questProgress = new QuestProgress(plugin, id, completed, completedBefore, completionDate, uuid, started, true); - - if (data.isConfigurationSection("quest-progress." + id + ".task-progress")) { - for (String taskid : data.getConfigurationSection("quest-progress." + id + ".task-progress").getKeys(false)) { - boolean taskCompleted = data.getBoolean("quest-progress." + id + ".task-progress." + taskid + ".completed"); - Object taskProgression = data.get("quest-progress." + id + ".task-progress." + taskid + ".progress"); - - TaskProgress taskProgress = new TaskProgress(questProgress, taskid, taskProgression, uuid, taskCompleted, false); - questProgress.addTaskProgress(taskProgress); - } - } - - questProgressFile.addQuestProgress(questProgress); - } - } - } else { - plugin.getQuestsLogger().debug("Player " + uuid + " does not have a quest progress file."); - } - } - } catch (Exception ex) { - plugin.getQuestsLogger().severe("Failed to load player: " + uuid + "! This WILL cause errors."); - ex.printStackTrace(); - // fuck - } finally { - lock.unlock(); - } - - return questProgressFile; - } - - public void saveProgressFile(UUID uuid, QuestProgressFile questProgressFile) { - ReentrantLock lock = lock(uuid); - try { - List questProgressValues = new ArrayList<>(questProgressFile.getAllQuestProgress()); - File directory = new File(plugin.getDataFolder() + File.separator + "playerdata"); - if (!directory.exists() && !directory.isDirectory()) { - directory.mkdirs(); - } - - File file = new File(plugin.getDataFolder() + File.separator + "playerdata" + File.separator + uuid.toString() + ".yml"); - if (!file.exists()) { - try { - file.createNewFile(); - } catch (IOException e) { - e.printStackTrace(); - } - } - - YamlConfiguration data = YamlConfiguration.loadConfiguration(file); - for (QuestProgress questProgress : questProgressValues) { - if (!questProgress.isModified()) continue; - data.set("quest-progress." + questProgress.getQuestId() + ".started", questProgress.isStarted()); - data.set("quest-progress." + questProgress.getQuestId() + ".completed", questProgress.isCompleted()); - data.set("quest-progress." + questProgress.getQuestId() + ".completed-before", questProgress.isCompletedBefore()); - data.set("quest-progress." + questProgress.getQuestId() + ".completion-date", questProgress.getCompletionDate()); - for (TaskProgress taskProgress : questProgress.getTaskProgress()) { - data.set("quest-progress." + questProgress.getQuestId() + ".task-progress." + taskProgress.getTaskId() + ".completed", taskProgress - .isCompleted()); - data.set("quest-progress." + questProgress.getQuestId() + ".task-progress." + taskProgress.getTaskId() + ".progress", taskProgress - .getProgress()); - } - } - - plugin.getQuestsLogger().debug("Writing player " + uuid + " to disk."); - try { - data.save(file); - plugin.getQuestsLogger().debug("Write of player " + uuid + " to disk complete."); - } catch (IOException e) { - plugin.getQuestsLogger().debug("Failed to write player: " + uuid + "!."); - e.printStackTrace(); - } - } finally { - lock.unlock(); - } - } -} diff --git a/src/main/java/com/leonardobishop/quests/updater/Updater.java b/src/main/java/com/leonardobishop/quests/updater/Updater.java deleted file mode 100644 index 6bd28b49..00000000 --- a/src/main/java/com/leonardobishop/quests/updater/Updater.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.leonardobishop.quests.updater; - -import com.leonardobishop.quests.Quests; -import com.leonardobishop.quests.util.Messages; - -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStreamReader; -import java.net.MalformedURLException; -import java.net.URL; -import java.net.URLConnection; -import java.util.concurrent.TimeUnit; - -public class Updater { - - private static final int PROJECT_ID = 23696; - private final String installedVersion; - private final Quests plugin; - private final boolean enabled; - - private String returnedVersion; - private URL api; - private boolean updateReady; - private long lastCheck; - - public Updater(Quests plugin, boolean enabled) { - this.plugin = plugin; - this.installedVersion = plugin.getDescription().getVersion(); - this.enabled = enabled; - try { - this.api = new URL(getApiUrl()); - } catch (MalformedURLException ignored) { } - } - - public String getUpdateLink() { - return "https://www.spigotmc.org/resources/" + PROJECT_ID; - } - - public String getApiUrl() { - return "https://api.spigotmc.org/legacy/update.php?resource=" + PROJECT_ID; - } - - public void check() { - if (!enabled) { - return; - } - // stop users from spamming the command and making needless requests - if (lastCheck != 0 && TimeUnit.MINUTES.convert(System.currentTimeMillis() - lastCheck, TimeUnit.MILLISECONDS) < 10) { - return; - } - try { - lastCheck = System.currentTimeMillis(); - URLConnection con = api.openConnection(); - returnedVersion = new BufferedReader(new InputStreamReader(con.getInputStream())).readLine(); - if (!returnedVersion.equals(installedVersion)) { - plugin.getQuestsLogger().info("A new version " + returnedVersion + " was found on Spigot (your version: " + installedVersion + "). Please update me! <3 - Link: " + getUpdateLink()); - updateReady = true; - } else { - updateReady = false; - } - } catch (IOException e) { - plugin.getQuestsLogger().warning("Failed to check for updates. You can check manually at " + getUpdateLink()); - // probably offline - } - } - - public boolean isUpdateReady() { - return updateReady; - } - - public String getMessage() { - return Messages.QUEST_UPDATER.getMessage().replace("{newver}", returnedVersion).replace("{oldver}", installedVersion).replace("{link}", getUpdateLink()); - } -} \ No newline at end of file diff --git a/src/main/java/com/leonardobishop/quests/util/Items.java b/src/main/java/com/leonardobishop/quests/util/Items.java deleted file mode 100644 index be34d72c..00000000 --- a/src/main/java/com/leonardobishop/quests/util/Items.java +++ /dev/null @@ -1,36 +0,0 @@ -package com.leonardobishop.quests.util; - -import com.leonardobishop.quests.Quests; -import org.bukkit.inventory.ItemStack; - -import java.util.HashMap; -import java.util.Map; - -public enum Items { - - BACK_BUTTON("gui.back-button"), - QUEST_LOCKED("gui.quest-locked-display"), - QUEST_COOLDOWN("gui.quest-cooldown-display"), - QUEST_COMPLETED("gui.quest-completed-display"), - QUEST_PERMISSION("gui.quest-permission-display"), - PAGE_PREV("gui.page-prev"), - PAGE_NEXT("gui.page-next"), - PAGE_DESCRIPTION("gui.page-desc"), - NO_STARTED_QUESTS("gui.no-started-quests"), - QUEST_CANCEL_YES("gui.quest-cancel-yes"), - QUEST_CANCEL_NO("gui.quest-cancel-no"), - QUEST_CANCEL_BACKGROUND("gui.quest-cancel-background"); - - private static final Map cachedItemStacks = new HashMap<>(); - - private final String path; - - Items(String path) { - this.path = path; - } - - public ItemStack getItem() { - return new ItemStack(cachedItemStacks.computeIfAbsent(path, s -> Quests.get().getItemStack(path, Quests.get().getConfig()))); - } - -} diff --git a/src/main/java/com/leonardobishop/quests/util/Messages.java b/src/main/java/com/leonardobishop/quests/util/Messages.java deleted file mode 100644 index a86a4144..00000000 --- a/src/main/java/com/leonardobishop/quests/util/Messages.java +++ /dev/null @@ -1,76 +0,0 @@ -package com.leonardobishop.quests.util; - -import com.leonardobishop.quests.Quests; -import org.bukkit.ChatColor; - -public enum Messages { - - TIME_FORMAT("messages.time-format"), - QUEST_START("messages.quest-start"), - QUEST_COMPLETE("messages.quest-complete"), - QUEST_CANCEL("messages.quest-cancel"), - QUEST_TRACK("messages.quest-track"), - QUEST_TRACK_STOP("messages.quest-track-stop"), - QUEST_RANDOM_NONE("messages.quest-random-none"), - QUEST_START_LIMIT("messages.quest-start-limit"), - QUEST_START_DISABLED("messages.quest-start-disabled"), - QUEST_START_LOCKED("messages.quest-start-locked"), - QUEST_START_COOLDOWN("messages.quest-start-cooldown"), - QUEST_START_STARTED("messages.quest-start-started"), - QUEST_START_PERMISSION("messages.quest-start-permission"), - QUEST_CATEGORY_QUEST_PERMISSION("messages.quest-category-quest-permission"), - QUEST_CATEGORY_PERMISSION("messages.quest-category-permission"), - QUEST_CANCEL_NOTSTARTED("messages.quest-cancel-notstarted"), - QUEST_UPDATER("messages.quest-updater"), - COMMAND_DATA_NOT_LOADED("messages.command-data-not-loaded"), - COMMAND_SUB_DOESNTEXIST("messages.command-sub-doesntexist"), - COMMAND_QUEST_START_DOESNTEXIST("messages.command-quest-start-doesntexist"), - COMMAND_QUEST_GENERAL_DOESNTEXIST("messages.command-quest-general-doesntexist"), - COMMAND_QUEST_OPENCATEGORY_ADMIN_SUCCESS("messages.command-quest-opencategory-admin-success"), - COMMAND_QUEST_OPENQUESTS_ADMIN_SUCCESS("messages.command-quest-openquests-admin-success"), - COMMAND_QUEST_ADMIN_PLAYERNOTFOUND("messages.command-quest-admin-playernotfound"), - COMMAND_CATEGORY_OPEN_DOESNTEXIST("messages.command-category-open-doesntexist"), - COMMAND_CATEGORY_OPEN_DISABLED("messages.command-category-open-disabled"), - COMMAND_QUEST_START_ADMIN_SUCCESS("messages.command-quest-start-admin-success"), - COMMAND_TASKVIEW_ADMIN_FAIL("messages.command-taskview-admin-fail"), - COMMAND_QUEST_START_ADMIN_FAIL("messages.command-quest-start-admin-fail"), - TITLE_QUEST_START_TITLE("titles.quest-start.title"), - TITLE_QUEST_START_SUBTITLE("titles.quest-start.subtitle"), - TITLE_QUEST_COMPLETE_TITLE("titles.quest-complete.title"), - TITLE_QUEST_COMPLETE_SUBTITLE("titles.quest-complete.subtitle"), - BETA_REMINDER("messages.beta-reminder"), - COMMAND_QUEST_ADMIN_LOADDATA("messages.command-quest-admin-loaddata"), - COMMAND_QUEST_ADMIN_NODATA("messages.command-quest-admin-nodata"), - COMMAND_QUEST_ADMIN_CLEAN_SUCCESS("messages.command-quest-admin-clean-success"), - COMMAND_QUEST_ADMIN_CLEAN_FAIL("messages.command-quest-admin-clean-fail"), - COMMAND_QUEST_ADMIN_FULLRESET("messages.command-quest-admin-fullreset"), - COMMAND_QUEST_ADMIN_START_FAILLOCKED("messages.command-quest-admin-start-faillocked"), - COMMAND_QUEST_ADMIN_START_FAILCOOLDOWN("messages.command-quest-admin-start-failcooldown"), - COMMAND_QUEST_ADMIN_START_FAILCOMPLETE("messages.command-quest-admin-start-failcomplete"), - COMMAND_QUEST_ADMIN_START_FAILLIMIT("messages.command-quest-admin-start-faillimit"), - COMMAND_QUEST_ADMIN_START_FAILSTARTED("messages.command-quest-admin-start-failstarted"), - COMMAND_QUEST_ADMIN_START_FAILPERMISSION("messages.command-quest-admin-start-failpermission"), - COMMAND_QUEST_ADMIN_START_FAILCATEGORY("messages.command-quest-admin-start-failpermission"), - COMMAND_QUEST_ADMIN_START_FAILCATEGORYPERMISSION("messages.command-quest-admin-start-failcategorypermission"), - COMMAND_QUEST_ADMIN_START_FAILOTHER("messages.command-quest-admin-start-failother"), - COMMAND_QUEST_ADMIN_START_SUCCESS("messages.command-quest-admin-start-success"), - COMMAND_QUEST_ADMIN_CATEGORY_PERMISSION("messages.command-quest-admin-category-permission"), - COMMAND_QUEST_ADMIN_COMPLETE_SUCCESS("messages.command-quest-admin-complete-success"), - COMMAND_QUEST_ADMIN_RESET_SUCCESS("messages.command-quest-admin-reset-success"); - - private final String path; - - Messages(String path) { - this.path = path; - } - - public String getMessage() { - if (Quests.get().getConfig().contains(path)) { - String message = Quests.get().getConfig().getString(path); - if (message != null) { - return ChatColor.translateAlternateColorCodes('&', message); - } - } - return path; - } -} diff --git a/src/main/java/com/leonardobishop/quests/util/Options.java b/src/main/java/com/leonardobishop/quests/util/Options.java deleted file mode 100644 index 0ad0a41d..00000000 --- a/src/main/java/com/leonardobishop/quests/util/Options.java +++ /dev/null @@ -1,93 +0,0 @@ -package com.leonardobishop.quests.util; - -import com.leonardobishop.quests.Quests; -import org.bukkit.ChatColor; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -public enum Options { - - CATEGORIES_ENABLED("options.categories-enabled"), - TRIM_GUI_SIZE("options.trim-gui-size"), - QUESTS_START_LIMIT("options.quest-started-limit"), - TITLES_ENABLED("options.titles-enabled"), - GUI_HIDE_LOCKED("options.gui-hide-locked"), - GUI_HIDE_QUESTS_NOPERMISSION("options.gui-hide-quests-nopermission"), - GUI_HIDE_CATEGORIES_NOPERMISSION("options.gui-hide-categories-nopermission"), - GUI_USE_PLACEHOLDERAPI("options.gui-use-placeholderapi"), - GUITITLE_QUESTS_CATEGORY("options.guinames.quests-category"), - GUITITLE_QUESTS("options.guinames.quests-menu"), - GUITITLE_QUESTS_STARTED("options.guinames.quests-started-menu"), - GUITITLE_DAILY_QUESTS("options.guinames.daily-quests"), - GUITITLE_QUEST_CANCEL("options.guinames.quest-cancel"), - ALLOW_QUEST_CANCEL("options.allow-quest-cancel"), - ALLOW_QUEST_TRACK("options.allow-quest-track"), - VERIFY_QUEST_EXISTS_ON_LOAD("options.verify-quest-exists-on-load"), - TAB_COMPLETE_ENABLED("options.tab-completion.enabled"), - ERROR_CHECKING_OVERRIDE("options.error-checking.override-errors"), - QUEST_AUTOSTART("options.quest-autostart"), - QUEST_AUTOTRACK("options.quest-autotrack"), - GLOBAL_TASK_CONFIGURATION_OVERRIDE("options.global-task-configuration-override"), - GLOBAL_QUEST_DISPLAY_CONFIGURATION_OVERRIDE("options.global-quest-display-configuration-override"), - GLOBAL_QUEST_DISPLAY_LORE_APPEND_NORMAL("global-quest-display.lore.append-normal"), - GLOBAL_QUEST_DISPLAY_LORE_APPEND_NOT_STARTED("global-quest-display.lore.append-not-started"), - GLOBAL_QUEST_DISPLAY_LORE_APPEND_STARTED("global-quest-display.lore.append-started"), - GLOBAL_QUEST_DISPLAY_LORE_APPEND_TRACKED("global-quest-display.lore.append-tracked"); - - private static final Map cachedBooleans = new ConcurrentHashMap<>(); - - private final String path; - - Options(String path) { - this.path = path; - } - - public int getIntValue() { - return Quests.get().getConfig().getInt(path); - } - - public int getIntValue(int def) { - return Quests.get().getConfig().getInt(path, def); - } - - public String getStringValue() { - return Quests.get().getConfig().getString(path); - } - - public String getStringValue(String def) { - return Quests.get().getConfig().getString(path, def); - } - - public boolean getBooleanValue() { - return cachedBooleans.computeIfAbsent(path, s -> Quests.get().getConfig().getBoolean(path)); - } - - public boolean getBooleanValue(boolean def) { - return Quests.get().getConfig().getBoolean(path, def); - } - - public List getStringListValue() { - return Quests.get().getConfig().getStringList(path); - } - - public static String color(String s) { - return ChatColor.translateAlternateColorCodes('&', s); - } - - public static List color(List s) { - if (s == null || s.size() == 0) return s; - - List colored = new ArrayList<>(); - for (String line : s) { - colored.add(ChatColor.translateAlternateColorCodes('&', line)); - } - return colored; - } - - public static void invalidateCaches() { - cachedBooleans.clear(); - } -} diff --git a/src/main/java/com/leonardobishop/quests/util/QuestCompleter.java b/src/main/java/com/leonardobishop/quests/util/QuestCompleter.java deleted file mode 100644 index b6b942fd..00000000 --- a/src/main/java/com/leonardobishop/quests/util/QuestCompleter.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.leonardobishop.quests.util; - -import com.leonardobishop.quests.Quests; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgress; -import com.leonardobishop.quests.player.questprogressfile.QuestProgressFile; -import com.leonardobishop.quests.player.questprogressfile.TaskProgress; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; - -import java.util.LinkedList; -import java.util.Queue; - -public class QuestCompleter implements Runnable { - - private final Queue completionQueue = new LinkedList<>(); - private final Queue fullCheckQueue = new LinkedList<>(); - private final Quests plugin; - - public QuestCompleter(Quests plugin) { - this.plugin = plugin; - } - - @Override - public void run() { - this.processCompletionQueue(); - this.processFullCheckQueue(); - } - - private void processCompletionQueue() { - QuestProgress questProgress = completionQueue.poll(); - if (questProgress == null) return; - - Player player = Bukkit.getPlayer(questProgress.getPlayer()); - if (player != null && player.isOnline()) { - QPlayer qPlayer = plugin.getPlayerManager().getPlayer(player.getUniqueId()); - if (qPlayer == null) return; - - Quest quest = plugin.getQuestManager().getQuestById(questProgress.getQuestId()); - - if (!qPlayer.hasStartedQuest(quest)) return; - - if (checkComplete(quest, questProgress)) { - qPlayer.completeQuest(quest); - } - } - } - - private void processFullCheckQueue() { - QuestProgressFile questProgressFile = fullCheckQueue.poll(); - if (questProgressFile == null) return; - - Player player = Bukkit.getPlayer(questProgressFile.getPlayerUUID()); - if (player != null && player.isOnline()) { - QPlayer qPlayer = plugin.getPlayerManager().getPlayer(player.getUniqueId()); - if (qPlayer == null) return; - for (QuestProgress questProgress : questProgressFile.getAllQuestProgress()) { - Quest quest = plugin.getQuestManager().getQuestById(questProgress.getQuestId()); - if (quest == null) continue; - if (!qPlayer.hasStartedQuest(quest)) continue; - - boolean complete = true; - for (Task task : quest.getTasks()) { - TaskProgress taskProgress; - if ((taskProgress = questProgress.getTaskProgress(task.getId())) == null || !taskProgress.isCompleted()) { - complete = false; - break; - } - } - if (complete) { - qPlayer.completeQuest(quest); - } - } - } - } - - private boolean checkComplete(Quest quest, QuestProgress questProgress) { - boolean complete = true; - for (Task task : quest.getTasks()) { - TaskProgress taskProgress; - if ((taskProgress = questProgress.getTaskProgress(task.getId())) == null || !taskProgress.isCompleted()) { - complete = false; - break; - } - } - - return complete; - } - - public void queueSingular(QuestProgress questProgress) { - completionQueue.add(questProgress); - } - - public void queueFullCheck(QuestProgressFile questProgressFile) { - fullCheckQueue.add(questProgressFile); - } -} diff --git a/src/main/java/com/leonardobishop/quests/util/QuestMode.java b/src/main/java/com/leonardobishop/quests/util/QuestMode.java deleted file mode 100644 index e942d909..00000000 --- a/src/main/java/com/leonardobishop/quests/util/QuestMode.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.leonardobishop.quests.util; - -public enum QuestMode { - - NORMAL, - DAILY; - -} diff --git a/src/main/java/com/leonardobishop/quests/util/QuestsAutosaveRunnable.java b/src/main/java/com/leonardobishop/quests/util/QuestsAutosaveRunnable.java deleted file mode 100644 index dbe0b3a9..00000000 --- a/src/main/java/com/leonardobishop/quests/util/QuestsAutosaveRunnable.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.leonardobishop.quests.util; - -import com.leonardobishop.quests.Quests; -import com.leonardobishop.quests.player.QPlayer; -import com.leonardobishop.quests.player.questprogressfile.QuestProgressFile; -import com.leonardobishop.quests.util.Options; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.scheduler.BukkitRunnable; - -import java.util.LinkedList; -import java.util.Queue; -import java.util.UUID; - -public class QuestsAutosaveRunnable extends BukkitRunnable { - - private final Queue queue = new LinkedList<>(); - private final Quests plugin; - - public QuestsAutosaveRunnable(Quests plugin) { - for (Player player : Bukkit.getOnlinePlayers()) { - queue.add(player.getUniqueId()); - } - - this.plugin = plugin; - - this.runTaskTimer(plugin, 2L, 2L); - } - - @Override - public void run() { - UUID player = queue.poll(); - if (player == null) { - try { - super.cancel(); - } catch (Exception ignored) {} - return; - } - - if (Bukkit.getPlayer(player) != null) { - plugin.getPlayerManager().savePlayer(player); - } - } - -} diff --git a/src/main/java/com/leonardobishop/quests/util/QuestsConfigLoader.java b/src/main/java/com/leonardobishop/quests/util/QuestsConfigLoader.java deleted file mode 100644 index 9c5215bc..00000000 --- a/src/main/java/com/leonardobishop/quests/util/QuestsConfigLoader.java +++ /dev/null @@ -1,454 +0,0 @@ -package com.leonardobishop.quests.util; - -import com.leonardobishop.quests.Quests; -import com.leonardobishop.quests.hook.itemgetter.ItemGetter; -import com.leonardobishop.quests.menu.QItemStack; -import com.leonardobishop.quests.quest.Category; -import com.leonardobishop.quests.quest.Quest; -import com.leonardobishop.quests.quest.Task; -import com.leonardobishop.quests.quest.tasktype.TaskType; -import org.apache.commons.lang.StringUtils; -import org.bukkit.ChatColor; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.configuration.file.YamlConfiguration; -import org.bukkit.inventory.ItemStack; - -import java.io.File; -import java.io.IOException; -import java.net.URI; -import java.nio.file.FileVisitResult; -import java.nio.file.FileVisitor; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.SimpleFileVisitor; -import java.nio.file.attribute.BasicFileAttributes; -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class QuestsConfigLoader { - - private final Map> filesWithProblems = new HashMap<>(); - private final Quests plugin; - private int problemsCount; - - public QuestsConfigLoader(Quests plugin) { - this.plugin = plugin; - } - - /** - * Loads and parses config into memory including the quests folder. - */ - public void loadConfig() { - plugin.reloadConfig(); - Options.invalidateCaches(); - filesWithProblems.clear(); - plugin.setBrokenConfig(false); - - // test CONFIG file integrity - try { - YamlConfiguration config = new YamlConfiguration(); - config.load(new File(plugin.getDataFolder() + File.separator + "config.yml")); - } catch (Exception ex) { - filesWithProblems.put("

config.yml", Collections.singletonList(new ConfigProblem(ConfigProblemType.ERROR, ConfigProblemDescriptions.MALFORMED_YAML.getDescription()))); - plugin.setBrokenConfig(true); - } - - - if (!plugin.isBrokenConfig()) { - HashMap> globalTaskConfig = new HashMap<>(); - for (String id : plugin.getConfig().getConfigurationSection("categories").getKeys(false)) { - ItemStack displayItem = plugin.getItemStack("categories." + id + ".display", plugin.getConfig()); - boolean permissionRequired = plugin.getConfig().getBoolean("categories." + id + ".permission-required", false); - - Category category = new Category(id, displayItem, permissionRequired); - plugin.getQuestManager().registerCategory(category); - } - plugin.getQuestsLogger().setServerLoggingLevel(QuestsLogger.LoggingLevel.fromNumber(plugin.getConfig().getInt("options.verbose-logging-level", 2))); - - HashMap pathToQuest = new HashMap<>(); - - if (plugin.getConfig().isConfigurationSection("global-task-configuration.types")) { - for (String type : plugin.getConfig().getConfigurationSection("global-task-configuration.types").getKeys(false)) { - HashMap configValues = new HashMap<>(); - for (String key : plugin.getConfig().getConfigurationSection("global-task-configuration.types." + type).getKeys(false)) { - configValues.put(key, plugin.getConfig().get("global-task-configuration.types." + type + "." + key)); - } - globalTaskConfig.putIfAbsent(type, configValues); - } - } - - try { - plugin.setQuestMode(QuestMode.valueOf(plugin.getConfig().getString("quest-mode.mode", "NORMAL").toUpperCase())); - } catch (IllegalArgumentException ex) { - plugin.setQuestMode(QuestMode.NORMAL); - } - - FileVisitor fileVisitor = new SimpleFileVisitor() { - final URI questsRoot = Paths.get(plugin.getDataFolder() + File.separator + "quests").toUri(); - - @Override - public FileVisitResult visitFile(Path path, BasicFileAttributes attributes) { - try { - File questFile = new File(path.toUri()); - URI relativeLocation = questsRoot.relativize(path.toUri()); - - if (!questFile.getName().toLowerCase().endsWith(".yml")) return FileVisitResult.CONTINUE; - - YamlConfiguration config = new YamlConfiguration(); - // test QUEST file integrity - try { - config.load(questFile); - } catch (Exception ex) { - filesWithProblems.put(relativeLocation.getPath(), Collections.singletonList(new ConfigProblem(ConfigProblemType.ERROR, ConfigProblemDescriptions.MALFORMED_YAML.getDescription()))); - return FileVisitResult.CONTINUE; - } - - String id = questFile.getName().replace(".yml", ""); - - List configProblems = new ArrayList<>(); - - if (!StringUtils.isAlphanumeric(id)) { - configProblems.add(new ConfigProblem(ConfigProblemType.ERROR, ConfigProblemDescriptions.INVALID_QUEST_ID.getDescription(id))); - } - - // CHECK EVERYTHING WRONG WITH THE QUEST FILE BEFORE ACTUALLY LOADING THE QUEST - - if (!config.isConfigurationSection("tasks")) { - configProblems.add(new ConfigProblem(ConfigProblemType.ERROR, ConfigProblemDescriptions.NO_TASKS.getDescription(), "tasks")); - } else { //continue - int validTasks = 0; - for (String taskId : config.getConfigurationSection("tasks").getKeys(false)) { - boolean isValid = true; - String taskRoot = "tasks." + taskId; - String taskType = config.getString(taskRoot + ".type"); - - if (!config.isConfigurationSection(taskRoot)) { - configProblems.add(new ConfigProblem(ConfigProblemType.WARNING, ConfigProblemDescriptions.TASK_MALFORMED_NOT_SECTION.getDescription(taskId), taskRoot)); - continue; - } - - if (taskType == null) { - configProblems.add(new ConfigProblem(ConfigProblemType.WARNING, ConfigProblemDescriptions.NO_TASK_TYPE.getDescription(), taskRoot)); - continue; - } - - // check the tasks - TaskType t = plugin.getTaskTypeManager().getTaskType(taskType); - if (t != null) { - HashMap configValues = new HashMap<>(); - for (String key : config.getConfigurationSection(taskRoot).getKeys(false)) { - configValues.put(key, config.get(taskRoot + "." + key)); - } - - configProblems.addAll(t.detectProblemsInConfig(taskRoot, configValues)); - } else { - configProblems.add(new ConfigProblem(ConfigProblemType.WARNING, ConfigProblemDescriptions.UNKNOWN_TASK_TYPE.getDescription(taskType), taskRoot)); - isValid = false; - } - - if (isValid) { - validTasks++; - } - } - if (validTasks == 0) { - configProblems.add(new ConfigProblem(ConfigProblemType.ERROR, ConfigProblemDescriptions.NO_TASKS.getDescription(), "tasks")); - } - } - - boolean error = false; - for (ConfigProblem problem : configProblems) { - if (problem.getType() == ConfigProblemType.ERROR) { - error = true; - break; - } - } - - // END OF THE CHECKING - if (!error && !Options.ERROR_CHECKING_OVERRIDE.getBooleanValue(false)) { - QItemStack displayItem = getQItemStack("display", config); - List rewards = config.getStringList("rewards"); - List requirements = config.getStringList("options.requires"); - List rewardString = config.getStringList("rewardstring"); - List startString = config.getStringList("startstring"); - boolean repeatable = config.getBoolean("options.repeatable", false); - boolean cooldown = config.getBoolean("options.cooldown.enabled", false); - boolean permissionRequired = config.getBoolean("options.permission-required", false); - int cooldownTime = config.getInt("options.cooldown.time", 10); - int sortOrder = config.getInt("options.sort-order", 1); - String category = config.getString("options.category"); - Map placeholders = new HashMap<>(); - - if (category == null) category = ""; - - if (plugin.getQuestMode() == QuestMode.DAILY) { - repeatable = true; - cooldown = true; - cooldownTime = 0; - requirements = Collections.emptyList(); - permissionRequired = false; - } - - Quest quest; - if (category.equals("")) { - quest = new Quest(id, displayItem, rewards, requirements, repeatable, cooldown, cooldownTime, permissionRequired, rewardString, startString, placeholders, sortOrder); - } else { - quest = new Quest(id, displayItem, rewards, requirements, repeatable, cooldown, cooldownTime, permissionRequired, rewardString, startString, placeholders, category, sortOrder); - Category c = plugin.getQuestManager().getCategoryById(category); - if (c != null) { - c.registerQuestId(id); - } else { - configProblems.add(new ConfigProblem(ConfigProblemType.WARNING, ConfigProblemDescriptions.UNKNOWN_CATEGORY.getDescription(category), "options.category")); - } - } - - for (String taskId : config.getConfigurationSection("tasks").getKeys(false)) { - String taskRoot = "tasks." + taskId; - String taskType = config.getString(taskRoot + ".type"); - - Task task = new Task(taskId, taskType); - - for (String key : config.getConfigurationSection(taskRoot).getKeys(false)) { - task.addConfigValue(key, config.get(taskRoot + "." + key)); - } - - if (globalTaskConfig.containsKey(taskType)) { - for (Map.Entry entry : globalTaskConfig.get(taskType).entrySet()) { - if (Options.GLOBAL_TASK_CONFIGURATION_OVERRIDE.getBooleanValue() && task.getConfigValue(entry.getKey()) != null) - continue; - task.addConfigValue(entry.getKey(), entry.getValue()); - } - } - - quest.registerTask(task); - } - - - for (String line : displayItem.getLoreNormal()) { - findInvalidTaskReferences(quest, line, configProblems, "display.lore-normal"); - } - for (String line : displayItem.getLoreStarted()) { - findInvalidTaskReferences(quest, line, configProblems, "display.lore-started"); - } - - if (config.isConfigurationSection("placeholders")) { - for (String p : config.getConfigurationSection("placeholders").getKeys(false)) { - placeholders.put(p, config.getString("placeholders." + p)); - findInvalidTaskReferences(quest, config.getString("placeholders." + p), configProblems, "placeholders." + p); - } - } - if (plugin.getConfig().getBoolean("options.show-quest-registrations")) { - plugin.getQuestsLogger().info("Registering quest " + quest.getId() + " with " + quest.getTasks().size() + " tasks."); - } - plugin.getQuestManager().registerQuest(quest); - plugin.getTaskTypeManager().registerQuestTasksWithTaskTypes(quest); - pathToQuest.put(relativeLocation.getPath(), quest); - } - if (!configProblems.isEmpty()) { - filesWithProblems.put(relativeLocation.getPath(), configProblems); - } - } catch (Exception e) { - plugin.getQuestsLogger().severe("An exception occurred when attempting to load quest '" + path + "' (will be ignored)"); - e.printStackTrace(); - } - return FileVisitResult.CONTINUE; - } - }; - - try { - Files.walkFileTree(Paths.get(plugin.getDataFolder() + File.separator + "quests"), fileVisitor); - } catch (IOException e) { - e.printStackTrace(); - } - - // post-load checks - for (Map.Entry loadedQuest : pathToQuest.entrySet()) { - List configProblems = new ArrayList<>(); - for (String req : loadedQuest.getValue().getRequirements()) { - if (plugin.getQuestManager().getQuestById(req) == null) { - configProblems.add(new ConfigProblem(ConfigProblemType.WARNING, ConfigProblemDescriptions.UNKNOWN_REQUIREMENT.getDescription(req), "options.requires")); - } - } - - if (!configProblems.isEmpty()) { - if (filesWithProblems.containsKey(loadedQuest.getKey())) { - filesWithProblems.get(loadedQuest.getKey()).addAll(configProblems); - } else { - filesWithProblems.put(loadedQuest.getKey(), configProblems); - } - } - } - - for (TaskType taskType : plugin.getTaskTypeManager().getTaskTypes()) { - try { - taskType.onReady(); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - - problemsCount = 0; - for (List problemList : plugin.getQuestsConfigLoader().getFilesWithProblems().values()) { - problemsCount = problemsCount + problemList.size(); - } - } - - public Map> getFilesWithProblems() { - return filesWithProblems; - } - - public int getProblemsCount() { - return problemsCount; - } - - private void findInvalidTaskReferences(Quest quest, String s, List configProblems, String location) { - Pattern pattern = Pattern.compile("\\{([^}]+)}"); - - Matcher matcher = pattern.matcher(s); - while (matcher.find()) { - String[] parts = matcher.group(1).split(":"); - boolean match = false; - for (Task t : quest.getTasks()) { - if (t.getId().equals(parts[0])) { - match = true; - break; - } - } - if (!match) - configProblems.add(new ConfigProblem(ConfigProblemType.WARNING, - ConfigProblemDescriptions.UNKNOWN_TASK_REFERENCE.getDescription(parts[0]), location)); - } - } - - private QItemStack getQItemStack(String path, FileConfiguration config) { - String cName = config.getString(path + ".name", path + ".name"); - List cLoreNormal = config.getStringList(path + ".lore-normal"); - List cLoreStarted = config.getStringList(path + ".lore-started"); - - List loreNormal = translateColoursInList(cLoreNormal); - List loreStarted = translateColoursInList(cLoreStarted); - - String name; - name = ChatColor.translateAlternateColorCodes('&', cName); - - ItemStack is = plugin.getItemStack(path, config, - ItemGetter.Filter.DISPLAY_NAME, ItemGetter.Filter.LORE, ItemGetter.Filter.ENCHANTMENTS, ItemGetter.Filter.ITEM_FLAGS); - - return new QItemStack(plugin, name, loreNormal, loreStarted, is); - } - - private List translateColoursInList(List list) { - List coloured = new ArrayList<>(); - for (String s : list) { - coloured.add(ChatColor.translateAlternateColorCodes('&', s)); - } - return coloured; - } - - public enum ConfigProblemDescriptions { - - MALFORMED_YAML("Malformed YAML file, cannot read config"), - INVALID_QUEST_ID("ID '%s' is invalid, must be alphanumeric, unique and with no spaces"), - NO_TASKS("Quest contains no valid tasks"), - NO_TASK_TYPE("Task type not specified"), - UNKNOWN_TASK_TYPE("Task type '%s' does not exist"), - NO_DISPLAY_NAME("No name specified"), - NO_DISPLAY_MATERIAL("No material specified"), - UNKNOWN_MATERIAL("Material '%s' does not exist"), - UNKNOWN_ENTITY_TYPE("Entity type '%s' does not exist"), - TASK_MALFORMED_NOT_SECTION("Task '%s' is not a configuration section (has no fields)"), - TASK_MISSING_FIELD("Required field '%s' is missing for task type '%s'"), - UNKNOWN_TASK_REFERENCE("Attempt to reference unknown task '%s'"), - UNKNOWN_CATEGORY("Category '%s' does not exist"), - UNKNOWN_REQUIREMENT("Quest requirement '%s' does not exist"); - - private final String description; - - ConfigProblemDescriptions(String description) { - this.description = description; - } - - @Override - public String toString() { - return getDescription(); - } - - public String getDescription(String... format) { - return String.format(description, (Object[]) format); - } - } - - public enum ConfigProblemType { - - ERROR("Error", "E", ChatColor.RED, 1), - WARNING("Warning", "W", ChatColor.YELLOW, 2); - - private final String title; - private final String shortened; - private final ChatColor color; - private final int priority; - - ConfigProblemType(String title, String shortened, ChatColor color, int priority) { - this.title = title; - this.shortened = shortened; - this.color = color; - this.priority = priority; - } - - public String getTitle() { - return title; - } - - public String getShortened() { - return shortened; - } - - public ChatColor getColor() { - return color; - } - - public int getPriority() { - return priority; - } - - } - - public static class ConfigProblem { - - private final ConfigProblemType type; - private final String description; - private final String location; - - public ConfigProblem(ConfigProblemType type, String description, String location) { - this.type = type; - this.description = description == null ? "?" : description; - ; - this.location = location == null ? "?" : location; - } - - public ConfigProblem(ConfigProblemType type, String description) { - this.type = type; - this.description = description == null ? "?" : description; - ; - this.location = "?"; - } - - public ConfigProblemType getType() { - return type; - } - - public String getDescription() { - return description; - } - - public String getLocation() { - return location; - } - } -} diff --git a/src/main/java/com/leonardobishop/quests/util/QuestsLogger.java b/src/main/java/com/leonardobishop/quests/util/QuestsLogger.java deleted file mode 100644 index 426a2601..00000000 --- a/src/main/java/com/leonardobishop/quests/util/QuestsLogger.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.leonardobishop.quests.util; - -import com.leonardobishop.quests.Quests; - -public class QuestsLogger { - - private final Quests plugin; - private LoggingLevel serverLoggingLevel; - - public QuestsLogger(Quests plugin, LoggingLevel serverLoggingLevel) { - this.plugin = plugin; - this.serverLoggingLevel = serverLoggingLevel; - } - - public LoggingLevel getServerLoggingLevel() { - return serverLoggingLevel; - } - - public void setServerLoggingLevel(LoggingLevel serverLoggingLevel) { - this.serverLoggingLevel = serverLoggingLevel; - } - - public void log(String str, LoggingLevel level) { - if (serverLoggingLevel.getNumericVerbosity() < level.getNumericVerbosity()) { - return; - } - switch (level) { - case DEBUG: - plugin.getLogger().info("Debug: " + str); - break; - case INFO: - plugin.getLogger().info(str); - break; - case ERROR: - plugin.getLogger().severe(str); - break; - case WARNING: - plugin.getLogger().warning(str); - break; - } - } - - public void debug(String str) { - log(str, LoggingLevel.DEBUG); - } - - public void info(String str) { - log(str, LoggingLevel.INFO); - } - - public void warning(String str) { - log(str, LoggingLevel.WARNING); - } - - public void severe(String str) { - log(str, LoggingLevel.ERROR); - } - - public enum LoggingLevel { - ERROR(0), - WARNING(1), - INFO(2), - DEBUG(3); - - private int numericVerbosity; - - LoggingLevel(int number) { - numericVerbosity = number; - } - - public int getNumericVerbosity() { - return numericVerbosity; - } - - static LoggingLevel fromNumber(int number) { - for (LoggingLevel level : LoggingLevel.values()) { - if (level.getNumericVerbosity() == number) { - return level; - } - } - return LoggingLevel.INFO; - } - } - -} diff --git a/src/main/resources/config.yml b/src/main/resources/config.yml deleted file mode 100644 index f7084505..00000000 --- a/src/main/resources/config.yml +++ /dev/null @@ -1,355 +0,0 @@ -# | =================================================== | -# | Thank you for downloading and trying out | -# | Quests | -# | https://www.spigotmc.org/resources/23696/ | -# | https://github.com/LMBishop/Quests/ | -# | | -# | =x= | -# | | -# | Trying to add new quests? | -# | | -# | Go to the 'quests' | -# | subdirectory to edit the | -# | quests | -# | | -# | The example quests | -# | are commented to help you | -# | learn how to use the plugin | -# | | -# | =x= | -# | | -# | Have Discord & need help? | -# | Head to the GitHub page and click on the | -# | Discord link, or create an issue | -# | =================================================== | - - -# Categories are a way of grouping up quests. -# When a player uses /quests, a menu of categories will be presented to them. -# When a player clicks ona category, a list of quests under that category will show. -# If categories are disabled, all quests will be shown under one big GUI. -# Players can access specific categories by command using /quests c [category]. -# If a quest does not have a category, it will not be shown. -categories: - examples: - display: - name: "&cExample Quests" - lore: - - "&7This category contains example quests" - - "&7which are commented in the config." - - "&7The comments should guide you with" - - "&7how the config works." - - "" - - "&cIt is highly recommended you read this" - - "&csection and all the comments so you can" - - "&cmake the most of this plugin." - type: "WATER_BUCKET" - permissionexample: - display: - name: "&cPermission Example" - lore: - - "&7This category is an example of one which" - - "&7requires a permission to open." - - "" - - "&cIt is highly recommended you read this" - - "&csection and all the comments so you can" - - "&cmake the most of this plugin." - type: "WATER_BUCKET" - # This category needs the permission "quests.category.permissionexample", because the category ID is 'permissionexample'. - # The permission for other categories is: "quests.category.". - permission-required: true - -# The items listed below are placeholder items for quests which the player cannot start. -# You should change these for 1.8 -gui: - back-button: - name: "&cReturn" - lore: - - "&7Return to the categories menu." - type: "ARROW" - page-prev: - name: "&7Previous Page" - lore: - - "&7Switch the page to page &c{prevpage}." - type: "FEATHER" - page-next: - name: "&7Next Page" - lore: - - "&7Switch the page to page &c{nextpage}." - type: "FEATHER" - page-desc: - name: "&7Page &c{page}" - lore: - - "&7You are currently viewing page &c{page}." - type: "PAPER" - quest-locked-display: - name: "&c&lQuest Locked" - lore: - - "&7You have not completed the requirements" - - "&7for this quest (&c{quest}&7)." - - "" - - "&7Requires: &c{requirements}" - - "&7to be completed to unlock." - type: "RED_STAINED_GLASS_PANE" - quest-permission-display: - name: "&6&lNo Permission" - lore: - - "&7You do not have permission for this" - - "&7quest (&6{quest}&7)." - type: "BROWN_STAINED_GLASS_PANE" - quest-cooldown-display: - name: "&e&lQuest On Cooldown" - lore: - - "&7You have recently completed this quest" - - "&7(&e{quest}&7) and you must" - - "&7wait another &e{time} &7to unlock again." - type: "ORANGE_STAINED_GLASS_PANE" - quest-completed-display: - name: "&a&lQuest Complete" - lore: - - "&7You have completed this quest" - - "&7(&a{quest}&7) and cannot." - - "&7repeat it." - type: "GREEN_STAINED_GLASS_PANE" - no-started-quests: - name: "&c&lNo Started Quests" - lore: - - "&7Go start some!" - type: "FEATHER" - quest-cancel-yes: - name: "&a&lConfirm Cancel" - lore: - - "&7Confirm you wish to cancel" - - "&7this quest and lose all" - - "&7progress." - type: "GREEN_STAINED_GLASS_PANE" - quest-cancel-no: - name: "&c&lAbort Cancel" - lore: - - "&7Return to the quest menu." - type: "RED_STAINED_GLASS_PANE" - quest-cancel-background: - type: "GRAY_STAINED_GLASS_PANE" - -# Here you can add custom items to the quest menu -# Categories & quests will fill empty slots -#custom-elements: -# "categories": # apply to the categories menu (the main menu by default) -# 0: # <--- slot 1, note the slots start from 0! so 0 = slot 1 in this case -# display: -# name: "&cExample Custom Item (slot 1)" -# lore: -# - "&7This is a custom item which can be added" -# - "&7to your menus. This is purely cosmetic." -# - "" -# - "&7Two empty slots should follow." -# type: "DIAMOND_BLOCK" -# 1: # <--- start from slot 2 -# spacer: true # empty slot in GUI -# repeat: 2 # repeats for 2 slots -# 3: # <--- start from slot 4 -# display: -# name: "&cExample Custom Item (slots 4 - 7)" -# lore: -# - "&7This is a custom item which can be added" -# - "&7to your menus, but in slot 4 and repeated" -# - "&73 times." -# - "&7" -# - "&7This will come after 2 empty slots." -# - "&7" -# - "&7This is purely cosmetic." -# type: "NETHERRACK" -# repeat: 3 # repeats for 3 more slots -# "c:examples": # apply to the category "examples" -# 0: -# display: -# name: "&cExample Custom Item (slot 1)" -# lore: -# - "&7This is a custom item which can be added" -# - "&7to your menus. This is purely cosmetic." -# type: "EMERALD_BLOCK" -# "quests": # apply to the general quests menu IF categories are disabled -# 0: -# display: -# name: "&cExample Custom Item (slot 1)" -# lore: -# - "&7This is a custom item which can be added" -# - "&7to your menus. This is purely cosmetic." -# type: "EMERALD_BLOCK" - -options: - # If categories are disabled, quests will be put into one big gui. - categories-enabled: true - # If true, the gui size will automatically change based on the amount of quests inside it. - trim-gui-size: true - # Enable/disable titles - titles-enabled: true - # Players cannot start any more quests than this at a single time - quest-started-limit: 2 - # Hide locked quests, quests on cooldown and completed (but not repeatable) quests - gui-hide-locked: false - # Allow players to cancel a quest (you may want to remove the cancel instructions in the global item lore) - allow-quest-cancel: true - # Allow players to track a quest (you may want to remove the tracking instructions in the global item lore) - allow-quest-track: true - # Titles for the GUIs - guinames: - quests-category: "Quests Categories" - quests-menu: "Quests" - quests-started-menu: "Started Quests" - daily-quests: "Daily Quests" - quest-cancel: "Cancel Quest" - # Show when quests register in console - will only show if verbose-logging-level=2. Disable if you want less console spam at startup. - show-quest-registrations: true - # Hide quests which a player cannot start due to permissions. - gui-hide-quests-nopermission: false - # Hide categories which a player cannot open due to permissions. - gui-hide-categories-nopermission: false - # Replace placeholders from PlaceholderAPI in Quests GUI items - gui-use-placeholderapi: false - # Make it so players do not have to start quest themselves - quest-autostart: false - # Automatically track quests on start, and stop tracking on completion - quest-autotrack: true - # How much quests should log, 0 = errors only, 1 = warnings, 2 = info, 3 = debug - verbose-logging-level: 2 - # Verify quests exist when a player's data is loaded - inconsistencies may arise when - # players progress on specific quests and those quests are later removed. The problem is that their progress - # is still kept in the quest progress file, which may lead to issues such as players reaching a quest started - # limit when the quests they had active no longer exist - having this option enabled prevents - # non-existent quests from being loaded - verify-quest-exists-on-load: true - performance-tweaking: # The following are measured in server ticks, multiply SECONDS by 20 to get the number of ticks. - quest-queue-executor-interval: 1 # how frequently Quests should execute the next check in the completion queue (def=1 - 0.05s) - increase this value if you are struggling with performance - quest-autosave-interval: 12000 # how frequently online players data will be autosaved (def=12000 - 10 minutes) - tab-completion: - enabled: true - error-checking: - # Allow quests to be loaded if they contain errors - # This may lead to errors in the console! - override-errors: false - # How much time (in seconds) that plugin will cache placeholders - placeholder-cache-time: 10 - # Whether or not the global task configuration will override per-task configuration settings - global-task-configuration-override: false - # Whether or not the global display configuration will override per-quest display settins - global-quest-display-configuration-override: false - # Storage options - please see the following: https://github.com/LMBishop/Quests/wiki/Storage-Providers - storage: - # Either 'yaml' (flatfile) or 'mysql' (network) - # Please read the following before using MySQL https://github.com/LMBishop/Quests/wiki/Storage-Providers#network - provider: "yaml" - # The following is only applicable for database storage providers (e.g. mysql) - database-settings: - network: - # The name of the database. This database should already exist! - database: "minecraft" - username: "root" - password: "" - # Address should be in the format ip:port (just like the game itself) - address: "localhost:3306" - # This plugin uses 'HikariCP' for connection management, the pooling configuration can be changed here - connection-pool-settings: - # The maximum number of connections to keep open with the database (def=8) - maximum-pool-size: 8 - # The minimum number of connections to keep open with the database (def=8) - minimum-idle: 8 - # The maximum time (in milliseconds) to keep a single connection open (def=1800000 - 30 min) - maximum-lifetime: 1800000 - # The time (in milliseconds) the plugin will wait for a response by the database (def=500) - connection-timeout: 5000 - # The prefix each table will use - table-prefix: "quests_" - - -quest-mode: - mode: "NORMAL" # More modes are a work in progress - -# The global task configuration will apply to the config of each task of a specified type in each quest. -# In the example below, every task with a type of "inventory" will have the config option "update-progress" -# set to true. This is useful if you do not want to go through each quest if you want to update the configuration -# for every task of a specific type. -# -# You must uncomment all below lines for the example to have any effect -# vvvvvvvvvvvvvvvvvvvvvvvvv -#global-task-configuration: -# types: -# inventory: -# update-progress: true - -global-quest-display: - lore: -# append-normal: -# - "..." - append-not-started: - - "" - - "&eLeft Click &7to start this quest." - append-started: - - "" - - "&aYou have started this quest." - - "&eMiddle Click &7to track this quest." - - "&eRight Click &7to cancel this quest." - append-tracked: - - "" - - "&aYou are &etracking &athis quest." - - "&eMiddle Click &7to stop tracking this quest." - - "&eRight Click &7to cancel this quest." - - -# Configure titles -titles: - quest-start: - title: "&cQuest Started" - subtitle: "&7{quest}" - quest-complete: - title: "&cQuest Complete" - subtitle: "&7{quest}" - -# Configure messages -messages: - time-format: "{hours}h {minutes}m" - quest-start: "&7Quest &c{quest} &7started!" - quest-complete: "&7Quest &c{quest} &7completed!" - quest-cancel: "&7Quest &c{quest} &7cancelled!" - quest-track: "&7Tracking quest &c{quest}&7." - quest-track-stop: "&7No longer tracking quest &c{quest}&7." - quest-random-none: "&cYou have no quests which you can start." - quest-start-limit: "&7Players are limited to &c{limit} &7started quests at a time." - quest-start-disabled: "&7You cannot repeat this quest." - quest-start-locked: "&7You have not unlocked this quest yet." - quest-start-cooldown: "&7You have recently completed this quest. You have to wait &c{time} &7until you are able to restart it." - quest-start-started: "&7You have already started this quest." - quest-start-permission: "&7You do not have permission to start this quest." - quest-category-permission: "&7You do not have permission to view this category." - quest-category-quest-permission: "&7You do not have permission to start this quest since it is in a category you do not have permission to view." - quest-cancel-notstarted: "&7You have not started this quest." - quest-updater: "&cQuests > &7A new version &c{newver} &7was found on Spigot (your version: &c{oldver}&7). Please update me! <3 - Link: {link}" - command-data-not-loaded: "&4Your quests progress file has not been loaded; you cannot use quests. If this issue persists, contact an admin." - command-sub-doesntexist: "&7The specified subcommand '&c{sub}' &7does not exist." - command-quest-start-doesntexist: "&7The specified quest '&c{quest}&7' does not exist." - command-quest-general-doesntexist: "&7The specified quest '&c{quest}&7' does not exist." - command-category-open-disabled: "&7Categories are disabled." - command-category-open-doesntexist: "&7The specified category '&c{category}&7' does not exist." - command-quest-admin-playernotfound: "&7Player '&c{player}&7' could not be found." - command-quest-openquests-admin-success: "&7Opened Quest GUI for player &c{player}&7." - command-quest-opencategory-admin-success: "&7Opened category &c{category} &7for player &c{player}&7." - command-taskview-admin-fail: "&7Task type '&c{task}&7' does not exist." - beta-reminder: "&cQuests > &7Reminder: you are currently using a &cbeta &7version of Quests. Please send bug reports to https://github.com/fatpigsarefat/Quests/issues and check for updates regularly using &c/quests admin update&7!" - command-quest-admin-loaddata: "&7Quest data for '&c{player}&7' is being loaded." - command-quest-admin-nodata: "&7No data could be found for player &c{player}&7." - command-quest-admin-fullreset: "&7Data for player &c{player}&7 has been fully reset." - command-quest-admin-clean-success: "&7All quest progress files have been cleaned." - command-quest-admin-clean-fail: "&cFailed to clean quest progress files. Please report the error in the console." - command-quest-admin-start-faillocked: "&7Quest '&c{quest}&7' could not be started for player &c{player}&7. They have not yet unlocked it." - command-quest-admin-start-failcooldown: "&7Quest '&c{quest}&7' could not be started for player &c{player}&7. It is still on cooldown for them." - command-quest-admin-start-failcomplete: "&7Quest '&c{quest}&7' could not be started for player &c{player}&7. They have already completed it." - command-quest-admin-start-faillimit: "&7Quest '&c{quest}&7' could not be started for player &c{player}&7. They have reached their quest start limit." - command-quest-admin-start-failstarted: "&7Quest '&c{quest}&7' could not be started for player &c{player}&7. It is already started." - command-quest-admin-start-failpermission: "&7Quest '&c{quest}&7' could not be started for player &c{player}&7. They do not have permission." - command-quest-admin-start-failcategorypermission: "&7Quest '&c{quest}&7' could not be started for player &c{player}&7. They do not have permission for the category which the quest is in." - command-quest-admin-start-failother: "&7Quest '&c{quest}&7' could not be started for player &c{player}&7." - command-quest-admin-start-success: "&7Quest &c{quest} &7started for player &c{player}&7." - command-quest-admin-category-permission: "&7Category &c{category} &7 could not be opened for player &c{player}&7. They do not have permission to view it." - command-quest-admin-complete-success: "&7Quest &c{quest} &7completed for player &c{player}&7." - command-quest-admin-reset-success: "&7Successfully reset quest '&c{quest}&7' for player &c{player}&7." - diff --git a/src/main/resources/plugin.yml b/src/main/resources/plugin.yml deleted file mode 100644 index 4c7b7389..00000000 --- a/src/main/resources/plugin.yml +++ /dev/null @@ -1,30 +0,0 @@ -name: Quests - -# This will be replaced with the property "version" in build.gradle -version: ${version} - -main: com.leonardobishop.quests.Quests -website: https://github.com/LMBishop/Quests -author: "LMBishop & contributors" -softdepend: [ASkyBlock, BentoBox, IridiumSkyblock, uSkyBlock, Citizens, MythicMobs, PlaceholderAPI, Essentials, ShopGUIPlus, CoreProtect] -prefix: Quests -api-version: "1.13" # allows new API features but Quests will still work pre-1.13 - -commands: - quests: - description: Main command - usage: /quests - permission: quests.command - aliases: [q, quest] - -#todo redo perms -permissions: - quests.command: - description: Permission for main command - default: true - quests.command.random: - description: Permission to execute /q random - default: true - quests.admin: - description: Permission for the admin commands - default: op \ No newline at end of file diff --git a/src/main/resources/quests/README.txt b/src/main/resources/quests/README.txt deleted file mode 100644 index 779dd6bb..00000000 --- a/src/main/resources/quests/README.txt +++ /dev/null @@ -1,40 +0,0 @@ -# !! READ ME - IT WILL NOT TAKE LONG !! -# -# Each file ín the 'quests' folder defines a single quest. -# The name of the file is the quest ID. These must be alphanumeric and unique. -# Quest files must be in the .yml format. -# -# A quest is a series of tasks which players must complete for a reward and may require a previous quest to start. -# A task is an objective such as breaking blocks or obtaining items. -# A reward is a command executed by the SERVER. Use {player} to get the players name. -# -# Most task types will allow you to restrict them to a certain world. Check out the wiki for which ones. -# -# A quest can have a 'startstring' (this is optional). They will be sent to the player when they start the quest. -# A quest can have a 'rewardstring' (this is optional). They will be sent to the player when they complete the quest. -# An example of the startstring/rewardstring in use can be seen in the quest example4. -# -# Each quest will have ONE "display" item, this is the item shown to the player in the GUI. -# The display item will have a "name", a "type" and TWO lores. -# The name is the name of the item, the type is the material and the lore is the text underneath the item (when mouse-over-ing). -# The first lore you must give is called 'lore-normal'. This is the lore seen if the player has not started the quest. -# The second lore you must give is 'lore-started'. This will be APPENDED to the first lore IF the player has started the quest - useful for putting progression. -# Within the lores you can get the players progress for each task. Use {TASKID:progress} (replace TASKID with the ID of the task). -# You can also get if a task is complete. Use {TASKID:complete} (replace TASKID with the ID of the task). -# -# Quests can be put inside a category. When a player runs /quests they will first see a menu of categories. -# They can click one and another menu of quests under that category will show up. -# -# =============================================================== -# -# You can see other task types here: -# https://github.com/LMBishop/Quests/wiki/Task-Types -# -# =============================================================== -# -# Need help? -# Find the Discord link in the README.md, or open an issue on GitHub -# https://github.com/LMBishop/Quests/issues -# https://github.com/LMBishop/Quests/blob/master/README.md -# -# =============================================================== diff --git a/src/main/resources/quests/example1.yml b/src/main/resources/quests/example1.yml deleted file mode 100644 index ca57f714..00000000 --- a/src/main/resources/quests/example1.yml +++ /dev/null @@ -1,61 +0,0 @@ -# The name of this file is the quest ID. It must be alphanumeric and unique. - -# Everything inside of this section defines tasks the player must complete to progress. -tasks: - # This is the task ID ("mining"). This can share the same name as the quest ID but MUST be unique with all other task IDs in the same quest. - mining: - # This defines what type of task this is. In this instance, it is "blockbreak" (breaking blocks) - # NOTE: guides to set up each type of task is on the wiki (see README)! - type: "blockbreak" - # This defines the amount of blocks which need to be broken - amount: 30 - # You can have multiple tasks for each quest (example further down). - -# Everything inside of this section defines the display item. -display: - # This is the name of the item. This allows color codes. - name: "&cExample I (Single Task)" - # This is the lore of the item if the player has not started the quest. This allows color codes and task/player placeholders. - lore-normal: - - "&cThis category is designed to show you the different" - - "&cattributes a quest can have." - - "" - - "&7This quest requires you to:" - - "&7 - Break &f30 blocks&7." - - "" - - "&7Rewards:" - - "&7 - &f10 &7diamonds." - # This lore will be appended to the bottom of the above lore when the player starts their quest. - # To get the players progress through a task, use {TASKID:progress} and replace TASKID with the ID of the task. - lore-started: - - "" - - "&7Your current progression:" - - "&7 - &f{mining:progress}&7/30 blocks broken." - # This is the material of the item. It is recommended to stick to bukkit names. - type: "WOODEN_PICKAXE" - -# List all commands to be executed by the server when the player completes the quest. Use {player} to get the players name. -rewards: - - "give {player} diamond 10" - -# These placeholders are accessible using PlaceholderAPI, for example %quests_tracked_p:description% -# They are useful for putting information about the players tracked quest on a scoreboard -# You may want to keep the names of them the same for ALL quests for this use-case -placeholders: - description: "&7Break &f30 blocks &7of any type." - progress: " &8- &f{mining:progress}&7/30 broken" - -# Everything inside this section define quest-specific options -options: - # This is the category for the quest, it will appear under the "examples" category. Categories can be disabled. - category: "examples" - # Set if the quest can be repeated after being completed for the first time. - repeatable: false - # Define the cooldown on quests. The above (repeatable) must be true for this to take effect. - cooldown: - # If true, players will have to wait between repeating quests. - enabled: true - # Time (in minutes) - time: 1440 - # This is the relative position in the GUI - sort-order: 1 \ No newline at end of file diff --git a/src/main/resources/quests/example2.yml b/src/main/resources/quests/example2.yml deleted file mode 100644 index 7ad82bea..00000000 --- a/src/main/resources/quests/example2.yml +++ /dev/null @@ -1,47 +0,0 @@ -# This is a quest which requires the previous quest to be complete to start. - -tasks: - # Unlike the previous quest, this quest has multiple tasks. - mining: - type: "blockbreak" - amount: 100 - building: - type: "blockplace" - amount: 100 -display: - name: "&cExample II (Multiple Tasks)" - lore-normal: - - "&cThis category is designed to show you the different" - - "&cattributes a quest can have. This quest requires" - - "&cmultiple things to be done, unlike the previous one." - - "" - - "&7This quest requires you to:" - - "&7 - Break &f100 &7blocks." - - "&7 - Place &f100 &7blocks." - - "" - - "&7Rewards:" - - "&7 - &f15 diamonds&7." - - "&7 - &f$50&7 added to your in-game balance." - lore-started: - - "" - - "&7Your current progression:" - - "&7 - &f{mining:progress}&7/100 blocks broken." - - "&7 - &f{building:progress}&7/100 blocks placed." - type: "GRASS_BLOCK" -rewards: - - "give {player} diamond 15" - - "eco give {player} 50" -placeholders: - description: "&7Break and place &f100 blocks &7of any type." - progress: " &8- &f{mining:progress}&7/100 broken, &f{building:progress}&7/100 placed" -options: - category: "examples" - # Unlike the previous quest, this quest has "example1" as a required quest. You cannot start this quest without "example1" quest complete. - requires: - - "example1" - repeatable: false - cooldown: - enabled: true - time: 1440 - # The sort order has been changed so this quest will appear after in the GUI - sort-order: 2 \ No newline at end of file diff --git a/src/main/resources/quests/example3.yml b/src/main/resources/quests/example3.yml deleted file mode 100644 index dbd893e4..00000000 --- a/src/main/resources/quests/example3.yml +++ /dev/null @@ -1,49 +0,0 @@ -# This is a quest which requires the previous quest to be complete to start. -# Unlike the previous quest, this one can be re-done but it has a 10 minute cooldown. - -tasks: - # Unlike the previous two quests, this quest specifies a specific block to be broken. - mining: - type: "blockbreakcertain" - amount: 81 - block: GOLD_ORE - building: - type: "blockplacecertain" - amount: 9 - block: GOLD_BLOCK -display: - name: "&cExample III (Repeatable, 10 minute cooldown)" - lore-normal: - - "&cThis category is designed to show you the different" - - "&cattributes a quest can have. This quest can be replayed" - - "&cafter a cooldown, unlike the previous one." - - "" - - "&7This quest requires you to:" - - "&7 - Break &f81 gold ore&7." - - "&7 - Place &f9 gold blocks&7." - - "" - - "&7Rewards:" - - "&7 - &f30 diamonds&7." - - "&7 - &f$10&7 added to your in-game balance." - lore-started: - - "" - - "&7Your current progression:" - - "&7 - &f{mining:progress}&7/81 gold ore broken." - - "&7 - &f{building:progress}&7/9 gold blocks placed." - type: "GOLD_ORE" -rewards: - - "give {player} diamond 30" - - "eco give {player} 10" -placeholders: - description: "&7Break &f81 gold ore &7and place &f9 gold blocks." - progress: " &8- &f{mining:progress}&7/81 gold ore, &f{building:progress}&7/9 gold blocks" -options: - category: "examples" - requires: - - "example2" - # This quest is repeatable, it has cooldowns enabled (meaning the player must wait before repeating it) and the time set to 10 (minutes). - repeatable: true - cooldown: - enabled: true - time: 10 - sort-order: 3 \ No newline at end of file diff --git a/src/main/resources/quests/example4.yml b/src/main/resources/quests/example4.yml deleted file mode 100644 index 4e9c27a8..00000000 --- a/src/main/resources/quests/example4.yml +++ /dev/null @@ -1,50 +0,0 @@ -# This is a quest which requires the previous quest to be complete to start. -# Unlike the previous quests, this quest has a reward string and a start string. - -tasks: - mobkilling: - type: "mobkilling" - amount: 3 -display: - name: "&cExample IV (Reward String)" - lore-normal: - - "&cThis category is designed to show you the different" - - "&cattributes a quest can have. This quest has a 'reward string'" - - "&c(a series of messages sent when a quest is complete)," - - "&cunlike the previous one." - - "" - - "&7This quest requires you to:" - - "&7 - Kill &f3 &7mobs." - - "" - - "&7Rewards:" - - "&7 - &f$50 &7added to your in-game balance." - - "&7 - &f1 diamond&7." - lore-started: - - "" - - "&7Your current progression:" - - "&7 - &f{mobkilling:progress}&7/3 mobs killed." - type: "STRING" -# Here you can list messages which will be sent to the player (if they are online) upon the quest starting. -startstring: - - "&7Upon completion of this quest, you will be rewarded with" - - " &8* &c$50" - - " &8* &c1 diamonds" -rewards: - - "eco give {player} 50" - - "give {player} diamond 1" -placeholders: - description: "&7Kill &f3 &7mobs." - progress: " &8- &f{mobkilling:progress}&7/3 mobs" -# Here you can list messages which will be sent to the player (if they are online) upon completion. -rewardstring: - - " &8* &c$1000 &7was added to your in-game balance." - - " &8* &c1 diamond &7was added to your inventory." -options: - category: "examples" - requires: - - "example3" - repeatable: true - cooldown: - enabled: true - time: 10 - sort-order: 4 \ No newline at end of file diff --git a/src/main/resources/quests/example5.yml b/src/main/resources/quests/example5.yml deleted file mode 100644 index cb92f0f1..00000000 --- a/src/main/resources/quests/example5.yml +++ /dev/null @@ -1,38 +0,0 @@ -tasks: - building: - type: "blockplace" - amount: 10 -display: - name: "&cExample V (Permission)" - lore-normal: - - "&cThis category is designed to show you the different" - - "&cattributes a quest can have. This quest requires" - - "&ccertain permissions." - - "" - - "&7This quest requires you to:" - - "&7 - Place &f10 &7blocks." - - "" - - "&7Rewards:" - - "&7 - &f$10 &7added to your in-game balance." - lore-started: - - "" - - "&7Your current progression:" - - "&7 - &f{building:progress}&7/10 blocks placed." - type: "GRASS_BLOCK" -rewards: - - "eco give {player} 10" -placeholders: - description: "&7Place &f10 &7blocks of any type." - progress: " &8- &f{building:progress}&7/10 blocks" -options: - category: "examples" - requires: - - "example4" - # Unlike the previous quests, this one requires you to have the permission "quests.quest.example5" to start. - # The permission for other quests is: "quests.quest.". - permission-required: true - repeatable: false - cooldown: - enabled: true - time: 1440 - sort-order: 5 \ No newline at end of file diff --git a/src/main/resources/quests/example6.yml b/src/main/resources/quests/example6.yml deleted file mode 100644 index 0913a7cb..00000000 --- a/src/main/resources/quests/example6.yml +++ /dev/null @@ -1,35 +0,0 @@ -tasks: - building: - type: "blockplace" - amount: 10 -display: - name: "&cExample VI (Different category, permissions)" - lore-normal: - - "&cThis category is designed to show you the different" - - "&cattributes a quest can have. This quest requires" - - "&ccertain permissions." - - "" - - "&7This quest requires you to:" - - "&7 - Place &f10 &7blocks." - - "" - - "&7Rewards:" - - "&7 - &f$10 &7added to your in-game balance." - lore-started: - - "" - - "&7Your current progression:" - - "&7 - &f{building:progress}&7/10 blocks placed." - type: "GRASS_BLOCK" -rewards: - - "eco give {player} 10" -placeholders: - description: "&7Place &f10 &7blocks of any type." - progress: " &8- &f{building:progress}&7/10 blocks" -options: - category: "permissionexample" - # This quest has no specific permission, however its category does. The permission for the category is "quests.category.permissionexample" - repeatable: false - cooldown: - enabled: true - time: 1440 - # The quest is in a different category so the sort order is 1. - sort-order: 1 \ No newline at end of file diff --git a/src/main/resources/quests/example7.yml b/src/main/resources/quests/example7.yml deleted file mode 100644 index 32bb7e04..00000000 --- a/src/main/resources/quests/example7.yml +++ /dev/null @@ -1,37 +0,0 @@ -tasks: - building: - type: "blockplace" - amount: 10 - worlds: - - "world" -display: - name: "&cExample VII (Different category, world restricted)" - lore-normal: - - "&cThis category is designed to show you the different" - - "&cattributes a quest can have. This quest requires" - - "&chas a task which requires you to be in a world called 'world'." - - "" - - "&7This quest requires you to:" - - "&7 - Place &f10 &7blocks." - - "" - - "&7Rewards:" - - "&7 - &f$10 &7added to your in-game balance." - lore-started: - - "" - - "&7Your current progression:" - - "&7 - &f{building:progress}&7/10 blocks placed." - type: "GRASS_BLOCK" -rewards: - - "eco give {player} 10" -placeholders: - description: "&7Place &f10 &7blocks of any type in world &fworld." - progress: " &8- &f{building:progress}&7/10 blocks" -options: - category: "permissionexample" - # This quest has no specific permission, however its category does. The permission for the category is "quests.category.permissionexample" - repeatable: false - cooldown: - enabled: true - time: 1440 - # The quest is in a different category so the sort order is 1. - sort-order: 1 \ No newline at end of file -- cgit v1.2.3-70-g09d2