diff --git a/src/main/java/com/songoda/skyblock/SkyBlock.java b/src/main/java/com/songoda/skyblock/SkyBlock.java index 568c9f69..e5d78d73 100644 --- a/src/main/java/com/songoda/skyblock/SkyBlock.java +++ b/src/main/java/com/songoda/skyblock/SkyBlock.java @@ -41,12 +41,14 @@ import com.songoda.update.SongodaUpdate; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.ConsoleCommandSender; +import org.bukkit.entity.Player; import org.bukkit.event.HandlerList; import org.bukkit.generator.ChunkGenerator; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import java.io.File; +import java.util.UUID; public class SkyBlock extends JavaPlugin { diff --git a/src/main/java/com/songoda/skyblock/api/island/IslandManager.java b/src/main/java/com/songoda/skyblock/api/island/IslandManager.java index a551fe56..e3cf6978 100644 --- a/src/main/java/com/songoda/skyblock/api/island/IslandManager.java +++ b/src/main/java/com/songoda/skyblock/api/island/IslandManager.java @@ -228,12 +228,26 @@ public class IslandManager { } /** - * Deletes an Island permanently + * Executes the {@link IslandManager#deleteIsland(Island, boolean)} method with island and + * true as the parameters + *

+ * See {@link IslandManager#deleteIsland(Island, boolean)} */ public void deleteIsland(Island island) { Preconditions.checkArgument(island != null, "Cannot delete island to null island"); - this.islandManager.deleteIsland(island.getIsland()); + this.islandManager.deleteIsland(island.getIsland(), true); + } + + /* + * If force is set to true, the island will be deleted and no conditions will be + * checked, else it will only delete the island if the island deletion + * conditions are met. + */ + public void deleteIsland(Island island, boolean force) { + Preconditions.checkArgument(island != null, "Cannot delete island to null island"); + + this.islandManager.deleteIsland(island.getIsland(), force); } /** diff --git a/src/main/java/com/songoda/skyblock/command/commands/admin/DeleteCommand.java b/src/main/java/com/songoda/skyblock/command/commands/admin/DeleteCommand.java index e90e2215..283ff49a 100644 --- a/src/main/java/com/songoda/skyblock/command/commands/admin/DeleteCommand.java +++ b/src/main/java/com/songoda/skyblock/command/commands/admin/DeleteCommand.java @@ -91,7 +91,7 @@ public class DeleteCommand extends SubCommand { } island.setDeleted(true); - islandManager.deleteIsland(island); + islandManager.deleteIsland(island, true); messageManager.sendMessage(sender, configLoad.getString("Command.Island.Admin.Delete.Deleted.Message").replace("%player", diff --git a/src/main/java/com/songoda/skyblock/command/commands/admin/ReloadCommand.java b/src/main/java/com/songoda/skyblock/command/commands/admin/ReloadCommand.java index 76a29ec7..23535649 100644 --- a/src/main/java/com/songoda/skyblock/command/commands/admin/ReloadCommand.java +++ b/src/main/java/com/songoda/skyblock/command/commands/admin/ReloadCommand.java @@ -19,6 +19,7 @@ import com.songoda.skyblock.limit.LimitationInstanceHandler; import com.songoda.skyblock.message.MessageManager; import com.songoda.skyblock.scoreboard.ScoreboardManager; import com.songoda.skyblock.sound.SoundManager; +import com.songoda.skyblock.utils.item.MenuClickRegistry; import com.songoda.skyblock.utils.version.Sounds; public class ReloadCommand extends SubCommand { @@ -40,11 +41,11 @@ public class ReloadCommand extends SubCommand { LimitationInstanceHandler limitHandler = skyblock.getLimitationHandler(); FileManager fileManager = skyblock.getFileManager(); - messageManager.sendMessage(sender, "&cPlease note that this command is not supported and may " + - "cause issues that could put the plugin in an unstable state. " + - "If you encounter any issues please stop your server, edit the configuration files, " + - "and then start your server again. This command does NOT reload all the plugin files, only " + - "the config.yml, language.yml, generators.yml, levelling.yml, and limits.yml."); + messageManager.sendMessage(sender, + "&cPlease note that this command is not supported and may " + "cause issues that could put the plugin in an unstable state. " + + "If you encounter any issues please stop your server, edit the configuration files, " + + "and then start your server again. This command does NOT reload all the plugin files, only " + + "the config.yml, language.yml, generators.yml, levelling.yml, and limits.yml."); Config config = fileManager.getConfig(new File(skyblock.getDataFolder(), "language.yml")); FileConfiguration configLoad = config.getFileConfiguration(); @@ -56,8 +57,7 @@ public class ReloadCommand extends SubCommand { Config configFileConfig = configs.get(configFileName); String configFilePath = configFileName.replace(configFileConfig.getFile().getName(), ""); - if (configFilePath.equals(skyblock.getDataFolder().toString() + "\\") - || configFilePath.equals(skyblock.getDataFolder().toString() + "/")) { + if (configFilePath.equals(skyblock.getDataFolder().toString() + "\\") || configFilePath.equals(skyblock.getDataFolder().toString() + "/")) { configFileConfig.loadFile(); } } @@ -95,6 +95,7 @@ public class ReloadCommand extends SubCommand { }); limitHandler.reloadAll(); + MenuClickRegistry.getInstance().reloadAll(); messageManager.sendMessage(sender, configLoad.getString("Command.Island.Admin.Reload.Reloaded.Message")); soundManager.playSound(sender, Sounds.ANVIL_USE.bukkitSound(), 1.0F, 1.0F); diff --git a/src/main/java/com/songoda/skyblock/command/commands/admin/StackableCommand.java b/src/main/java/com/songoda/skyblock/command/commands/admin/StackableCommand.java index ff24df1b..be606d18 100644 --- a/src/main/java/com/songoda/skyblock/command/commands/admin/StackableCommand.java +++ b/src/main/java/com/songoda/skyblock/command/commands/admin/StackableCommand.java @@ -9,7 +9,6 @@ import org.bukkit.block.Block; import org.bukkit.command.ConsoleCommandSender; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; - import com.songoda.skyblock.command.SubCommand; import com.songoda.skyblock.message.MessageManager; import com.songoda.skyblock.stackable.Stackable; diff --git a/src/main/java/com/songoda/skyblock/command/commands/island/BanCommand.java b/src/main/java/com/songoda/skyblock/command/commands/island/BanCommand.java index e2f3007b..d0f31804 100644 --- a/src/main/java/com/songoda/skyblock/command/commands/island/BanCommand.java +++ b/src/main/java/com/songoda/skyblock/command/commands/island/BanCommand.java @@ -1,5 +1,13 @@ package com.songoda.skyblock.command.commands.island; +import java.io.File; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.command.ConsoleCommandSender; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; + import com.songoda.skyblock.ban.Ban; import com.songoda.skyblock.command.SubCommand; import com.songoda.skyblock.config.FileManager; @@ -7,19 +15,11 @@ import com.songoda.skyblock.config.FileManager.Config; import com.songoda.skyblock.island.Island; import com.songoda.skyblock.island.IslandManager; import com.songoda.skyblock.island.IslandRole; -import com.songoda.skyblock.island.IslandWorld; import com.songoda.skyblock.message.MessageManager; import com.songoda.skyblock.sound.SoundManager; import com.songoda.skyblock.utils.player.OfflinePlayer; import com.songoda.skyblock.utils.version.Sounds; import com.songoda.skyblock.utils.world.LocationUtil; -import org.bukkit.Bukkit; -import org.bukkit.command.ConsoleCommandSender; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; - -import java.io.File; -import java.util.UUID; public class BanCommand extends SubCommand { @@ -40,16 +40,11 @@ public class BanCommand extends SubCommand { if (island == null) { messageManager.sendMessage(player, configLoad.getString("Command.Island.Ban.Owner.Message")); soundManager.playSound(player, Sounds.ANVIL_LAND.bukkitSound(), 1.0F, 1.0F); - } else if (fileManager.getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration() - .getBoolean("Island.Visitor.Banning")) { + } else if (fileManager.getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration().getBoolean("Island.Visitor.Banning")) { if (island.hasRole(IslandRole.Owner, player.getUniqueId()) - || (island.hasRole(IslandRole.Operator, player.getUniqueId()) - && island.getSetting(IslandRole.Operator, "Ban").getStatus())) { + || (island.hasRole(IslandRole.Operator, player.getUniqueId()) && island.getSetting(IslandRole.Operator, "Ban").getStatus())) { Player targetPlayer = Bukkit.getServer().getPlayer(args[0]); - if (targetPlayer != null && targetPlayer.hasPermission("fabledskyblock.bypass.ban")) - return; - UUID targetPlayerUUID = null; String targetPlayerName = null; @@ -58,8 +53,6 @@ public class BanCommand extends SubCommand { targetPlayerUUID = targetPlayerOffline.getUniqueId(); targetPlayerName = targetPlayerOffline.getName(); - if (skyblock.getEconomyManager().hasPermission(skyblock.getWorldManager().getWorld(IslandWorld.Normal).getName(), Bukkit.getOfflinePlayer(targetPlayerUUID), "fabledskyblock.bypass.ban")) - return; } else { targetPlayerUUID = targetPlayer.getUniqueId(); targetPlayerName = targetPlayer.getName(); @@ -71,39 +64,35 @@ public class BanCommand extends SubCommand { } else if (targetPlayerUUID.equals(player.getUniqueId())) { messageManager.sendMessage(player, configLoad.getString("Command.Island.Ban.Yourself.Message")); soundManager.playSound(player, Sounds.ANVIL_LAND.bukkitSound(), 1.0F, 1.0F); - } else if (island.hasRole(IslandRole.Member, targetPlayerUUID) - || island.hasRole(IslandRole.Operator, targetPlayerUUID) + } else if (island.hasRole(IslandRole.Member, targetPlayerUUID) || island.hasRole(IslandRole.Operator, targetPlayerUUID) || island.hasRole(IslandRole.Owner, targetPlayerUUID)) { - messageManager.sendMessage(player, configLoad.getString("Command.Island.Ban.Member.Message")); - soundManager.playSound(player, Sounds.ANVIL_LAND.bukkitSound(), 1.0F, 1.0F); - } else if (island.getBan().isBanned(targetPlayerUUID)) { - messageManager.sendMessage(player, configLoad.getString("Command.Island.Ban.Already.Message")); - soundManager.playSound(player, Sounds.ANVIL_LAND.bukkitSound(), 1.0F, 1.0F); - } else { - messageManager.sendMessage(player, - configLoad.getString("Command.Island.Ban.Banned.Sender.Message").replace("%player", - targetPlayerName)); - soundManager.playSound(player, Sounds.IRONGOLEM_HIT.bukkitSound(), 1.0F, 1.0F); + messageManager.sendMessage(player, configLoad.getString("Command.Island.Ban.Member.Message")); + soundManager.playSound(player, Sounds.ANVIL_LAND.bukkitSound(), 1.0F, 1.0F); + } else + if (island.getBan().isBanned(targetPlayerUUID)) { + messageManager.sendMessage(player, configLoad.getString("Command.Island.Ban.Already.Message")); + soundManager.playSound(player, Sounds.ANVIL_LAND.bukkitSound(), 1.0F, 1.0F); + } else { + messageManager.sendMessage(player, configLoad.getString("Command.Island.Ban.Banned.Sender.Message").replace("%player", targetPlayerName)); + soundManager.playSound(player, Sounds.IRONGOLEM_HIT.bukkitSound(), 1.0F, 1.0F); - if (island.isCoopPlayer(targetPlayerUUID)) { - island.removeCoopPlayer(targetPlayerUUID); - } + if (island.isCoopPlayer(targetPlayerUUID)) { + island.removeCoopPlayer(targetPlayerUUID); + } - Ban ban = island.getBan(); - ban.addBan(player.getUniqueId(), targetPlayerUUID); - ban.save(); + Ban ban = island.getBan(); + ban.addBan(player.getUniqueId(), targetPlayerUUID); + ban.save(); - if (targetPlayer != null) { - if (islandManager.isPlayerAtIsland(island, targetPlayer)) { - messageManager.sendMessage(targetPlayer, - configLoad.getString("Command.Island.Ban.Banned.Target.Message") - .replace("%player", player.getName())); - soundManager.playSound(targetPlayer, Sounds.IRONGOLEM_HIT.bukkitSound(), 1.0F, 1.0F); + if (targetPlayer != null) { + if (islandManager.isPlayerAtIsland(island, targetPlayer)) { + messageManager.sendMessage(targetPlayer, configLoad.getString("Command.Island.Ban.Banned.Target.Message").replace("%player", player.getName())); + soundManager.playSound(targetPlayer, Sounds.IRONGOLEM_HIT.bukkitSound(), 1.0F, 1.0F); - LocationUtil.teleportPlayerToSpawn(targetPlayer); + LocationUtil.teleportPlayerToSpawn(targetPlayer); + } } } - } } else { messageManager.sendMessage(player, configLoad.getString("Command.Island.Ban.Permission.Message")); soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); diff --git a/src/main/java/com/songoda/skyblock/command/commands/island/ConfirmCommand.java b/src/main/java/com/songoda/skyblock/command/commands/island/ConfirmCommand.java index a7dd627a..0ec12f61 100644 --- a/src/main/java/com/songoda/skyblock/command/commands/island/ConfirmCommand.java +++ b/src/main/java/com/songoda/skyblock/command/commands/island/ConfirmCommand.java @@ -165,12 +165,14 @@ public class ConfirmCommand extends SubCommand { } } - island.setDeleted(true); - islandManager.deleteIsland(island); - - messageManager.sendMessage(player, configLoad - .getString("Command.Island.Confirmation.Deletion.Sender.Message")); - soundManager.playSound(player, Sounds.EXPLODE.bukkitSound(), 10.0F, 10.0F); + if (islandManager.deleteIsland(island, false)) { + island.setDeleted(true); + messageManager.sendMessage(player, configLoad.getString("Command.Island.Confirmation.Deletion.Sender.Message")); + soundManager.playSound(player, Sounds.EXPLODE.bukkitSound(), 10.0F, 10.0F); + }else { + messageManager.sendMessage(player, configLoad.getString("Command.Island.Confirmation.Deletion.Sender.MaxDeletionMessage")); + soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1f, 1f); + } } } } else { diff --git a/src/main/java/com/songoda/skyblock/command/commands/island/KickCommand.java b/src/main/java/com/songoda/skyblock/command/commands/island/KickCommand.java index dd70fd9f..e098ab96 100644 --- a/src/main/java/com/songoda/skyblock/command/commands/island/KickCommand.java +++ b/src/main/java/com/songoda/skyblock/command/commands/island/KickCommand.java @@ -1,5 +1,16 @@ package com.songoda.skyblock.command.commands.island; +import java.io.File; +import java.io.IOException; +import java.util.Set; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.command.ConsoleCommandSender; +import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.Player; + import com.songoda.skyblock.api.event.island.IslandKickEvent; import com.songoda.skyblock.api.utils.APIUtil; import com.songoda.skyblock.command.SubCommand; @@ -8,7 +19,6 @@ import com.songoda.skyblock.config.FileManager.Config; import com.songoda.skyblock.island.Island; import com.songoda.skyblock.island.IslandManager; import com.songoda.skyblock.island.IslandRole; -import com.songoda.skyblock.island.IslandWorld; import com.songoda.skyblock.message.MessageManager; import com.songoda.skyblock.playerdata.PlayerData; import com.songoda.skyblock.playerdata.PlayerDataManager; @@ -18,16 +28,6 @@ import com.songoda.skyblock.sound.SoundManager; import com.songoda.skyblock.utils.player.OfflinePlayer; import com.songoda.skyblock.utils.version.Sounds; import com.songoda.skyblock.utils.world.LocationUtil; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.command.ConsoleCommandSender; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.entity.Player; - -import java.io.File; -import java.io.IOException; -import java.util.Set; -import java.util.UUID; public class KickCommand extends SubCommand { @@ -49,210 +49,174 @@ public class KickCommand extends SubCommand { Island island = islandManager.getIsland(player); if (island == null) { - messageManager.sendMessage(player, - languageConfig.getFileConfiguration().getString("Command.Island.Kick.Owner.Message")); + messageManager.sendMessage(player, languageConfig.getFileConfiguration().getString("Command.Island.Kick.Owner.Message")); soundManager.playSound(player, Sounds.ANVIL_LAND.bukkitSound(), 1.0F, 1.0F); } else if (island.hasRole(IslandRole.Owner, player.getUniqueId()) - || (island.hasRole(IslandRole.Operator, player.getUniqueId()) - && island.getSetting(IslandRole.Operator, "Kick").getStatus())) { - UUID targetPlayerUUID = null; - String targetPlayerName = null; + || (island.hasRole(IslandRole.Operator, player.getUniqueId()) && island.getSetting(IslandRole.Operator, "Kick").getStatus())) { + UUID targetPlayerUUID = null; + String targetPlayerName = null; - Player targetPlayer = Bukkit.getServer().getPlayer(args[0]); + Player targetPlayer = Bukkit.getServer().getPlayer(args[0]); - if (targetPlayer != null && targetPlayer.hasPermission("fabledskyblock.bypass.ban")) - return; - - Set islandMembers = island.getRole(IslandRole.Member), - islandOperators = island.getRole(IslandRole.Operator), - islandVisitors = islandManager.getVisitorsAtIsland(island); - - if (targetPlayer == null) { - OfflinePlayer targetPlayerOffline = new OfflinePlayer(args[0]); - targetPlayerUUID = targetPlayerOffline.getUniqueId(); - targetPlayerName = targetPlayerOffline.getName(); - - if (skyblock.getEconomyManager().hasPermission(skyblock.getWorldManager().getWorld(IslandWorld.Normal).getName(), Bukkit.getOfflinePlayer(targetPlayerUUID), "fabledskyblock.bypass.ban")) - return; - } else { - targetPlayerUUID = targetPlayer.getUniqueId(); - targetPlayerName = targetPlayer.getName(); - } - - if (targetPlayerUUID.equals(player.getUniqueId())) { - messageManager.sendMessage(player, - languageConfig.getFileConfiguration().getString("Command.Island.Kick.Yourself.Message")); - soundManager.playSound(player, Sounds.ANVIL_LAND.bukkitSound(), 1.0F, 1.0F); - } else if (islandOperators.contains(player.getUniqueId()) - && islandOperators.contains(targetPlayerUUID)) { - messageManager.sendMessage(player, languageConfig.getFileConfiguration() - .getString("Command.Island.Kick.Role.Operator.Message")); - soundManager.playSound(player, Sounds.ANVIL_LAND.bukkitSound(), 1.0F, 1.0F); - } else if (island.getOwnerUUID().equals(targetPlayerUUID)) { - messageManager.sendMessage(player, - languageConfig.getFileConfiguration().getString("Command.Island.Kick.Role.Owner.Message")); - soundManager.playSound(player, Sounds.ANVIL_LAND.bukkitSound(), 1.0F, 1.0F); - } else if (island.isOpen() && islandVisitors.contains(targetPlayerUUID) && targetPlayer != null) { - if (island.isCoopPlayer(targetPlayerUUID)) { - messageManager.sendMessage(player, - languageConfig.getFileConfiguration().getString("Command.Island.Kick.Cooped.Message")); - soundManager.playSound(player, Sounds.ANVIL_LAND.bukkitSound(), 1.0F, 1.0F); - } else { - IslandKickEvent islandKickEvent = new IslandKickEvent(island.getAPIWrapper(), - APIUtil.fromImplementation(IslandRole.Visitor), - Bukkit.getServer().getOfflinePlayer(targetPlayerUUID), player); - - Bukkit.getScheduler().runTask(skyblock, () -> Bukkit.getServer().getPluginManager().callEvent(islandKickEvent)); - - if (!islandKickEvent.isCancelled()) { - LocationUtil.teleportPlayerToSpawn(targetPlayer); - - messageManager.sendMessage(player, - languageConfig.getFileConfiguration() - .getString("Command.Island.Kick.Kicked.Sender.Message") - .replace("%player", targetPlayerName)); - soundManager.playSound(player, Sounds.IRONGOLEM_HIT.bukkitSound(), 1.0F, 1.0F); - - messageManager.sendMessage(targetPlayer, - languageConfig.getFileConfiguration() - .getString("Command.Island.Kick.Kicked.Target.Message") - .replace("%player", player.getName())); - soundManager.playSound(targetPlayer, Sounds.IRONGOLEM_HIT.bukkitSound(), 1.0F, 1.0F); - } - } - } else if (islandMembers.contains(targetPlayerUUID) || islandOperators.contains(targetPlayerUUID)) { - IslandRole islandRole = IslandRole.Member; - - if (islandOperators.contains(targetPlayerUUID)) { - islandRole = IslandRole.Operator; - } - - IslandKickEvent islandKickEvent = new IslandKickEvent(island.getAPIWrapper(), - APIUtil.fromImplementation(islandRole), - Bukkit.getServer().getOfflinePlayer(targetPlayerUUID), player); - - Bukkit.getScheduler().runTask(skyblock, () -> Bukkit.getServer().getPluginManager().callEvent(islandKickEvent)); - - if (!islandKickEvent.isCancelled()) { - messageManager.sendMessage(player, - languageConfig.getFileConfiguration() - .getString("Command.Island.Kick.Kicked.Sender.Message") - .replace("%player", targetPlayerName)); - soundManager.playSound(player, Sounds.IRONGOLEM_HIT.bukkitSound(), 1.0F, 1.0F); + Set islandMembers = island.getRole(IslandRole.Member), islandOperators = island.getRole(IslandRole.Operator), + islandVisitors = islandManager.getVisitorsAtIsland(island); if (targetPlayer == null) { - Config config = fileManager - .getConfig(new File(new File(skyblock.getDataFolder().toString() + "/player-data"), - targetPlayerUUID.toString() + ".yml")); - FileConfiguration configLoad = config.getFileConfiguration(); - - configLoad.set("Statistics.Island.Playtime", null); - configLoad.set("Statistics.Island.Join", null); - configLoad.set("Island.Owner", null); - - try { - configLoad.save(config.getFile()); - } catch (IOException e) { - e.printStackTrace(); - } + OfflinePlayer targetPlayerOffline = new OfflinePlayer(args[0]); + targetPlayerUUID = targetPlayerOffline.getUniqueId(); + targetPlayerName = targetPlayerOffline.getName(); } else { - messageManager.sendMessage(targetPlayer, - languageConfig.getFileConfiguration() - .getString("Command.Island.Kick.Kicked.Target.Message") - .replace("%player", player.getName())); - soundManager.playSound(targetPlayer, Sounds.IRONGOLEM_HIT.bukkitSound(), 1.0F, 1.0F); - - if (islandManager.isPlayerAtIsland(island, targetPlayer)) { - LocationUtil.teleportPlayerToSpawn(targetPlayer); - } - - if (scoreboardManager != null) { - Scoreboard scoreboard = scoreboardManager.getScoreboard(targetPlayer); - scoreboard.setDisplayName(ChatColor.translateAlternateColorCodes('&', languageConfig - .getFileConfiguration().getString("Scoreboard.Tutorial.Displayname"))); - scoreboard.setDisplayList(languageConfig.getFileConfiguration() - .getStringList("Scoreboard.Tutorial.Displaylines")); - scoreboard.run(); - } - - playerData = playerDataManager.getPlayerData(targetPlayer); - playerData.setPlaytime(0); - playerData.setMemberSince(null); - playerData.setOwner(null); - playerData.setChat(false); - playerData.save(); + targetPlayerUUID = targetPlayer.getUniqueId(); + targetPlayerName = targetPlayer.getName(); } - if (islandMembers.contains(targetPlayerUUID)) { - island.removeRole(IslandRole.Member, targetPlayerUUID); - } else if (islandOperators.contains(targetPlayerUUID)) { - island.removeRole(IslandRole.Operator, targetPlayerUUID); - } + if (targetPlayerUUID.equals(player.getUniqueId())) { + messageManager.sendMessage(player, languageConfig.getFileConfiguration().getString("Command.Island.Kick.Yourself.Message")); + soundManager.playSound(player, Sounds.ANVIL_LAND.bukkitSound(), 1.0F, 1.0F); + } else if (islandOperators.contains(player.getUniqueId()) && islandOperators.contains(targetPlayerUUID)) { + messageManager.sendMessage(player, languageConfig.getFileConfiguration().getString("Command.Island.Kick.Role.Operator.Message")); + soundManager.playSound(player, Sounds.ANVIL_LAND.bukkitSound(), 1.0F, 1.0F); + } else if (island.getOwnerUUID().equals(targetPlayerUUID)) { + messageManager.sendMessage(player, languageConfig.getFileConfiguration().getString("Command.Island.Kick.Role.Owner.Message")); + soundManager.playSound(player, Sounds.ANVIL_LAND.bukkitSound(), 1.0F, 1.0F); + } else if (island.isOpen() && islandVisitors.contains(targetPlayerUUID) && targetPlayer != null) { + if (island.isCoopPlayer(targetPlayerUUID)) { + messageManager.sendMessage(player, languageConfig.getFileConfiguration().getString("Command.Island.Kick.Cooped.Message")); + soundManager.playSound(player, Sounds.ANVIL_LAND.bukkitSound(), 1.0F, 1.0F); + } else { + IslandKickEvent islandKickEvent = new IslandKickEvent(island.getAPIWrapper(), APIUtil.fromImplementation(IslandRole.Visitor), + Bukkit.getServer().getOfflinePlayer(targetPlayerUUID), player); - island.save(); + Bukkit.getScheduler().runTask(skyblock, () -> Bukkit.getServer().getPluginManager().callEvent(islandKickEvent)); - Set islandMembersOnline = islandManager.getMembersOnline(island); + if (!islandKickEvent.isCancelled()) { + LocationUtil.teleportPlayerToSpawn(targetPlayer); - if (islandMembersOnline.size() == 1) { - for (UUID islandMembersOnlineList : islandMembersOnline) { - if (!islandMembersOnlineList.equals(player.getUniqueId())) { - targetPlayer = Bukkit.getServer().getPlayer(islandMembersOnlineList); - PlayerData targetPlayerData = playerDataManager.getPlayerData(targetPlayer); + messageManager.sendMessage(player, + languageConfig.getFileConfiguration().getString("Command.Island.Kick.Kicked.Sender.Message").replace("%player", targetPlayerName)); + soundManager.playSound(player, Sounds.IRONGOLEM_HIT.bukkitSound(), 1.0F, 1.0F); - if (targetPlayerData.isChat()) { - targetPlayerData.setChat(false); - messageManager.sendMessage(targetPlayer, fileManager - .getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Chat.Untoggled.Message")); + messageManager.sendMessage(targetPlayer, + languageConfig.getFileConfiguration().getString("Command.Island.Kick.Kicked.Target.Message").replace("%player", player.getName())); + soundManager.playSound(targetPlayer, Sounds.IRONGOLEM_HIT.bukkitSound(), 1.0F, 1.0F); + } + } + } else if (islandMembers.contains(targetPlayerUUID) || islandOperators.contains(targetPlayerUUID)) { + IslandRole islandRole = IslandRole.Member; + + if (islandOperators.contains(targetPlayerUUID)) { + islandRole = IslandRole.Operator; + } + + IslandKickEvent islandKickEvent = new IslandKickEvent(island.getAPIWrapper(), APIUtil.fromImplementation(islandRole), + Bukkit.getServer().getOfflinePlayer(targetPlayerUUID), player); + + Bukkit.getScheduler().runTask(skyblock, () -> Bukkit.getServer().getPluginManager().callEvent(islandKickEvent)); + + if (!islandKickEvent.isCancelled()) { + messageManager.sendMessage(player, + languageConfig.getFileConfiguration().getString("Command.Island.Kick.Kicked.Sender.Message").replace("%player", targetPlayerName)); + soundManager.playSound(player, Sounds.IRONGOLEM_HIT.bukkitSound(), 1.0F, 1.0F); + + if (targetPlayer == null) { + Config config = fileManager.getConfig(new File(new File(skyblock.getDataFolder().toString() + "/player-data"), targetPlayerUUID.toString() + ".yml")); + FileConfiguration configLoad = config.getFileConfiguration(); + + configLoad.set("Statistics.Island.Playtime", null); + configLoad.set("Statistics.Island.Join", null); + configLoad.set("Island.Owner", null); + + try { + configLoad.save(config.getFile()); + } catch (IOException e) { + e.printStackTrace(); + } + } else { + messageManager.sendMessage(targetPlayer, + languageConfig.getFileConfiguration().getString("Command.Island.Kick.Kicked.Target.Message").replace("%player", player.getName())); + soundManager.playSound(targetPlayer, Sounds.IRONGOLEM_HIT.bukkitSound(), 1.0F, 1.0F); + + if (islandManager.isPlayerAtIsland(island, targetPlayer)) { + LocationUtil.teleportPlayerToSpawn(targetPlayer); + } + + if (scoreboardManager != null) { + Scoreboard scoreboard = scoreboardManager.getScoreboard(targetPlayer); + scoreboard.setDisplayName( + ChatColor.translateAlternateColorCodes('&', languageConfig.getFileConfiguration().getString("Scoreboard.Tutorial.Displayname"))); + scoreboard.setDisplayList(languageConfig.getFileConfiguration().getStringList("Scoreboard.Tutorial.Displaylines")); + scoreboard.run(); + } + + playerData = playerDataManager.getPlayerData(targetPlayer); + playerData.setPlaytime(0); + playerData.setMemberSince(null); + playerData.setOwner(null); + playerData.setChat(false); + playerData.save(); + } + + if (islandMembers.contains(targetPlayerUUID)) { + island.removeRole(IslandRole.Member, targetPlayerUUID); + } else if (islandOperators.contains(targetPlayerUUID)) { + island.removeRole(IslandRole.Operator, targetPlayerUUID); + } + + island.save(); + + Set islandMembersOnline = islandManager.getMembersOnline(island); + + if (islandMembersOnline.size() == 1) { + for (UUID islandMembersOnlineList : islandMembersOnline) { + if (!islandMembersOnlineList.equals(player.getUniqueId())) { + targetPlayer = Bukkit.getServer().getPlayer(islandMembersOnlineList); + PlayerData targetPlayerData = playerDataManager.getPlayerData(targetPlayer); + + if (targetPlayerData.isChat()) { + targetPlayerData.setChat(false); + messageManager.sendMessage(targetPlayer, fileManager.getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration() + .getString("Island.Chat.Untoggled.Message")); + } + } + } + } + + if (scoreboardManager != null) { + if (island.getRole(IslandRole.Member).size() == 0 && island.getRole(IslandRole.Operator).size() == 0) { + Scoreboard scoreboard = scoreboardManager.getScoreboard(player); + scoreboard.setDisplayName( + ChatColor.translateAlternateColorCodes('&', languageConfig.getFileConfiguration().getString("Scoreboard.Island.Solo.Displayname"))); + + if (islandManager.getVisitorsAtIsland(island).size() == 0) { + scoreboard.setDisplayList(languageConfig.getFileConfiguration().getStringList("Scoreboard.Island.Solo.Empty.Displaylines")); + } else { + scoreboard.setDisplayList(languageConfig.getFileConfiguration().getStringList("Scoreboard.Island.Solo.Occupied.Displaylines")); + } + + scoreboard.run(); } } } - } - - if (scoreboardManager != null) { - if (island.getRole(IslandRole.Member).size() == 0 - && island.getRole(IslandRole.Operator).size() == 0) { - Scoreboard scoreboard = scoreboardManager.getScoreboard(player); - scoreboard.setDisplayName(ChatColor.translateAlternateColorCodes('&', languageConfig - .getFileConfiguration().getString("Scoreboard.Island.Solo.Displayname"))); - - if (islandManager.getVisitorsAtIsland(island).size() == 0) { - scoreboard.setDisplayList(languageConfig.getFileConfiguration() - .getStringList("Scoreboard.Island.Solo.Empty.Displaylines")); - } else { - scoreboard.setDisplayList(languageConfig.getFileConfiguration() - .getStringList("Scoreboard.Island.Solo.Occupied.Displaylines")); - } - - scoreboard.run(); + } else { + if (island.isOpen()) { + messageManager.sendMessage(player, languageConfig.getFileConfiguration().getString("Command.Island.Kick.Occupant.Visit.Open.Message")); + } else { + messageManager.sendMessage(player, languageConfig.getFileConfiguration().getString("Command.Island.Kick.Occupant.Visit.Closed.Message")); } + + soundManager.playSound(player, Sounds.ANVIL_LAND.bukkitSound(), 1.0F, 1.0F); } - } - } else { - if (island.isOpen()) { - messageManager.sendMessage(player, languageConfig.getFileConfiguration() - .getString("Command.Island.Kick.Occupant.Visit.Open.Message")); } else { - messageManager.sendMessage(player, languageConfig.getFileConfiguration() - .getString("Command.Island.Kick.Occupant.Visit.Closed.Message")); + if (island.isOpen()) { + messageManager.sendMessage(player, languageConfig.getFileConfiguration().getString("Command.Island.Kick.Permission.Visit.Open.Message")); + } else { + messageManager.sendMessage(player, languageConfig.getFileConfiguration().getString("Command.Island.Kick.Permission.Visit.Closed.Message")); + } + + soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); } - - soundManager.playSound(player, Sounds.ANVIL_LAND.bukkitSound(), 1.0F, 1.0F); - } - } else { - if (island.isOpen()) { - messageManager.sendMessage(player, languageConfig.getFileConfiguration() - .getString("Command.Island.Kick.Permission.Visit.Open.Message")); - } else { - messageManager.sendMessage(player, languageConfig.getFileConfiguration() - .getString("Command.Island.Kick.Permission.Visit.Closed.Message")); - } - - soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); - } } else { - messageManager.sendMessage(player, - languageConfig.getFileConfiguration().getString("Command.Island.Kick.Invalid.Message")); + messageManager.sendMessage(player, languageConfig.getFileConfiguration().getString("Command.Island.Kick.Invalid.Message")); soundManager.playSound(player, Sounds.ANVIL_LAND.bukkitSound(), 1.0F, 1.0F); } }); diff --git a/src/main/java/com/songoda/skyblock/generator/GeneratorManager.java b/src/main/java/com/songoda/skyblock/generator/GeneratorManager.java index d718d430..6960ec6d 100644 --- a/src/main/java/com/songoda/skyblock/generator/GeneratorManager.java +++ b/src/main/java/com/songoda/skyblock/generator/GeneratorManager.java @@ -114,9 +114,8 @@ public class GeneratorManager { @SuppressWarnings("deprecation") public BlockState generateBlock(Generator generator, Block block) { Materials materials = getRandomMaterials(generator); - if (materials == null) - return block.getState(); - + if (materials == null) return block.getState(); + skyblock.getSoundManager().playSound(block.getLocation(), Sounds.FIZZ.bukkitSound(), 1.0F, 10.0F); if (NMSUtil.getVersionNumber() > 12) { @@ -127,8 +126,7 @@ public class GeneratorManager { try { block.getClass().getMethod("setData", byte.class).invoke(block, (byte) is.getDurability()); - } catch (IllegalAccessException | IllegalArgumentException - | InvocationTargetException | NoSuchMethodException | SecurityException e) { + } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { e.printStackTrace(); } } diff --git a/src/main/java/com/songoda/skyblock/island/IslandManager.java b/src/main/java/com/songoda/skyblock/island/IslandManager.java index ebeb0190..410307a7 100644 --- a/src/main/java/com/songoda/skyblock/island/IslandManager.java +++ b/src/main/java/com/songoda/skyblock/island/IslandManager.java @@ -52,6 +52,7 @@ import com.songoda.skyblock.structure.StructureManager; import com.songoda.skyblock.upgrade.Upgrade; import com.songoda.skyblock.upgrade.UpgradeManager; import com.songoda.skyblock.utils.player.OfflinePlayer; +import com.songoda.skyblock.utils.player.PlayerUtil; import com.songoda.skyblock.utils.structure.SchematicUtil; import com.songoda.skyblock.utils.structure.StructureUtil; import com.songoda.skyblock.utils.version.Materials; @@ -162,6 +163,21 @@ public class IslandManager { FileManager fileManager = skyblock.getFileManager(); BanManager banManager = skyblock.getBanManager(); + PlayerData data = skyblock.getPlayerDataManager().getPlayerData(player); + + long amt = 0; + + if (data != null) { + final int highest = PlayerUtil.getNumberFromPermission(player, "fabledskyblock.limit.create", true, 2); + + if ((amt = data.getIslandCreationCount()) >= highest) { + skyblock.getMessageManager().sendMessage(player, + fileManager.getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration().getString("Island.Creator.Error.MaxCreationMessage")); + return false; + } + + } + if (fileManager.getConfig(new File(skyblock.getDataFolder(), "locations.yml")).getFileConfiguration().getString("Location.Spawn") == null) { skyblock.getMessageManager().sendMessage(player, fileManager.getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration().getString("Island.Creator.Error.Message")); @@ -170,6 +186,8 @@ public class IslandManager { return false; } + data.setIslandCreationCount(amt + 1); + Island island = new Island(player); island.setStructure(structure.getName()); islandStorage.put(player.getUniqueId(), island); @@ -231,12 +249,6 @@ public class IslandManager { } Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(skyblock, () -> { - if (structure.getCommands() != null) { - for (String commandList : structure.getCommands()) { - Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), commandList.replace("%player", player.getName())); - } - } - player.teleport(island.getLocation(IslandWorld.Normal, IslandEnvironment.Main)); player.setFallDistance(0.0F); }, configLoad.getInt("Island.Creation.TeleportTimeout") * 20); @@ -250,7 +262,14 @@ public class IslandManager { } Biome biome = sBiome.getBiome(); - Bukkit.getServer().getScheduler().runTaskLater(skyblock, () -> skyblock.getBiomeManager().setBiome(island, biome), 20L); + Bukkit.getServer().getScheduler().runTaskLater(skyblock, () -> { + skyblock.getBiomeManager().setBiome(island, biome); + if (structure.getCommands() != null) { + for (String commandList : structure.getCommands()) { + Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), commandList.replace("%player", player.getName())); + } + } + }, 20L); // Recalculate island level after 5 seconds if (configLoad.getBoolean("Island.Levelling.ScanAutomatically")) @@ -373,14 +392,31 @@ public class IslandManager { int j = 0; - public void deleteIsland(Island island) { + public boolean deleteIsland(Island island, boolean force) { ScoreboardManager scoreboardManager = skyblock.getScoreboardManager(); PlayerDataManager playerDataManager = skyblock.getPlayerDataManager(); CooldownManager cooldownManager = skyblock.getCooldownManager(); FileManager fileManager = skyblock.getFileManager(); WorldManager worldManager = skyblock.getWorldManager(); - // Delete island from world. + if (!force) { + PlayerData data = playerDataManager.getPlayerData(island.getOwnerUUID()); + + if (data != null) { + + final Player player = data.getPlayer(); + + if (player != null) { + + long amt = 0; + final int highest = PlayerUtil.getNumberFromPermission(player, "fabledskyblock.limit.delete", true, 1); + + if ((amt = data.getIslandDeletionCount()) >= highest) return false; + + data.setIslandDeletionCount(amt + 1); + } + } + } final Map> snapshots = new HashMap<>(3); @@ -462,6 +498,7 @@ public class IslandManager { Bukkit.getServer().getPluginManager().callEvent(new IslandDeleteEvent(island.getAPIWrapper())); islandStorage.remove(island.getOwnerUUID()); + return true; } public void deleteIslandData(UUID uuid) { @@ -1171,16 +1208,17 @@ public class IslandManager { } public Set getCoopPlayersAtIsland(Island island) { - Set coopPlayersAtIsland = new HashSet<>(); + final Set coopPlayersAtIsland = new HashSet<>(); - if (island != null) { - for (Player all : Bukkit.getOnlinePlayers()) { - if (island.getCoopPlayers().containsKey(all.getUniqueId())) { - if (isPlayerAtIsland(island, all)) { - coopPlayersAtIsland.add(all.getUniqueId()); - } - } - } + if (island == null) return coopPlayersAtIsland; + + for (UUID coopUUID : island.getCoopPlayers().keySet()) { + + final Player player = Bukkit.getPlayer(coopUUID); + + if (player == null) continue; + + if (isPlayerAtIsland(island, player)) coopPlayersAtIsland.add(coopUUID); } return coopPlayersAtIsland; diff --git a/src/main/java/com/songoda/skyblock/leaderboard/LeaderboardManager.java b/src/main/java/com/songoda/skyblock/leaderboard/LeaderboardManager.java index dc6919d6..2cda71d8 100644 --- a/src/main/java/com/songoda/skyblock/leaderboard/LeaderboardManager.java +++ b/src/main/java/com/songoda/skyblock/leaderboard/LeaderboardManager.java @@ -28,8 +28,7 @@ public class LeaderboardManager { this.skyblock = skyblock; new LeaderboardTask(skyblock).runTaskTimerAsynchronously(skyblock, 0L, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")) - .getFileConfiguration().getInt("Island.Leaderboard.Reset.Time") * 20); + skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration().getInt("Island.Leaderboard.Reset.Time") * 20); resetLeaderboard(); setupLeaderHeads(); @@ -43,18 +42,16 @@ public class LeaderboardManager { visitManager.loadIslands(); int arraySize = visitManager.getIslands().size(); - + List islandLevels = new ArrayList<>(arraySize); List islandBanks = new ArrayList<>(arraySize); List islandVotes = new ArrayList<>(arraySize); - boolean enableExemptions = skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")) - .getFileConfiguration().getBoolean("Island.Leaderboard.Exemptions.Enable"); + boolean enableExemptions = skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration() + .getBoolean("Island.Leaderboard.Exemptions.Enable"); for (UUID ownerUUID : visitManager.getIslands().keySet()) { - if (enableExemptions && economyManager.hasPermission(worldManager.getWorld(IslandWorld.Normal).getName(), - Bukkit.getOfflinePlayer(ownerUUID), - "fabledskyblock.top.exempt")) + if (enableExemptions && economyManager.hasPermission(worldManager.getWorld(IslandWorld.Normal).getName(), Bukkit.getOfflinePlayer(ownerUUID), "fabledskyblock.top.exempt")) continue; Visit visit = visitManager.getIslands().get(ownerUUID); @@ -92,23 +89,23 @@ public class LeaderboardManager { List leaderboardPlayers = new ArrayList<>(visitManager.getIslands().size()); switch (type) { - case Level: - for (UUID ownerUUID : visitManager.getIslands().keySet()) { - Visit visit = visitManager.getIslands().get(ownerUUID); - leaderboardPlayers.add(new LeaderboardPlayer(ownerUUID, visit.getLevel().getLevel())); - } - break; - case Bank: - for (UUID ownerUUID : visitManager.getIslands().keySet()) { - Visit visit = visitManager.getIslands().get(ownerUUID); - leaderboardPlayers.add(new LeaderboardPlayer(ownerUUID, (long) visit.getBankBalance())); - } - case Votes: - for (UUID ownerUUID : visitManager.getIslands().keySet()) { - Visit visit = visitManager.getIslands().get(ownerUUID); - leaderboardPlayers.add(new LeaderboardPlayer(ownerUUID, visit.getVoters().size())); - } - break; + case Level: + for (UUID ownerUUID : visitManager.getIslands().keySet()) { + Visit visit = visitManager.getIslands().get(ownerUUID); + leaderboardPlayers.add(new LeaderboardPlayer(ownerUUID, visit.getLevel().getLevel())); + } + break; + case Bank: + for (UUID ownerUUID : visitManager.getIslands().keySet()) { + Visit visit = visitManager.getIslands().get(ownerUUID); + leaderboardPlayers.add(new LeaderboardPlayer(ownerUUID, (long) visit.getBankBalance())); + } + case Votes: + for (UUID ownerUUID : visitManager.getIslands().keySet()) { + Visit visit = visitManager.getIslands().get(ownerUUID); + leaderboardPlayers.add(new LeaderboardPlayer(ownerUUID, visit.getVoters().size())); + } + break; } leaderboardPlayers.sort(Comparator.comparingLong(LeaderboardPlayer::getValue).reversed()); diff --git a/src/main/java/com/songoda/skyblock/leaderboard/leaderheads/TopLevel.java b/src/main/java/com/songoda/skyblock/leaderboard/leaderheads/TopLevel.java index 19d110d5..cb3e6883 100644 --- a/src/main/java/com/songoda/skyblock/leaderboard/leaderheads/TopLevel.java +++ b/src/main/java/com/songoda/skyblock/leaderboard/leaderheads/TopLevel.java @@ -17,9 +17,7 @@ public class TopLevel extends DataCollector { public TopLevel(SkyBlock skyblock) { super("toplevels", skyblock.getDescription().getName(), BoardType.DEFAULT, "&bTop Level", "toplevel", - Arrays.asList(ChatColor.DARK_GRAY + "-=+=-", ChatColor.AQUA + "{name}", - ChatColor.WHITE + "{amount} Level", ChatColor.DARK_GRAY + "-=+=-"), - true, UUID.class); + Arrays.asList(ChatColor.DARK_GRAY + "-=+=-", ChatColor.AQUA + "{name}", ChatColor.WHITE + "{amount} Level", ChatColor.DARK_GRAY + "-=+=-"), true, UUID.class); this.skyblock = skyblock; } diff --git a/src/main/java/com/songoda/skyblock/levelling/rework/IslandLevelManager.java b/src/main/java/com/songoda/skyblock/levelling/rework/IslandLevelManager.java index 13dbbb30..e139049f 100644 --- a/src/main/java/com/songoda/skyblock/levelling/rework/IslandLevelManager.java +++ b/src/main/java/com/songoda/skyblock/levelling/rework/IslandLevelManager.java @@ -27,6 +27,7 @@ import com.songoda.skyblock.levelling.rework.calculator.impl.EpicSpawnerCalculat import com.songoda.skyblock.levelling.rework.calculator.impl.UltimateStackerCalculator; import com.songoda.skyblock.levelling.rework.calculator.impl.WildStackerCalculator; import com.songoda.skyblock.message.MessageManager; +import com.songoda.skyblock.stackable.StackableManager; import com.songoda.skyblock.utils.version.Materials; import com.songoda.skyblock.utils.version.NMSUtil; @@ -63,12 +64,12 @@ public final class IslandLevelManager { } if (attemptScanner != null) { - - if(SkyBlock.getInstance().getIslandManager().getIslandPlayerAt(attemptScanner) != island) { + + if (SkyBlock.getInstance().getIslandManager().getIslandPlayerAt(attemptScanner) != island) { messageManager.sendMessage(attemptScanner, config.getString("Command.Island.Level.Scanning.NotOnIsland.Message")); return; } - + messageManager.sendMessage(attemptScanner, config.getString("Command.Island.Level.Scanning.Started.Message")); } @@ -164,7 +165,9 @@ public final class IslandLevelManager { if (finalType == Materials.SPAWNER) finalType = Materials.getSpawner(((CreatureSpawner) block.getState()).getSpawnedType()); final List calculators = CalculatorRegistry.getCalculators(blockType); - final long stackSize = SkyBlock.getInstance().getStackableManager().getStackSizeOf(block.getLocation(), blockType); + final StackableManager stackableManager = SkyBlock.getInstance().getStackableManager(); + + final long stackSize = stackableManager == null ? 0 : stackableManager.getStackSizeOf(block.getLocation(), blockType); if (calculators == null) { diff --git a/src/main/java/com/songoda/skyblock/levelling/rework/IslandScan.java b/src/main/java/com/songoda/skyblock/levelling/rework/IslandScan.java index 3ae2ce63..dd4a3e85 100644 --- a/src/main/java/com/songoda/skyblock/levelling/rework/IslandScan.java +++ b/src/main/java/com/songoda/skyblock/levelling/rework/IslandScan.java @@ -138,10 +138,13 @@ public final class IslandScan extends BukkitRunnable { if (config.getBoolean("Command.Island.Level.Scanning.Progress.Should-Display-Message") && executions == 1 || totalScanned == blocksSize || executions % runEveryX == 0) { + final double percent = ((double) totalScanned / (double) blocksSize) * 100; + String message = config.getString("Command.Island.Level.Scanning.Progress.Message"); message = message.replace("%current_scanned_blocks%", String.valueOf(totalScanned)); message = message.replace("%max_blocks%", String.valueOf(blocksSize)); - message = message.replace("%percent%", FORMATTER.format(((double) totalScanned / (double) blocksSize) * 100)); + message = message.replace("%percent_whole%", String.valueOf((int) percent)); + message = message.replace("%percent%", FORMATTER.format(percent)); final boolean displayComplete = totalScanned == blocksSize && config.getBoolean("Command.Island.Level.Scanning.Finished.Should-Display-Message"); final MessageManager messageManager = SkyBlock.getInstance().getMessageManager(); diff --git a/src/main/java/com/songoda/skyblock/limit/impl/BlockLimitation.java b/src/main/java/com/songoda/skyblock/limit/impl/BlockLimitation.java index 00333724..ace66ff4 100644 --- a/src/main/java/com/songoda/skyblock/limit/impl/BlockLimitation.java +++ b/src/main/java/com/songoda/skyblock/limit/impl/BlockLimitation.java @@ -3,17 +3,14 @@ package com.songoda.skyblock.limit.impl; import java.util.Locale; import java.util.Map; import java.util.Set; -import java.util.stream.Collectors; - import org.bukkit.block.Block; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.entity.Player; -import org.bukkit.permissions.PermissionAttachmentInfo; - import com.songoda.skyblock.SkyBlock; import com.songoda.skyblock.island.Island; import com.songoda.skyblock.island.IslandManager; import com.songoda.skyblock.limit.EnumLimitation; +import com.songoda.skyblock.utils.player.PlayerUtil; import com.songoda.skyblock.utils.version.Materials; public final class BlockLimitation extends EnumLimitation { @@ -46,7 +43,7 @@ public final class BlockLimitation extends EnumLimitation { final String enumName = key.toUpperCase(Locale.ENGLISH); final Materials type = Materials.fromString(enumName); - if (type == null) throw new IllegalArgumentException("Unable to parse Materials from '" + enumName + "' in " + loadFrom.getCurrentPath()); + if (type == null) throw new IllegalArgumentException("Unable to parse Materials from '" + enumName + "' in the Section '" + loadFrom.getCurrentPath() + "'"); getMap().put(type, loadFrom.getLong(key)); } @@ -63,25 +60,9 @@ public final class BlockLimitation extends EnumLimitation { if (material == null) return -1; - long limit = getMap().getOrDefault(material, getDefault()); - final String name = material.name().toLowerCase(); - Set permissions = player.getEffectivePermissions().stream() - .filter(x -> x.getPermission().toLowerCase().startsWith("fabledskyblock.limit.block." + name)).collect(Collectors.toSet()); - - for (PermissionAttachmentInfo permission : permissions) { - try { - String permString = permission.getPermission(); - String numberString = permString.substring(permString.lastIndexOf(".") + 1); - if (numberString.equals("*")) return -1; - - limit = Math.max(limit, Integer.parseInt(numberString)); - } catch (Exception ignored) { - } - } - - return limit; + return Math.max(getMap().getOrDefault(material, getDefault()), PlayerUtil.getNumberFromPermission(player, "fabledskyblock.limit.block." + name, true, -1)); } @SuppressWarnings("deprecation") @@ -94,8 +75,7 @@ public final class BlockLimitation extends EnumLimitation { final long totalPlaced; if (block.getType() == Materials.SPAWNER.parseMaterial()) { - totalPlaced = island.getLevel().getMaterials().entrySet().stream().filter(x -> x.getKey().contains("SPAWNER")) - .mapToLong(Map.Entry::getValue).sum(); + totalPlaced = island.getLevel().getMaterials().entrySet().stream().filter(x -> x.getKey().contains("SPAWNER")).mapToLong(Map.Entry::getValue).sum(); } else { totalPlaced = island.getLevel().getMaterialAmount(Materials.getMaterials(block.getType(), block.getData()).name()); } diff --git a/src/main/java/com/songoda/skyblock/listeners/Block.java b/src/main/java/com/songoda/skyblock/listeners/Block.java index c1573319..d7f1ed45 100644 --- a/src/main/java/com/songoda/skyblock/listeners/Block.java +++ b/src/main/java/com/songoda/skyblock/listeners/Block.java @@ -15,6 +15,7 @@ import org.bukkit.block.BlockFace; import org.bukkit.block.BlockState; import org.bukkit.block.CreatureSpawner; import org.bukkit.configuration.file.FileConfiguration; +import org.bukkit.entity.ArmorStand; import org.bukkit.entity.EntityType; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -55,585 +56,599 @@ import com.songoda.skyblock.world.WorldManager; public class Block implements Listener { - private final SkyBlock skyblock; - - public Block(SkyBlock skyblock) { - this.skyblock = skyblock; - } - - @SuppressWarnings("deprecation") - @EventHandler(priority = EventPriority.LOW) - public void onBlockBreak(BlockBreakEvent event) { - Player player = event.getPlayer(); - org.bukkit.block.Block block = event.getBlock(); - - IslandManager islandManager = skyblock.getIslandManager(); - StackableManager stackableManager = skyblock.getStackableManager(); - WorldManager worldManager = skyblock.getWorldManager(); - - if (!worldManager.isIslandWorld(block.getWorld())) return; - - IslandWorld world = worldManager.getIslandWorld(block.getWorld()); - - Location blockLocation = block.getLocation(); - - Island island = islandManager.getIslandAtLocation(blockLocation); - - if (island == null) { - event.setCancelled(true); - return; - } - - if (!islandManager.hasPermission(player, blockLocation, "Destroy")) { - event.setCancelled(true); - skyblock.getMessageManager().sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); - skyblock.getSoundManager().playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); - return; - } - - if (stackableManager != null - && stackableManager.isStacked(blockLocation)) { - Stackable stackable = stackableManager.getStack(block.getLocation(), block.getType()); - if (stackable != null) { - Material material = block.getType(); - byte data = block.getData(); - - int droppedAmount = 0; - if (event.getPlayer().isSneaking()) { - Location dropLoc = blockLocation.clone().add(0.5, 0.5, 0.5); - int count = stackable.getSize(); - droppedAmount = count; - while (count > 64) { - dropLoc.getWorld().dropItemNaturally(dropLoc, new ItemStack(material, 64, data)); - count -= 64; - } - dropLoc.getWorld().dropItemNaturally(dropLoc, new ItemStack(material, count, block.getData())); - block.setType(Material.AIR); - stackable.setSize(0); - } else { - block.getWorld().dropItemNaturally(blockLocation.clone().add(.5, 1, .5), new ItemStack(material, 1, data)); - stackable.takeOne(); - droppedAmount = 1; - } - - if (stackable.getSize() <= 1) { - stackableManager.removeStack(stackable); - } - - Config config = skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")); - FileConfiguration configLoad = config.getFileConfiguration(); - - if (configLoad.getBoolean("Island.Block.Level.Enable")) { - Materials materials = Materials.getMaterials(material, data); - if (materials != null) { - IslandLevel level = island.getLevel(); - - if (level.hasMaterial(materials.name())) { - long materialAmount = level.getMaterialAmount(materials.name()); - - if (materialAmount - droppedAmount <= 0) { - level.removeMaterial(materials.name()); - } else { - level.setMaterialAmount(materials.name(), materialAmount - droppedAmount); - } - } - } - } - - event.setCancelled(true); - } - } - - Config config = skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")); - FileConfiguration configLoad = config.getFileConfiguration(); - - if (LocationUtil.isLocationLocation(block.getLocation(), island.getLocation(world, IslandEnvironment.Main).clone().subtract(0.0D, 1.0D, 0.0D)) - || LocationUtil.isLocationLocation(block.getLocation(), island.getLocation(world, IslandEnvironment.Main).clone())) { - if (configLoad.getBoolean("Island.Spawn.Protection")) { - event.setCancelled(true); - skyblock.getMessageManager().sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.SpawnProtection.Break.Message")); - skyblock.getSoundManager().playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); - } - } - - if (event.isCancelled() || !configLoad.getBoolean("Island.Block.Level.Enable")) return; - - Materials materials = Materials.getMaterials(block.getType(), block.getData()); - - if (materials == null) return; - - IslandLevel level = island.getLevel(); - - if (!level.hasMaterial(materials.name())) return; - - long materialAmount = level.getMaterialAmount(materials.name()); - - if (materialAmount - 1 <= 0) { - level.removeMaterial(materials.name()); - } else { - level.setMaterialAmount(materials.name(), materialAmount - 1); - } - } - - @SuppressWarnings("deprecation") - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) - public void onBlockPlace(BlockPlaceEvent event) { - Player player = event.getPlayer(); - org.bukkit.block.Block block = event.getBlock(); - - IslandManager islandManager = skyblock.getIslandManager(); - WorldManager worldManager = skyblock.getWorldManager(); - IslandLevelManager levellingManager = skyblock.getLevellingManager(); - if (!worldManager.isIslandWorld(block.getWorld())) return; - - IslandWorld world = worldManager.getIslandWorld(block.getWorld()); - Island island = islandManager.getIslandAtLocation(block.getLocation()); - - if (island == null) { - event.setCancelled(true); - return; - } - - if (levellingManager.isScanning(island)) { - skyblock.getMessageManager().sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Command.Island.Level.Scanning.BlockPlacing.Message")); - event.setCancelled(true); - return; - } - - if (!islandManager.hasPermission(player, block.getLocation(), "Place")) { - event.setCancelled(true); - skyblock.getMessageManager().sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); - skyblock.getSoundManager().playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); - return; - } - Config config = skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")); - FileConfiguration configLoad = config.getFileConfiguration(); - - if (configLoad.getBoolean("Island.WorldBorder.Block") && block.getType() == Material.DISPENSER) { - if (!islandManager.isLocationAtIsland(island, block.getLocation(), world)) { - event.setCancelled(true); - } - } - - // Check spawn protection - if (configLoad.getBoolean("Island.Spawn.Protection")) { - boolean isObstructing = false; - // Directly on the block - if (LocationUtil.isLocationAffectingIslandSpawn(block.getLocation(), island, world)) { - isObstructing = true; - } - - // Specific check for beds - if (!isObstructing && event.getBlock().getState().getData() instanceof org.bukkit.material.Bed) { - BlockFace bedDirection = ((org.bukkit.material.Bed) event.getBlock().getState().getData()).getFacing(); - org.bukkit.block.Block bedBlock = block.getRelative(bedDirection); - if (LocationUtil.isLocationAffectingIslandSpawn(bedBlock.getLocation(), island, world)) - isObstructing = true; - } - - if (isObstructing) { - skyblock.getMessageManager().sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.SpawnProtection.Place.Message")); - skyblock.getSoundManager().playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); - - event.setCancelled(true); - return; - } - } - - BlockLimitation limits = skyblock.getLimitationHandler().getInstance(BlockLimitation.class); - - long limit = limits.getBlockLimit(player, block); - - if (limits.isBlockLimitExceeded(player, block, limit)) { - Materials material = Materials.getMaterials(block.getType(), block.getData()); - - skyblock.getMessageManager().sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Limit.Block.Exceeded.Message") - .replace("%type", WordUtils.capitalizeFully(material.name().replace("_", " "))) - .replace("%limit", NumberUtil.formatNumber(limit))); - skyblock.getSoundManager().playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); - - event.setCancelled(true); - return; - } - - if (!configLoad.getBoolean("Island.Block.Level.Enable")) - return; - - if (event.getBlock().getType() == Materials.END_PORTAL_FRAME.parseMaterial() - && event.getPlayer().getItemInHand().getType() == Materials.ENDER_EYE.parseMaterial()) return; - - // Fix a bug in Paper 1.8.8 when using ViaVersion on a 1.12.2 client. - // BUG: Player can infinitely increase their level by placing a block at their feet. - // It doesn't take the block away but still increments the level. - // This doesn't happen in Spigot, but does happen in PaperSpigot due to a BlockPlaceEvent being incorrectly fired. - // The solution is to wait a tick to make sure that the block was actually placed. - // This shouldn't cause any issues besides the task number being increased insanely fast. - Bukkit.getScheduler().runTask(skyblock, () -> { - Materials materials = Materials.getMaterials(block.getType(), block.getData()); - if (materials == null || materials == Materials.AIR) - return; - - if (materials.equals(Materials.SPAWNER)) { - if (Bukkit.getPluginManager().isPluginEnabled("EpicSpawners") || Bukkit.getPluginManager().isPluginEnabled("WildStacker")) - return; - - CreatureSpawner creatureSpawner = (CreatureSpawner) block.getState(); - EntityType spawnerType = creatureSpawner.getSpawnedType(); - materials = Materials.getSpawner(spawnerType); - } - - long materialAmount = 0; - IslandLevel level = island.getLevel(); - - if (level.hasMaterial(materials.name())) { - materialAmount = level.getMaterialAmount(materials.name()); - } - - level.setMaterialAmount(materials.name(), materialAmount + 1); - }); - } - - - @EventHandler - public void onBlockFromTo(BlockFromToEvent event) { - if (!skyblock.getWorldManager().isIslandWorld(event.getBlock().getWorld())) return; - - GeneratorManager generatorManager = skyblock.getGeneratorManager(); - IslandManager islandManager = skyblock.getIslandManager(); - WorldManager worldManager = skyblock.getWorldManager(); - - Island island = islandManager.getIslandAtLocation(event.getBlock().getLocation()); - IslandWorld world = worldManager.getIslandWorld(event.getBlock().getWorld()); - - Config config = skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")); - FileConfiguration configLoad = config.getFileConfiguration(); - - if (island == null) return; - - org.bukkit.block.Block block = event.getToBlock(); - - // Protect outside of border - if (!islandManager.isLocationAtIsland(island, block.getLocation(), world)) { - event.setCancelled(true); - return; - } - - // Protect spawn - if (LocationUtil.isLocationAffectingIslandSpawn(block.getLocation(), island, world) && configLoad.getBoolean("Island.Spawn.Protection")) { - event.setCancelled(true); - return; - } - - if (NMSUtil.getVersionNumber() < 12) { - if (generatorManager != null && generatorManager.getGenerators().size() > 0 && generatorManager.isGenerator(block)) { - List generators = new ArrayList<>(generatorManager.getGenerators()); - Collections.reverse(generators); // Use the highest generator available - - // Filter valid players on the island - Set possiblePlayers = new HashSet<>(); - for (Player p : Bukkit.getOnlinePlayers()) { - boolean isMember = island.hasRole(IslandRole.Owner, p.getUniqueId()) || - island.hasRole(IslandRole.Member, p.getUniqueId()) || - island.hasRole(IslandRole.Coop, p.getUniqueId()) || - island.hasRole(IslandRole.Operator, p.getUniqueId()); - if (isMember && islandManager.isLocationAtIsland(island, p.getLocation(), world)) { - possiblePlayers.add(p); - } - } - - // Find highest generator available - for (Generator generator : generators) { - for (Player p : possiblePlayers) { - if (generator.isPermission()) { - if (!p.hasPermission(generator.getPermission()) - && !p.hasPermission("fabledskyblock.generator.*") - && !p.hasPermission("fabledskyblock.*")) { - continue; - } - } - - org.bukkit.block.BlockState genState = generatorManager.generateBlock(generator, block); - event.getToBlock().getState().setType(genState.getType()); - event.getToBlock().getState().setData(genState.getData()); - - return; - } - } - } - } - } - - @EventHandler - public void onBlockPistonExtend(BlockPistonExtendEvent event) { - WorldManager worldManager = skyblock.getWorldManager(); - if (!worldManager.isIslandWorld(event.getBlock().getWorld())) - return; - - IslandManager islandManager = skyblock.getIslandManager(); - Island island = islandManager.getIslandAtLocation(event.getBlock().getLocation()); - if (island == null) - return; - - Config config = skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")); - FileConfiguration configLoad = config.getFileConfiguration(); - - IslandWorld world = worldManager.getIslandWorld(event.getBlock().getWorld()); - for (org.bukkit.block.Block block : event.getBlocks()) { - if (!islandManager.isLocationAtIsland(island, block.getLocation(), world) || !islandManager.isLocationAtIsland(island, block.getRelative(event.getDirection()).getLocation(), world)) { - event.setCancelled(true); - return; - } - - if (skyblock.getStackableManager() != null && skyblock.getStackableManager().isStacked(block.getLocation())) { - event.setCancelled(true); - return; - } - - if (configLoad.getBoolean("Island.Spawn.Protection")) { - // Check exact block - if (LocationUtil.isLocationAffectingIslandSpawn(block.getLocation(), island, world)) { - event.setCancelled(true); - return; - } - - // Check block in direction - if (LocationUtil.isLocationAffectingIslandSpawn(block.getRelative(event.getDirection()).getLocation(), island, world)) { - event.setCancelled(true); - return; - } - } - - if (!skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration().getBoolean("Island.Block.Piston.Connected.Extend")) { - if (block.getType() == Materials.PISTON.parseMaterial() || block.getType() == Materials.STICKY_PISTON.parseMaterial()) { - event.setCancelled(true); - return; - } - } - } - - // Check piston head - if (configLoad.getBoolean("Island.Spawn.Protection")) { - if (LocationUtil.isLocationAffectingIslandSpawn(event.getBlock().getRelative(event.getDirection()).getLocation(), island, world)) { - event.setCancelled(true); - } - } - } - - @EventHandler - public void onBlockPistonRetract(BlockPistonRetractEvent event) { - WorldManager worldManager = skyblock.getWorldManager(); - if (!skyblock.getWorldManager().isIslandWorld(event.getBlock().getWorld())) - return; - - IslandManager islandManager = skyblock.getIslandManager(); - Island island = islandManager.getIslandAtLocation(event.getBlock().getLocation()); - if (island == null) - return; - - Config config = skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")); - FileConfiguration configLoad = config.getFileConfiguration(); - - IslandWorld world = worldManager.getIslandWorld(event.getBlock().getWorld()); - for (org.bukkit.block.Block block : event.getBlocks()) { - if (!islandManager.isLocationAtIsland(island, block.getLocation(), world)) { - event.setCancelled(true); - return; - } - - if (skyblock.getStackableManager() != null && skyblock.getStackableManager().isStacked(block.getLocation())) { - event.setCancelled(true); - return; - } - - if (LocationUtil.isLocationAffectingIslandSpawn(block.getLocation(), island, world) && configLoad.getBoolean("Island.Spawn.Protection")) { - event.setCancelled(true); - return; - } - - if (!skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration().getBoolean("Island.Block.Piston.Connected.Retract")) { - if (block.getType() == Materials.PISTON.parseMaterial() || block.getType() == Materials.STICKY_PISTON.parseMaterial()) { - event.setCancelled(true); - return; - } - } - } - } - - @EventHandler - public void onBlockForm(BlockFormEvent event) { - org.bukkit.block.Block block = event.getBlock(); - WorldManager worldManager = skyblock.getWorldManager(); - if (!worldManager.isIslandWorld(block.getWorld())) - return; - - // Check ice/snow forming - if (block.getType() == Material.ICE || block.getType() == Material.SNOW) { - if (!skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration().getBoolean("Island.Weather.IceAndSnow")) - event.setCancelled(true); - return; - } - - IslandManager islandManager = skyblock.getIslandManager(); - Island island = islandManager.getIslandAtLocation(block.getLocation()); - if (island == null) - return; - - // Check spawn block protection - IslandWorld world = worldManager.getIslandWorld(block.getWorld()); - if (LocationUtil.isLocationAffectingIslandSpawn(block.getLocation(), island, world)) { - if (skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration().getBoolean("Island.Spawn.Protection")) { - event.setCancelled(true); - return; - } - } - - Material material = block.getType(); - if (material != Materials.WATER.parseMaterial() && - material != Materials.LEGACY_STATIONARY_WATER.parseMaterial() && - material != Materials.LAVA.parseMaterial() && - material != Materials.LEGACY_STATIONARY_LAVA.parseMaterial()) - return; - - BlockState state = event.getNewState(); - Material type = state.getType(); - if (type != Material.COBBLESTONE && type != Material.STONE) - return; - - GeneratorManager generatorManager = skyblock.getGeneratorManager(); - if(generatorManager == null) return; + private final SkyBlock skyblock; + + public Block(SkyBlock skyblock) { + this.skyblock = skyblock; + } + + @SuppressWarnings("deprecation") + @EventHandler(priority = EventPriority.LOW) + public void onBlockBreak(BlockBreakEvent event) { + Player player = event.getPlayer(); + org.bukkit.block.Block block = event.getBlock(); + + IslandManager islandManager = skyblock.getIslandManager(); + StackableManager stackableManager = skyblock.getStackableManager(); + WorldManager worldManager = skyblock.getWorldManager(); + + if (!worldManager.isIslandWorld(block.getWorld())) return; + + Location blockLocation = block.getLocation(); + + Island island = islandManager.getIslandAtLocation(blockLocation); + + if (island == null) { + event.setCancelled(true); + return; + } + + if (!islandManager.hasPermission(player, blockLocation, "Destroy")) { + event.setCancelled(true); + skyblock.getMessageManager().sendMessage(player, + skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration().getString("Island.Settings.Permission.Message")); + skyblock.getSoundManager().playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); + return; + } + + if (stackableManager != null && stackableManager.isStacked(blockLocation)) { + Stackable stackable = stackableManager.getStack(block.getLocation(), block.getType()); + if (stackable != null) { + Material material = block.getType(); + byte data = block.getData(); + + int droppedAmount = 0; + if (event.getPlayer().isSneaking()) { + droppedAmount = stackable.getSize(); + block.getWorld().dropItemNaturally(blockLocation.clone().add(0.5, 0.5, 0.5), new ItemStack(material, droppedAmount, block.getData())); + block.setType(Material.AIR); + stackable.setSize(0); + } else { + block.getWorld().dropItemNaturally(blockLocation.clone().add(.5, 1, .5), new ItemStack(material, 1, data)); + stackable.takeOne(); + droppedAmount = 1; + } + + if (stackable.getSize() <= 1) { + stackableManager.removeStack(stackable); + } + + Config config = skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")); + FileConfiguration configLoad = config.getFileConfiguration(); + + if (configLoad.getBoolean("Island.Block.Level.Enable")) { + Materials materials = Materials.getMaterials(material, data); + if (materials != null) { + IslandLevel level = island.getLevel(); + + if (level.hasMaterial(materials.name())) { + long materialAmount = level.getMaterialAmount(materials.name()); + + if (materialAmount - droppedAmount <= 0) { + level.removeMaterial(materials.name()); + } else { + level.setMaterialAmount(materials.name(), materialAmount - droppedAmount); + } + } + } + } + + event.setCancelled(true); + } + } + + Config config = skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")); + FileConfiguration configLoad = config.getFileConfiguration(); + + IslandWorld world = worldManager.getIslandWorld(block.getWorld()); + + if (LocationUtil.isLocationLocation(block.getLocation(), island.getLocation(world, IslandEnvironment.Main).clone().subtract(0.0D, 1.0D, 0.0D)) + || LocationUtil.isLocationLocation(block.getLocation(), island.getLocation(world, IslandEnvironment.Main).clone())) { + if (configLoad.getBoolean("Island.Spawn.Protection")) { + event.setCancelled(true); + skyblock.getMessageManager().sendMessage(player, + skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration().getString("Island.SpawnProtection.Break.Message")); + skyblock.getSoundManager().playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); + } + } + + if (event.isCancelled() || !configLoad.getBoolean("Island.Block.Level.Enable")) return; + + final Materials materials; + + if (block.getType() == Materials.SPAWNER.parseMaterial()) { + materials = Materials.getSpawner(((CreatureSpawner) block.getState()).getSpawnedType()); + } else { + materials = Materials.getMaterials(block.getType(), block.getData()); + } + + if (materials == null) return; + + IslandLevel level = island.getLevel(); + + if (!level.hasMaterial(materials.name())) return; + + long materialAmount = level.getMaterialAmount(materials.name()); + + if (materialAmount - 1 <= 0) { + level.removeMaterial(materials.name()); + } else { + level.setMaterialAmount(materials.name(), materialAmount - 1); + } + } + + @SuppressWarnings("deprecation") + @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + public void onBlockPlace(BlockPlaceEvent event) { + Player player = event.getPlayer(); + org.bukkit.block.Block block = event.getBlock(); + + IslandManager islandManager = skyblock.getIslandManager(); + WorldManager worldManager = skyblock.getWorldManager(); + IslandLevelManager levellingManager = skyblock.getLevellingManager(); + if (!worldManager.isIslandWorld(block.getWorld())) return; + + Location blockLoc = block.getLocation(); - List generators = Lists.newArrayList(generatorManager.getGenerators()); - if(generators == null || generators.isEmpty()) return; - Collections.reverse(generators); // Use the highest generator available + Island island = islandManager.getIslandAtLocation(blockLoc); - // Filter valid players on the island. - Set possiblePlayers = new HashSet<>(); - for (Player player : Bukkit.getOnlinePlayers()) { - boolean isMember = island.hasRole(IslandRole.Owner, player.getUniqueId()) || - island.hasRole(IslandRole.Member, player.getUniqueId()) || - island.hasRole(IslandRole.Coop, player.getUniqueId()) || - island.hasRole(IslandRole.Operator, player.getUniqueId()); - if (isMember && islandManager.isLocationAtIsland(island, player.getLocation(), world)) { - possiblePlayers.add(player); - } - } + if (island == null) { + event.setCancelled(true); + return; + } - // Find highest generator available - for (Generator generator : generators) { - for (Player player : possiblePlayers) { - if (generator.isPermission()) { - if (!player.hasPermission(generator.getPermission()) - && !player.hasPermission("fabledskyblock.generator.*") - && !player.hasPermission("fabledskyblock.*")) { - continue; - } - } + if (levellingManager.isScanning(island)) { + skyblock.getMessageManager().sendMessage(player, skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration() + .getString("Command.Island.Level.Scanning.BlockPlacing.Message")); + event.setCancelled(true); + return; + } - org.bukkit.block.BlockState genState = generatorManager.generateBlock(generator, block); - state.setType(genState.getType()); + if (!islandManager.hasPermission(player, blockLoc, "Place")) { + event.setCancelled(true); + skyblock.getMessageManager().sendMessage(player, + skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration().getString("Island.Settings.Permission.Message")); + skyblock.getSoundManager().playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); + return; + } + + Config config = skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")); + FileConfiguration configLoad = config.getFileConfiguration(); + IslandWorld world = worldManager.getIslandWorld(block.getWorld()); + + if (configLoad.getBoolean("Island.WorldBorder.Block") && block.getType() == Material.DISPENSER) { + if (!islandManager.isLocationAtIsland(island, blockLoc, world)) { + event.setCancelled(true); + } + } - if (NMSUtil.getVersionNumber() < 13) - state.setData(genState.getData()); - return; - } - } - } + // Check spawn protection + if (configLoad.getBoolean("Island.Spawn.Protection")) { + boolean isObstructing = false; + // Directly on the block + if (LocationUtil.isLocationAffectingIslandSpawn(blockLoc, island, world)) { + isObstructing = true; + } - @EventHandler - public void onBlockBurn(BlockBurnEvent event) { - org.bukkit.block.Block block = event.getBlock(); - WorldManager worldManager = skyblock.getWorldManager(); - if (!worldManager.isIslandWorld(block.getWorld())) - return; - - IslandManager islandManager = skyblock.getIslandManager(); - if (!islandManager.hasSetting(block.getLocation(), IslandRole.Owner, "FireSpread")) - event.setCancelled(true); - } + // Specific check for beds + if (!isObstructing && event.getBlock().getState().getData() instanceof org.bukkit.material.Bed) { + BlockFace bedDirection = ((org.bukkit.material.Bed) event.getBlock().getState().getData()).getFacing(); + org.bukkit.block.Block bedBlock = block.getRelative(bedDirection); + if (LocationUtil.isLocationAffectingIslandSpawn(bedBlock.getLocation(), island, world)) isObstructing = true; + } - @EventHandler - public void onPortalCreate(PortalCreateEvent event) { - if (!skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration().getBoolean("Island.Spawn.Protection")) - return; + if (isObstructing) { + skyblock.getMessageManager().sendMessage(player, + skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration().getString("Island.SpawnProtection.Place.Message")); + skyblock.getSoundManager().playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); - WorldManager worldManager = skyblock.getWorldManager(); - IslandManager islandManager = skyblock.getIslandManager(); - // PortalCreateEvent.getBlocks() changed from ArrayList to ArrayList in 1.14.1 - if (NMSUtil.getVersionNumber() > 13) { - List blocks = event.getBlocks(); - if (event.getBlocks().isEmpty()) - return; + event.setCancelled(true); + return; + } + } - Island island = islandManager.getIslandAtLocation(event.getBlocks().get(0).getLocation()); - if (island == null) - return; + BlockLimitation limits = skyblock.getLimitationHandler().getInstance(BlockLimitation.class); - // Check spawn block protection - IslandWorld world = worldManager.getIslandWorld(event.getBlocks().get(0).getWorld()); + long limit = limits.getBlockLimit(player, block); - for (BlockState block : blocks) { - if (LocationUtil.isLocationAffectingIslandSpawn(block.getLocation(), island, world)) { - event.setCancelled(true); - return; - } - } - } else { - try { - @SuppressWarnings("unchecked") - List blocks = (List) event.getClass().getMethod("getBlocks").invoke(event); - if (blocks.isEmpty()) - return; + if (limits.isBlockLimitExceeded(player, block, limit)) { + Materials material = Materials.getMaterials(block.getType(), block.getData()); - Island island = islandManager.getIslandAtLocation(blocks.get(0).getLocation()); - if (island == null) - return; + skyblock.getMessageManager().sendMessage(player, + skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration().getString("Island.Limit.Block.Exceeded.Message") + .replace("%type", WordUtils.capitalizeFully(material.name().replace("_", " "))).replace("%limit", NumberUtil.formatNumber(limit))); + skyblock.getSoundManager().playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); - // Check spawn block protection - IslandWorld world = worldManager.getIslandWorld(blocks.get(0).getWorld()); - for (org.bukkit.block.Block block : blocks) { - if (LocationUtil.isLocationAffectingIslandSpawn(block.getLocation(), island, world)) { - event.setCancelled(true); - return; - } - } - } catch (ReflectiveOperationException ex) { - ex.printStackTrace(); - } - } - } + event.setCancelled(true); + return; + } - @EventHandler - public void onDispenserDispenseBlock(BlockDispenseEvent event) { - if (!skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration().getBoolean("Island.Spawn.Protection")) - return; + if (!configLoad.getBoolean("Island.Block.Level.Enable")) return; - WorldManager worldManager = skyblock.getWorldManager(); - IslandManager islandManager = skyblock.getIslandManager(); - @SuppressWarnings("deprecation") - BlockFace dispenserDirection = ((org.bukkit.material.Dispenser) event.getBlock().getState().getData()).getFacing(); - org.bukkit.block.Block placeLocation = event.getBlock().getRelative(dispenserDirection); + if (event.getBlock().getType() == Materials.END_PORTAL_FRAME.parseMaterial() && event.getPlayer().getItemInHand().getType() == Materials.ENDER_EYE.parseMaterial()) return; - Island island = islandManager.getIslandAtLocation(placeLocation.getLocation()); - if (island == null) - return; + // Fix a bug in Paper 1.8.8 when using ViaVersion on a 1.12.2 client. + // BUG: Player can infinitely increase their level by placing a block at their + // feet. + // It doesn't take the block away but still increments the level. + // This doesn't happen in Spigot, but does happen in PaperSpigot due to a + // BlockPlaceEvent being incorrectly fired. + // The solution is to wait a tick to make sure that the block was actually + // placed. + // This shouldn't cause any issues besides the task number being increased + // insanely fast. + Bukkit.getScheduler().runTask(skyblock, () -> { + Materials materials = Materials.getMaterials(block.getType(), block.getData()); + if (materials == null || materials == Materials.AIR) return; - // Check spawn block protection - IslandWorld world = worldManager.getIslandWorld(placeLocation.getWorld()); + if (materials.equals(Materials.SPAWNER)) { + if (Bukkit.getPluginManager().isPluginEnabled("EpicSpawners") || Bukkit.getPluginManager().isPluginEnabled("WildStacker")) return; - if (LocationUtil.isLocationAffectingIslandSpawn(placeLocation.getLocation(), island, world)) - event.setCancelled(true); - } + CreatureSpawner creatureSpawner = (CreatureSpawner) block.getState(); + EntityType spawnerType = creatureSpawner.getSpawnedType(); + materials = Materials.getSpawner(spawnerType); + } + + long materialAmount = 0; + IslandLevel level = island.getLevel(); + + if (level.hasMaterial(materials.name())) { + materialAmount = level.getMaterialAmount(materials.name()); + } + + level.setMaterialAmount(materials.name(), materialAmount + 1); + }); + } + + @EventHandler + public void onBlockFromTo(BlockFromToEvent event) { + if (!skyblock.getWorldManager().isIslandWorld(event.getBlock().getWorld())) return; + + GeneratorManager generatorManager = skyblock.getGeneratorManager(); + IslandManager islandManager = skyblock.getIslandManager(); + WorldManager worldManager = skyblock.getWorldManager(); + + Island island = islandManager.getIslandAtLocation(event.getBlock().getLocation()); + IslandWorld world = worldManager.getIslandWorld(event.getBlock().getWorld()); + + Config config = skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")); + FileConfiguration configLoad = config.getFileConfiguration(); + + if (island == null) return; + + org.bukkit.block.Block block = event.getToBlock(); + + // Protect outside of border + if (!islandManager.isLocationAtIsland(island, block.getLocation(), world)) { + event.setCancelled(true); + return; + } + + // Protect spawn + if (LocationUtil.isLocationAffectingIslandSpawn(block.getLocation(), island, world) && configLoad.getBoolean("Island.Spawn.Protection")) { + event.setCancelled(true); + return; + } + + if (NMSUtil.getVersionNumber() < 12) { + if (generatorManager != null && generatorManager.getGenerators().size() > 0 && generatorManager.isGenerator(block)) { + List generators = new ArrayList<>(generatorManager.getGenerators()); + Collections.reverse(generators); // Use the highest generator available + + // Filter valid players on the island + Set possiblePlayers = new HashSet<>(); + for (Player p : Bukkit.getOnlinePlayers()) { + boolean isMember = island.hasRole(IslandRole.Owner, p.getUniqueId()) || island.hasRole(IslandRole.Member, p.getUniqueId()) + || island.hasRole(IslandRole.Coop, p.getUniqueId()) || island.hasRole(IslandRole.Operator, p.getUniqueId()); + if (isMember && islandManager.isLocationAtIsland(island, p.getLocation(), world)) { + possiblePlayers.add(p); + } + } + + // Find highest generator available + for (Generator generator : generators) { + for (Player p : possiblePlayers) { + if (generator.isPermission()) { + if (!p.hasPermission(generator.getPermission()) && !p.hasPermission("fabledskyblock.generator.*") && !p.hasPermission("fabledskyblock.*")) { + continue; + } + } + + org.bukkit.block.BlockState genState = generatorManager.generateBlock(generator, block); + org.bukkit.block.BlockState toBlockState = event.getToBlock().getState(); + + toBlockState.setData(genState.getData()); + toBlockState.setType(genState.getType()); + toBlockState.update(); + + return; + } + } + } + } + } + + @EventHandler + public void onBlockPistonExtend(BlockPistonExtendEvent event) { + WorldManager worldManager = skyblock.getWorldManager(); + if (!worldManager.isIslandWorld(event.getBlock().getWorld())) return; + + IslandManager islandManager = skyblock.getIslandManager(); + Island island = islandManager.getIslandAtLocation(event.getBlock().getLocation()); + if (island == null) return; + + Config config = skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")); + FileConfiguration configLoad = config.getFileConfiguration(); + + if (performStackCheck(event.getBlock(), event.getBlocks(), event.getDirection())) { + event.setCancelled(true); + return; + } + + IslandWorld world = worldManager.getIslandWorld(event.getBlock().getWorld()); + for (org.bukkit.block.Block block : event.getBlocks()) { + if (!islandManager.isLocationAtIsland(island, block.getLocation(), world) + || !islandManager.isLocationAtIsland(island, block.getRelative(event.getDirection()).getLocation(), world)) { + event.setCancelled(true); + return; + } + + if (skyblock.getStackableManager() != null && skyblock.getStackableManager().isStacked(block.getLocation())) { + event.setCancelled(true); + return; + } + + if (configLoad.getBoolean("Island.Spawn.Protection")) { + // Check exact block + if (LocationUtil.isLocationAffectingIslandSpawn(block.getLocation(), island, world)) { + event.setCancelled(true); + return; + } + + // Check block in direction + if (LocationUtil.isLocationAffectingIslandSpawn(block.getRelative(event.getDirection()).getLocation(), island, world)) { + event.setCancelled(true); + return; + } + } + + if (!skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration().getBoolean("Island.Block.Piston.Connected.Extend")) { + if (block.getType() == Materials.PISTON.parseMaterial() || block.getType() == Materials.STICKY_PISTON.parseMaterial()) { + event.setCancelled(true); + return; + } + } + } + + // Check piston head + if (configLoad.getBoolean("Island.Spawn.Protection")) { + if (LocationUtil.isLocationAffectingIslandSpawn(event.getBlock().getRelative(event.getDirection()).getLocation(), island, world)) { + event.setCancelled(true); + } + } + + } + + private boolean performStackCheck(org.bukkit.block.Block block, List list, BlockFace blockFace) { + return !getArmorStands(list.isEmpty() ? block : list.get(list.size() - 1), blockFace).isEmpty(); + } + + private List getArmorStands(org.bukkit.block.Block block, BlockFace blockFace) { + + final List list = new ArrayList<>(); + + block = block.getRelative(blockFace); + + final Location loc = block.getLocation(); + + int locX = loc.getBlockX(); + int locZ = loc.getBlockZ(); + int locY = loc.getBlockY(); + + for (org.bukkit.entity.Entity entity : block.getChunk().getEntities()) { + + if (!(entity instanceof ArmorStand) || !entity.hasMetadata("StackableArmorStand")) continue; + + final Location entityLoc = entity.getLocation(); + + if (entityLoc.getBlockX() != locX) continue; + if (entityLoc.getBlockZ() != locZ) continue; + + final int dist = locY - entityLoc.getBlockY(); + + if (dist >= 0 && dist < 2) list.add((ArmorStand) entity); + } + + return list; + } + + @EventHandler + public void onBlockPistonRetract(BlockPistonRetractEvent event) { + WorldManager worldManager = skyblock.getWorldManager(); + if (!skyblock.getWorldManager().isIslandWorld(event.getBlock().getWorld())) return; + + IslandManager islandManager = skyblock.getIslandManager(); + Island island = islandManager.getIslandAtLocation(event.getBlock().getLocation()); + if (island == null) return; + + Config config = skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")); + FileConfiguration configLoad = config.getFileConfiguration(); + + if (performStackCheck(event.getBlock(), event.getBlocks(), event.getDirection())) { + event.setCancelled(true); + return; + } + + IslandWorld world = worldManager.getIslandWorld(event.getBlock().getWorld()); + for (org.bukkit.block.Block block : event.getBlocks()) { + if (!islandManager.isLocationAtIsland(island, block.getLocation(), world)) { + event.setCancelled(true); + return; + } + + if (skyblock.getStackableManager() != null && skyblock.getStackableManager().isStacked(block.getLocation())) { + event.setCancelled(true); + return; + } + + if (LocationUtil.isLocationAffectingIslandSpawn(block.getLocation(), island, world) && configLoad.getBoolean("Island.Spawn.Protection")) { + event.setCancelled(true); + return; + } + + if (!skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration().getBoolean("Island.Block.Piston.Connected.Retract")) { + if (block.getType() == Materials.PISTON.parseMaterial() || block.getType() == Materials.STICKY_PISTON.parseMaterial()) { + event.setCancelled(true); + return; + } + } + } + } + + @EventHandler + public void onBlockForm(BlockFormEvent event) { + org.bukkit.block.Block block = event.getBlock(); + WorldManager worldManager = skyblock.getWorldManager(); + if (!worldManager.isIslandWorld(block.getWorld())) return; + + // Check ice/snow forming + if (block.getType() == Material.ICE || block.getType() == Material.SNOW) { + if (!skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration().getBoolean("Island.Weather.IceAndSnow")) + event.setCancelled(true); + return; + } + + IslandManager islandManager = skyblock.getIslandManager(); + Island island = islandManager.getIslandAtLocation(block.getLocation()); + if (island == null) return; + + // Check spawn block protection + IslandWorld world = worldManager.getIslandWorld(block.getWorld()); + if (LocationUtil.isLocationAffectingIslandSpawn(block.getLocation(), island, world)) { + if (skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration().getBoolean("Island.Spawn.Protection")) { + event.setCancelled(true); + return; + } + } + + Material material = block.getType(); + if (material != Materials.WATER.parseMaterial() && material != Materials.LEGACY_STATIONARY_WATER.parseMaterial() && material != Materials.LAVA.parseMaterial() + && material != Materials.LEGACY_STATIONARY_LAVA.parseMaterial()) + return; + + BlockState state = event.getNewState(); + Material type = state.getType(); + if (type != Material.COBBLESTONE && type != Material.STONE) return; + + GeneratorManager generatorManager = skyblock.getGeneratorManager(); + if (generatorManager == null) return; + + List generators = Lists.newArrayList(generatorManager.getGenerators()); + if (generators == null || generators.isEmpty()) return; + Collections.reverse(generators); // Use the highest generator available + + // Filter valid players on the island. + Set possiblePlayers = new HashSet<>(); + for (Player player : Bukkit.getOnlinePlayers()) { + boolean isMember = island.hasRole(IslandRole.Owner, player.getUniqueId()) || island.hasRole(IslandRole.Member, player.getUniqueId()) + || island.hasRole(IslandRole.Coop, player.getUniqueId()) || island.hasRole(IslandRole.Operator, player.getUniqueId()); + if (isMember && islandManager.isLocationAtIsland(island, player.getLocation(), world)) { + possiblePlayers.add(player); + } + } + + // Find highest generator available + for (Generator generator : generators) { + for (Player player : possiblePlayers) { + if (generator.isPermission()) { + if (!player.hasPermission(generator.getPermission()) && !player.hasPermission("fabledskyblock.generator.*") && !player.hasPermission("fabledskyblock.*")) { + continue; + } + } + + org.bukkit.block.BlockState genState = generatorManager.generateBlock(generator, block); + state.setType(genState.getType()); + + if (NMSUtil.getVersionNumber() < 13) state.setData(genState.getData()); + return; + } + } + } + + @EventHandler + public void onBlockBurn(BlockBurnEvent event) { + org.bukkit.block.Block block = event.getBlock(); + WorldManager worldManager = skyblock.getWorldManager(); + if (!worldManager.isIslandWorld(block.getWorld())) return; + + IslandManager islandManager = skyblock.getIslandManager(); + if (!islandManager.hasSetting(block.getLocation(), IslandRole.Owner, "FireSpread")) event.setCancelled(true); + } + + @EventHandler + public void onPortalCreate(PortalCreateEvent event) { + if (!skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration().getBoolean("Island.Spawn.Protection")) return; + + WorldManager worldManager = skyblock.getWorldManager(); + IslandManager islandManager = skyblock.getIslandManager(); + // PortalCreateEvent.getBlocks() changed from ArrayList to + // ArrayList in 1.14.1 + if (NMSUtil.getVersionNumber() > 13) { + List blocks = event.getBlocks(); + if (event.getBlocks().isEmpty()) return; + + Island island = islandManager.getIslandAtLocation(event.getBlocks().get(0).getLocation()); + if (island == null) return; + + // Check spawn block protection + IslandWorld world = worldManager.getIslandWorld(event.getBlocks().get(0).getWorld()); + + for (BlockState block : blocks) { + if (LocationUtil.isLocationAffectingIslandSpawn(block.getLocation(), island, world)) { + event.setCancelled(true); + return; + } + } + } else { + try { + @SuppressWarnings("unchecked") + List blocks = (List) event.getClass().getMethod("getBlocks").invoke(event); + if (blocks.isEmpty()) return; + + Island island = islandManager.getIslandAtLocation(blocks.get(0).getLocation()); + if (island == null) return; + + // Check spawn block protection + IslandWorld world = worldManager.getIslandWorld(blocks.get(0).getWorld()); + for (org.bukkit.block.Block block : blocks) { + if (LocationUtil.isLocationAffectingIslandSpawn(block.getLocation(), island, world)) { + event.setCancelled(true); + return; + } + } + } catch (ReflectiveOperationException ex) { + ex.printStackTrace(); + } + } + } + + @EventHandler + public void onDispenserDispenseBlock(BlockDispenseEvent event) { + if (!skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration().getBoolean("Island.Spawn.Protection")) return; + + WorldManager worldManager = skyblock.getWorldManager(); + IslandManager islandManager = skyblock.getIslandManager(); + @SuppressWarnings("deprecation") + BlockFace dispenserDirection = ((org.bukkit.material.Dispenser) event.getBlock().getState().getData()).getFacing(); + org.bukkit.block.Block placeLocation = event.getBlock().getRelative(dispenserDirection); + + Island island = islandManager.getIslandAtLocation(placeLocation.getLocation()); + if (island == null) return; + + // Check spawn block protection + IslandWorld world = worldManager.getIslandWorld(placeLocation.getWorld()); + + if (LocationUtil.isLocationAffectingIslandSpawn(placeLocation.getLocation(), island, world)) event.setCancelled(true); + } } diff --git a/src/main/java/com/songoda/skyblock/listeners/Interact.java b/src/main/java/com/songoda/skyblock/listeners/Interact.java index 9d76890b..d214e632 100644 --- a/src/main/java/com/songoda/skyblock/listeners/Interact.java +++ b/src/main/java/com/songoda/skyblock/listeners/Interact.java @@ -57,7 +57,7 @@ public class Interact implements Listener { } @SuppressWarnings("deprecation") - @EventHandler(priority = EventPriority.LOW, ignoreCancelled = true) + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void onPlayerInteract(PlayerInteractEvent event) { Player player = event.getPlayer(); org.bukkit.block.Block block = event.getClickedBlock(); @@ -84,8 +84,7 @@ public class Interact implements Listener { event.setCancelled(true); messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); + skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration().getString("Island.Settings.Permission.Message")); soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); return; @@ -95,8 +94,7 @@ public class Interact implements Listener { event.setCancelled(true); messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); + skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration().getString("Island.Settings.Permission.Message")); soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); return; @@ -106,8 +104,7 @@ public class Interact implements Listener { event.setCancelled(true); messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); + skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration().getString("Island.Settings.Permission.Message")); soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); return; @@ -117,8 +114,7 @@ public class Interact implements Listener { event.setCancelled(true); messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); + skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration().getString("Island.Settings.Permission.Message")); soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); return; @@ -132,62 +128,73 @@ public class Interact implements Listener { event.setCancelled(true); messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); + skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration().getString("Island.Settings.Permission.Message")); soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); } } } if (event.getAction() == Action.RIGHT_CLICK_BLOCK) { - if (stackableManager != null - && stackableManager.isStackableMaterial(event.getMaterial()) - && event.getClickedBlock().getType() == event.getMaterial() - && !player.isSneaking() && islandManager.hasPermission(player, block.getLocation(), "Place") - && (!skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration().getBoolean("Island.Stackable.RequirePermission") || player.hasPermission("fabledskyblock.stackable"))) { + + System.out.println("1st Condition: " + (stackableManager != null)); + System.out.println("2nd Condition: " + (stackableManager != null && stackableManager.isStackableMaterial(event.getMaterial()))); + System.out.println("3rd Condition: " + (event.getClickedBlock().getType() == event.getMaterial())); + System.out.println("4th Condition: " + (!player.isSneaking())); + System.out.println("5th Condition: " + + ((!skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration().getBoolean("Island.Stackable.RequirePermission") + || player.hasPermission("fabledskyblock.stackable")))); + System.out.println("All must be true."); + + if (stackableManager != null && stackableManager.isStackableMaterial(event.getMaterial()) && event.getClickedBlock().getType() == event.getMaterial() && !player.isSneaking() + && islandManager.hasPermission(player, block.getLocation(), "Place") + && (!skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration().getBoolean("Island.Stackable.RequirePermission") + || player.hasPermission("fabledskyblock.stackable"))) { if (NMSUtil.getVersionNumber() > 8) { if (event.getHand() == EquipmentSlot.OFF_HAND) return; } if (levellingManager.isScanning(island)) { - skyblock.getMessageManager().sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Command.Island.Level.Scanning.BlockPlacing.Message")); + skyblock.getMessageManager().sendMessage(player, skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration() + .getString("Command.Island.Level.Scanning.BlockPlacing.Message")); event.setCancelled(true); return; } BlockLimitation limits = skyblock.getLimitationHandler().getInstance(BlockLimitation.class); - + long limit = limits.getBlockLimit(player, block); - + if (limits.isBlockLimitExceeded(player, block, limit)) { - Materials material = Materials.getMaterials(block.getType(), block.getData()); + Materials material = Materials.getMaterials(block.getType(), block.getData()); - skyblock.getMessageManager().sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Limit.Block.Exceeded.Message") - .replace("%type", WordUtils.capitalizeFully(material.name().replace("_", " "))) - .replace("%limit", NumberUtil.formatNumber(limit))); - skyblock.getSoundManager().playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); + skyblock.getMessageManager().sendMessage(player, + skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration().getString("Island.Limit.Block.Exceeded.Message") + .replace("%type", WordUtils.capitalizeFully(material.name().replace("_", " "))).replace("%limit", NumberUtil.formatNumber(limit))); + skyblock.getSoundManager().playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); - event.setCancelled(true); - return; + event.setCancelled(true); + return; } - + Location location = event.getClickedBlock().getLocation(); - if (stackableManager.isStacked(location)) { - Stackable stackable = stackableManager.getStack(location, event.getMaterial()); - if (stackable != null) - stackable.addOne(); + Stackable stackable = stackableManager.getStack(location, event.getMaterial()); + int itemAmount = event.getItem().getAmount(); + + if (stackable == null) { + stackableManager.addStack(stackable = new Stackable(location, event.getMaterial())); + stackable.setSize(itemAmount + 1); + System.out.println("Stack is null. Creating"); } else { - stackableManager.addStack(new Stackable(location, event.getMaterial())); + stackable.setSize(stackable.getSize() + itemAmount); + System.out.println("Incrementing stack count."); } + event.setCancelled(true); - InventoryUtil.takeItem(player, 1); + InventoryUtil.takeItem(player, itemAmount); FileManager.Config config = skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")); FileConfiguration configLoad = config.getFileConfiguration(); + if (!configLoad.getBoolean("Island.Block.Level.Enable")) return; Materials materials = Materials.getMaterials(block.getType(), block.getData()); @@ -200,17 +207,17 @@ public class Interact implements Listener { materialAmount = level.getMaterialAmount(materials.name()); } - level.setMaterialAmount(materials.name(), materialAmount + 1); + level.setMaterialAmount(materials.name(), materialAmount + itemAmount); return; } - + // Check if the clicked block is outside of the border. WorldManager worldManager = skyblock.getWorldManager(); org.bukkit.block.Block clickedBlock = event.getClickedBlock(); IslandWorld world = worldManager.getIslandWorld(clickedBlock.getWorld()); if (!islandManager.isLocationAtIsland(island, clickedBlock.getLocation(), world)) { - event.setCancelled(true); - return; + event.setCancelled(true); + return; } if (event.getItem() != null && event.getItem().getType() == Materials.BONE_MEAL.parseMaterial() && !islandManager.hasPermission(player, block.getLocation(), "Place")) { @@ -224,8 +231,7 @@ public class Interact implements Listener { event.setCancelled(true); messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); + skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration().getString("Island.Settings.Permission.Message")); soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); return; @@ -235,367 +241,312 @@ public class Interact implements Listener { event.setCancelled(true); messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); + skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration().getString("Island.Settings.Permission.Message")); soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); return; } - } else if (block.getType() == Materials.LEGACY_BED_BLOCK.parseMaterial() - || block.getType() == Materials.WHITE_BED.parseMaterial() - || block.getType() == Materials.ORANGE_BED.parseMaterial() - || block.getType() == Materials.MAGENTA_BED.parseMaterial() - || block.getType() == Materials.LIGHT_BLUE_BED.parseMaterial() - || block.getType() == Materials.YELLOW_BED.parseMaterial() - || block.getType() == Materials.LIME_BED.parseMaterial() - || block.getType() == Materials.PINK_BED.parseMaterial() - || block.getType() == Materials.GRAY_BED.parseMaterial() - || block.getType() == Materials.LIGHT_GRAY_BED.parseMaterial() - || block.getType() == Materials.CYAN_BED.parseMaterial() - || block.getType() == Materials.CYAN_BED.parseMaterial() - || block.getType() == Materials.PURPLE_BED.parseMaterial() - || block.getType() == Materials.BLUE_BED.parseMaterial() - || block.getType() == Materials.BROWN_BED.parseMaterial() - || block.getType() == Materials.GREEN_BED.parseMaterial() - || block.getType() == Materials.RED_BED.parseMaterial() + } else if (block.getType() == Materials.LEGACY_BED_BLOCK.parseMaterial() || block.getType() == Materials.WHITE_BED.parseMaterial() + || block.getType() == Materials.ORANGE_BED.parseMaterial() || block.getType() == Materials.MAGENTA_BED.parseMaterial() + || block.getType() == Materials.LIGHT_BLUE_BED.parseMaterial() || block.getType() == Materials.YELLOW_BED.parseMaterial() + || block.getType() == Materials.LIME_BED.parseMaterial() || block.getType() == Materials.PINK_BED.parseMaterial() || block.getType() == Materials.GRAY_BED.parseMaterial() + || block.getType() == Materials.LIGHT_GRAY_BED.parseMaterial() || block.getType() == Materials.CYAN_BED.parseMaterial() + || block.getType() == Materials.CYAN_BED.parseMaterial() || block.getType() == Materials.PURPLE_BED.parseMaterial() + || block.getType() == Materials.BLUE_BED.parseMaterial() || block.getType() == Materials.BROWN_BED.parseMaterial() + || block.getType() == Materials.GREEN_BED.parseMaterial() || block.getType() == Materials.RED_BED.parseMaterial() || block.getType() == Materials.BLACK_BED.parseMaterial()) { - if (!islandManager.hasPermission(player, block.getLocation(), "Bed")) { - event.setCancelled(true); - - messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); - soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); - - return; - } - } else if (block.getType() == Material.BREWING_STAND) { - if (!islandManager.hasPermission(player, block.getLocation(), "Brewing")) { - event.setCancelled(true); - - messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); - soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); - - return; - } - } else if (block.getType() == Material.CHEST || block.getType() == Material.TRAPPED_CHEST - || (NMSUtil.getVersionNumber() > 9 - && (block.getType() == Materials.SHULKER_BOX.parseMaterial() - || block.getType() == Materials.BLACK_SHULKER_BOX.parseMaterial() - || block.getType() == Materials.BLUE_SHULKER_BOX.parseMaterial() - || block.getType() == Materials.BROWN_SHULKER_BOX.parseMaterial() - || block.getType() == Materials.CYAN_SHULKER_BOX.parseMaterial() - || block.getType() == Materials.GRAY_SHULKER_BOX.parseMaterial() - || block.getType() == Materials.GREEN_SHULKER_BOX.parseMaterial() - || block.getType() == Materials.LIGHT_BLUE_SHULKER_BOX.parseMaterial() - || block.getType() == Materials.LIGHT_GRAY_SHULKER_BOX.parseMaterial() - || block.getType() == Materials.LIME_SHULKER_BOX.parseMaterial() - || block.getType() == Materials.MAGENTA_SHULKER_BOX.parseMaterial() - || block.getType() == Materials.ORANGE_SHULKER_BOX.parseMaterial() - || block.getType() == Materials.PINK_SHULKER_BOX.parseMaterial() - || block.getType() == Materials.PURPLE_SHULKER_BOX.parseMaterial() - || block.getType() == Materials.RED_SHULKER_BOX.parseMaterial() - || block.getType() == Materials.WHITE_SHULKER_BOX.parseMaterial() - || block.getType() == Materials.YELLOW_SHULKER_BOX.parseMaterial()))) { - if (!islandManager.hasPermission(player, block.getLocation(), "Storage")) { - event.setCancelled(true); - - messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); - soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); - - return; - } - } else if (block.getType() == Materials.CRAFTING_TABLE.parseMaterial()) { - if (!islandManager.hasPermission(player, block.getLocation(), "Workbench")) { - event.setCancelled(true); - - messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); - soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); - - return; - } - } else if (block.getType() == Material.BIRCH_DOOR || block.getType() == Material.ACACIA_DOOR - || block.getType() == Material.DARK_OAK_DOOR || block.getType() == Material.JUNGLE_DOOR - || block.getType() == Material.SPRUCE_DOOR - || block.getType() == Materials.LEGACY_WOODEN_DOOR.parseMaterial() - || block.getType() == Materials.OAK_DOOR.parseMaterial()) { - if (!islandManager.hasPermission(player, block.getLocation(), "Door")) { - event.setCancelled(true); - - messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); - soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); - - return; - } - } else if (block.getType() == Materials.ENCHANTING_TABLE.parseMaterial()) { - if (!islandManager.hasPermission(player, block.getLocation(), "Enchant")) { - event.setCancelled(true); - - messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); - soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); - - return; - } - } else if (block.getType() == Material.FURNACE - || block.getType() == Materials.LEGACY_BURNING_FURNACE.parseMaterial()) { - if (!islandManager.hasPermission(player, block.getLocation(), "Furnace")) { - event.setCancelled(true); - - messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); - soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); - - return; - } - } else if (block.getType() == Material.STONE_BUTTON - || block.getType() == Materials.OAK_BUTTON.parseMaterial() - || block.getType() == Materials.SPRUCE_BUTTON.parseMaterial() - || block.getType() == Materials.BIRCH_BUTTON.parseMaterial() - || block.getType() == Materials.JUNGLE_BUTTON.parseMaterial() - || block.getType() == Materials.ACACIA_BUTTON.parseMaterial() - || block.getType() == Materials.DARK_OAK_BUTTON.parseMaterial() - || block.getType() == Materials.LEVER.parseMaterial()) { - if (!islandManager.hasPermission(player, block.getLocation(), "LeverButton")) { - event.setCancelled(true); - - messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); - soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); - - return; - } - } else if (block.getType() == Material.JUKEBOX) { - if (!islandManager.hasPermission(player, block.getLocation(), "Jukebox")) { - event.setCancelled(true); - - messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); - soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); - - return; - } - } else if (block.getType() == Materials.OAK_TRAPDOOR.parseMaterial() - || block.getType() == Materials.SPRUCE_TRAPDOOR.parseMaterial() - || block.getType() == Materials.BIRCH_TRAPDOOR.parseMaterial() - || block.getType() == Materials.JUNGLE_TRAPDOOR.parseMaterial() - || block.getType() == Materials.ACACIA_TRAPDOOR.parseMaterial() - || block.getType() == Materials.DARK_OAK_TRAPDOOR.parseMaterial() - || block.getType() == Material.NOTE_BLOCK - || block.getType() == Material.HOPPER - || block.getType() == Materials.COMPARATOR.parseMaterial() - || block.getType() == Materials.LEGACY_REDSTONE_COMPARATOR_OFF.parseMaterial() - || block.getType() == Materials.LEGACY_REDSTONE_COMPARATOR_ON.parseMaterial() - || block.getType() == Materials.REPEATER.parseMaterial() - || block.getType() == Materials.LEGACY_DIODE_BLOCK_OFF.parseMaterial() - || block.getType() == Materials.LEGACY_DIODE_BLOCK_ON.parseMaterial()) { - if (!islandManager.hasPermission(player, block.getLocation(), "Redstone")) { - event.setCancelled(true); - - messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); - soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); - - return; - } - } else if (block.getType() == Materials.OAK_FENCE_GATE.parseMaterial() - || block.getType() == Material.ACACIA_FENCE_GATE || block.getType() == Material.BIRCH_FENCE_GATE - || block.getType() == Material.DARK_OAK_FENCE_GATE || block.getType() == Material.JUNGLE_FENCE_GATE - || block.getType() == Material.SPRUCE_FENCE_GATE) { - if (!islandManager.hasPermission(player, block.getLocation(), "Gate")) { - event.setCancelled(true); - - messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); - soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); - - return; - } - } else if (block.getType() == Material.DROPPER || block.getType() == Material.DISPENSER) { - if (!islandManager.hasPermission(player, block.getLocation(), "DropperDispenser")) { - event.setCancelled(true); - - messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); - soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); - - return; - } - } else if (block.getType() == Material.TNT) { - if (!islandManager.hasPermission(player, block.getLocation(), "Destroy")) { - event.setCancelled(true); - - messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); - soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); - - return; - } - } else if (block.getType() == Materials.LEGACY_CAKE_BLOCK.getPostMaterial()) { - if (player.getFoodLevel() < 20 && !islandManager.hasPermission(player, block.getLocation(), "Cake")) { - event.setCancelled(true); - - messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); - soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); - - return; - } - } else if (block.getType() == Material.HOPPER) { - if (!islandManager.hasPermission(player, block.getLocation(), "Hopper")) { - event.setCancelled(true); - - messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); - soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); - - return; - } - } else if ((player.getGameMode() == GameMode.SURVIVAL) && (block.getType() == Material.OBSIDIAN) - && (event.getItem() != null) && (event.getItem().getType() != Material.AIR) - && (event.getItem().getType() == Material.BUCKET)) { - if (skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")) - .getFileConfiguration().getBoolean("Island.Block.Obsidian.Enable") - && islandManager.hasPermission(player, block.getLocation(), "Bucket")) { - int NMSVersion = NMSUtil.getVersionNumber(); - boolean isInventoryFull = false; - - if (NMSVersion > 8) { - isInventoryFull = InventoryUtil.isInventoryFull(player.getInventory(), 5, 1, Material.BUCKET); - } else { - isInventoryFull = InventoryUtil.isInventoryFull(player.getInventory(), 0, 1, Material.BUCKET); - } - - soundManager.playSound(block.getLocation(), Sounds.FIZZ.bukkitSound(), 1.0F, 1.0F); - - InventoryUtil.removeItem(player.getInventory(), 1, false, Material.BUCKET); - block.setType(Material.AIR); - - if (isInventoryFull) { - player.getWorld().dropItemNaturally(player.getLocation(), new ItemStack(Material.LAVA_BUCKET)); - } else { - if (NMSVersion > 8) { - isInventoryFull = InventoryUtil.isInventoryFull(player.getInventory(), 5, 1, - Material.LAVA_BUCKET); - } else { - isInventoryFull = InventoryUtil.isInventoryFull(player.getInventory(), 0, 1, - Material.LAVA_BUCKET); - } - - if (isInventoryFull) { - player.getWorld().dropItemNaturally(player.getLocation(), - new ItemStack(Material.LAVA_BUCKET)); - } else { - player.getInventory().addItem(new ItemStack(Material.LAVA_BUCKET)); - } - } - - event.setCancelled(true); - - return; - } - } else if (block.getType() == Materials.END_PORTAL_FRAME.parseMaterial()) { - if (skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")) - .getFileConfiguration().getBoolean("Island.Block.EndFrame.Enable") - && islandManager.hasPermission(player, block.getLocation(), "Destroy")) { - - if (NMSUtil.getVersionNumber() > 8 && event.getHand() == EquipmentSlot.OFF_HAND) - return; - - if (Bukkit.getPluginManager().isPluginEnabled("EpicAnchors")) { - if (com.songoda.epicanchors.EpicAnchors.getInstance().getAnchorManager().getAnchor(block.getLocation()) != null) { + if (!islandManager.hasPermission(player, block.getLocation(), "Bed")) { event.setCancelled(true); + + messageManager.sendMessage(player, skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration() + .getString("Island.Settings.Permission.Message")); + soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); + return; } - } - - ItemStack is = event.getPlayer().getItemInHand(); - boolean hasEye = ((block.getData() >> 2) & 1) == 1; - - if (is == null || is.getType() == Material.AIR) { - if (stackableManager != null && stackableManager.isStacked(block.getLocation())) { - Stackable stackable = stackableManager.getStack(block.getLocation(), Materials.END_PORTAL_FRAME.parseMaterial()); - stackable.takeOne(); - - if (stackable.getSize() <= 1) { - stackableManager.removeStack(stackable); - } - } else { - block.setType(Material.AIR); - } - - player.getInventory().addItem(new ItemStack(Materials.END_PORTAL_FRAME.parseMaterial(), 1)); - if (hasEye) player.getInventory().addItem(new ItemStack(Materials.ENDER_EYE.parseMaterial(), 1)); - player.updateInventory(); - - FileManager.Config config = skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")); - FileConfiguration configLoad = config.getFileConfiguration(); - - if (configLoad.getBoolean("Island.Block.Level.Enable")) { - Materials materials = Materials.END_PORTAL_FRAME; - IslandLevel level = island.getLevel(); - - if (level.hasMaterial(materials.name())) { - long materialAmount = level.getMaterialAmount(materials.name()); - - if (materialAmount - 1 <= 0) { - level.removeMaterial(materials.name()); - } else { - level.setMaterialAmount(materials.name(), materialAmount - 1); - } - } - } - - soundManager.playSound(player, Sounds.CHICKEN_EGG_POP.bukkitSound(), 10.0F, 10.0F); - + } else + if (block.getType() == Material.BREWING_STAND) { + if (!islandManager.hasPermission(player, block.getLocation(), "Brewing")) { event.setCancelled(true); + + messageManager.sendMessage(player, skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration() + .getString("Island.Settings.Permission.Message")); + soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); + return; } - } - } + } else if (block.getType() == Material.CHEST || block.getType() == Material.TRAPPED_CHEST + || (NMSUtil.getVersionNumber() > 9 && (block.getType() == Materials.SHULKER_BOX.parseMaterial() || block.getType() == Materials.BLACK_SHULKER_BOX.parseMaterial() + || block.getType() == Materials.BLUE_SHULKER_BOX.parseMaterial() || block.getType() == Materials.BROWN_SHULKER_BOX.parseMaterial() + || block.getType() == Materials.CYAN_SHULKER_BOX.parseMaterial() || block.getType() == Materials.GRAY_SHULKER_BOX.parseMaterial() + || block.getType() == Materials.GREEN_SHULKER_BOX.parseMaterial() || block.getType() == Materials.LIGHT_BLUE_SHULKER_BOX.parseMaterial() + || block.getType() == Materials.LIGHT_GRAY_SHULKER_BOX.parseMaterial() || block.getType() == Materials.LIME_SHULKER_BOX.parseMaterial() + || block.getType() == Materials.MAGENTA_SHULKER_BOX.parseMaterial() || block.getType() == Materials.ORANGE_SHULKER_BOX.parseMaterial() + || block.getType() == Materials.PINK_SHULKER_BOX.parseMaterial() || block.getType() == Materials.PURPLE_SHULKER_BOX.parseMaterial() + || block.getType() == Materials.RED_SHULKER_BOX.parseMaterial() || block.getType() == Materials.WHITE_SHULKER_BOX.parseMaterial() + || block.getType() == Materials.YELLOW_SHULKER_BOX.parseMaterial()))) { + if (!islandManager.hasPermission(player, block.getLocation(), "Storage")) { + event.setCancelled(true); + + messageManager.sendMessage(player, skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration() + .getString("Island.Settings.Permission.Message")); + soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); + + return; + } + } else + if (block.getType() == Materials.CRAFTING_TABLE.parseMaterial()) { + if (!islandManager.hasPermission(player, block.getLocation(), "Workbench")) { + event.setCancelled(true); + + messageManager.sendMessage(player, skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration() + .getString("Island.Settings.Permission.Message")); + soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); + + return; + } + } else if (block.getType() == Material.BIRCH_DOOR || block.getType() == Material.ACACIA_DOOR || block.getType() == Material.DARK_OAK_DOOR + || block.getType() == Material.JUNGLE_DOOR || block.getType() == Material.SPRUCE_DOOR || block.getType() == Materials.LEGACY_WOODEN_DOOR.parseMaterial() + || block.getType() == Materials.OAK_DOOR.parseMaterial()) { + if (!islandManager.hasPermission(player, block.getLocation(), "Door")) { + event.setCancelled(true); + + messageManager.sendMessage(player, skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration() + .getString("Island.Settings.Permission.Message")); + soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); + + return; + } + } else + if (block.getType() == Materials.ENCHANTING_TABLE.parseMaterial()) { + if (!islandManager.hasPermission(player, block.getLocation(), "Enchant")) { + event.setCancelled(true); + + messageManager.sendMessage(player, skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration() + .getString("Island.Settings.Permission.Message")); + soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); + + return; + } + } else if (block.getType() == Material.FURNACE || block.getType() == Materials.LEGACY_BURNING_FURNACE.parseMaterial()) { + if (!islandManager.hasPermission(player, block.getLocation(), "Furnace")) { + event.setCancelled(true); + + messageManager.sendMessage(player, skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration() + .getString("Island.Settings.Permission.Message")); + soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); + + return; + } + } else if (block.getType() == Material.STONE_BUTTON || block.getType() == Materials.OAK_BUTTON.parseMaterial() + || block.getType() == Materials.SPRUCE_BUTTON.parseMaterial() || block.getType() == Materials.BIRCH_BUTTON.parseMaterial() + || block.getType() == Materials.JUNGLE_BUTTON.parseMaterial() || block.getType() == Materials.ACACIA_BUTTON.parseMaterial() + || block.getType() == Materials.DARK_OAK_BUTTON.parseMaterial() || block.getType() == Materials.LEVER.parseMaterial()) { + if (!islandManager.hasPermission(player, block.getLocation(), "LeverButton")) { + event.setCancelled(true); + + messageManager.sendMessage(player, skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration() + .getString("Island.Settings.Permission.Message")); + soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); + + return; + } + } else + if (block.getType() == Material.JUKEBOX) { + if (!islandManager.hasPermission(player, block.getLocation(), "Jukebox")) { + event.setCancelled(true); + + messageManager.sendMessage(player, skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration() + .getString("Island.Settings.Permission.Message")); + soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); + + return; + } + } else if (block.getType() == Materials.OAK_TRAPDOOR.parseMaterial() || block.getType() == Materials.SPRUCE_TRAPDOOR.parseMaterial() + || block.getType() == Materials.BIRCH_TRAPDOOR.parseMaterial() || block.getType() == Materials.JUNGLE_TRAPDOOR.parseMaterial() + || block.getType() == Materials.ACACIA_TRAPDOOR.parseMaterial() || block.getType() == Materials.DARK_OAK_TRAPDOOR.parseMaterial() + || block.getType() == Material.NOTE_BLOCK || block.getType() == Material.HOPPER || block.getType() == Materials.COMPARATOR.parseMaterial() + || block.getType() == Materials.LEGACY_REDSTONE_COMPARATOR_OFF.parseMaterial() + || block.getType() == Materials.LEGACY_REDSTONE_COMPARATOR_ON.parseMaterial() || block.getType() == Materials.REPEATER.parseMaterial() + || block.getType() == Materials.LEGACY_DIODE_BLOCK_OFF.parseMaterial() || block.getType() == Materials.LEGACY_DIODE_BLOCK_ON.parseMaterial()) { + if (!islandManager.hasPermission(player, block.getLocation(), "Redstone")) { + event.setCancelled(true); + + messageManager.sendMessage(player, skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration() + .getString("Island.Settings.Permission.Message")); + soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); + + return; + } + } else + if (block.getType() == Materials.OAK_FENCE_GATE.parseMaterial() || block.getType() == Material.ACACIA_FENCE_GATE + || block.getType() == Material.BIRCH_FENCE_GATE || block.getType() == Material.DARK_OAK_FENCE_GATE || block.getType() == Material.JUNGLE_FENCE_GATE + || block.getType() == Material.SPRUCE_FENCE_GATE) { + if (!islandManager.hasPermission(player, block.getLocation(), "Gate")) { + event.setCancelled(true); + + messageManager.sendMessage(player, skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) + .getFileConfiguration().getString("Island.Settings.Permission.Message")); + soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); + + return; + } + } else + if (block.getType() == Material.DROPPER || block.getType() == Material.DISPENSER) { + if (!islandManager.hasPermission(player, block.getLocation(), "DropperDispenser")) { + event.setCancelled(true); + + messageManager.sendMessage(player, skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration() + .getString("Island.Settings.Permission.Message")); + soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); + + return; + } + } else if (block.getType() == Material.TNT) { + if (!islandManager.hasPermission(player, block.getLocation(), "Destroy")) { + event.setCancelled(true); + + messageManager.sendMessage(player, skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration() + .getString("Island.Settings.Permission.Message")); + soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); + + return; + } + } else if (block.getType() == Materials.LEGACY_CAKE_BLOCK.getPostMaterial()) { + if (player.getFoodLevel() < 20 && !islandManager.hasPermission(player, block.getLocation(), "Cake")) { + event.setCancelled(true); + + messageManager.sendMessage(player, skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration() + .getString("Island.Settings.Permission.Message")); + soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); + + return; + } + } else if (block.getType() == Material.HOPPER) { + if (!islandManager.hasPermission(player, block.getLocation(), "Hopper")) { + event.setCancelled(true); + + messageManager.sendMessage(player, skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration() + .getString("Island.Settings.Permission.Message")); + soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); + + return; + } + } else if ((player.getGameMode() == GameMode.SURVIVAL) && (block.getType() == Material.OBSIDIAN) && (event.getItem() != null) + && (event.getItem().getType() != Material.AIR) && (event.getItem().getType() == Material.BUCKET)) { + if (skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration() + .getBoolean("Island.Block.Obsidian.Enable") && islandManager.hasPermission(player, block.getLocation(), "Bucket")) { + int NMSVersion = NMSUtil.getVersionNumber(); + boolean isInventoryFull = false; + + if (NMSVersion > 8) { + isInventoryFull = InventoryUtil.isInventoryFull(player.getInventory(), 5, 1, Material.BUCKET); + } else { + isInventoryFull = InventoryUtil.isInventoryFull(player.getInventory(), 0, 1, Material.BUCKET); + } + + soundManager.playSound(block.getLocation(), Sounds.FIZZ.bukkitSound(), 1.0F, 1.0F); + + InventoryUtil.removeItem(player.getInventory(), 1, false, Material.BUCKET); + block.setType(Material.AIR); + + if (isInventoryFull) { + player.getWorld().dropItemNaturally(player.getLocation(), new ItemStack(Material.LAVA_BUCKET)); + } else { + if (NMSVersion > 8) { + isInventoryFull = InventoryUtil.isInventoryFull(player.getInventory(), 5, 1, Material.LAVA_BUCKET); + } else { + isInventoryFull = InventoryUtil.isInventoryFull(player.getInventory(), 0, 1, Material.LAVA_BUCKET); + } + + if (isInventoryFull) { + player.getWorld().dropItemNaturally(player.getLocation(), new ItemStack(Material.LAVA_BUCKET)); + } else { + player.getInventory().addItem(new ItemStack(Material.LAVA_BUCKET)); + } + } + + event.setCancelled(true); + + return; + } + } else + if (block.getType() == Materials.END_PORTAL_FRAME.parseMaterial()) { + if (skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration() + .getBoolean("Island.Block.EndFrame.Enable") && islandManager.hasPermission(player, block.getLocation(), "Destroy")) { + + if (NMSUtil.getVersionNumber() > 8 && event.getHand() == EquipmentSlot.OFF_HAND) return; + + if (Bukkit.getPluginManager().isPluginEnabled("EpicAnchors")) { + if (com.songoda.epicanchors.EpicAnchors.getInstance().getAnchorManager().getAnchor(block.getLocation()) != null) { + event.setCancelled(true); + return; + } + } + + ItemStack is = event.getPlayer().getItemInHand(); + boolean hasEye = ((block.getData() >> 2) & 1) == 1; + + if (is == null || is.getType() == Material.AIR) { + if (stackableManager != null && stackableManager.isStacked(block.getLocation())) { + Stackable stackable = stackableManager.getStack(block.getLocation(), Materials.END_PORTAL_FRAME.parseMaterial()); + stackable.takeOne(); + + if (stackable.getSize() <= 1) { + stackableManager.removeStack(stackable); + } + } else { + block.setType(Material.AIR); + } + + player.getInventory().addItem(new ItemStack(Materials.END_PORTAL_FRAME.parseMaterial(), 1)); + if (hasEye) player.getInventory().addItem(new ItemStack(Materials.ENDER_EYE.parseMaterial(), 1)); + player.updateInventory(); + + FileManager.Config config = skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")); + FileConfiguration configLoad = config.getFileConfiguration(); + + if (configLoad.getBoolean("Island.Block.Level.Enable")) { + Materials materials = Materials.END_PORTAL_FRAME; + IslandLevel level = island.getLevel(); + + if (level.hasMaterial(materials.name())) { + long materialAmount = level.getMaterialAmount(materials.name()); + + if (materialAmount - 1 <= 0) { + level.removeMaterial(materials.name()); + } else { + level.setMaterialAmount(materials.name(), materialAmount - 1); + } + } + } + + soundManager.playSound(player, Sounds.CHICKEN_EGG_POP.bukkitSound(), 10.0F, 10.0F); + + event.setCancelled(true); + return; + } + } + } if ((event.getItem() != null) && (event.getItem().getType() != Material.AIR) && !event.isCancelled()) { - if (event.getItem().getType() == Material.BUCKET || event.getItem().getType() == Material.WATER_BUCKET - || event.getItem().getType() == Material.LAVA_BUCKET) { + if (event.getItem().getType() == Material.BUCKET || event.getItem().getType() == Material.WATER_BUCKET || event.getItem().getType() == Material.LAVA_BUCKET) { if (!islandManager.hasPermission(player, block.getLocation(), "Bucket")) { event.setCancelled(true); - messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); + messageManager.sendMessage(player, skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration() + .getString("Island.Settings.Permission.Message")); soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); player.updateInventory(); } } else if (event.getItem().getType() == Material.GLASS_BOTTLE) { - if (block.getType() == Material.WATER - || block.getType() == Materials.LEGACY_STATIONARY_WATER.getPostMaterial() - || block.getType() == Material.CAULDRON) { + if (block.getType() == Material.WATER || block.getType() == Materials.LEGACY_STATIONARY_WATER.getPostMaterial() || block.getType() == Material.CAULDRON) { if (!islandManager.hasPermission(player, block.getLocation(), "WaterCollection")) { event.setCancelled(true); - messageManager.sendMessage(player, - skyblock.getFileManager() - .getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); + messageManager.sendMessage(player, skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration() + .getString("Island.Settings.Permission.Message")); soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); player.updateInventory(); @@ -605,21 +556,18 @@ public class Interact implements Listener { if (!islandManager.hasPermission(player, block.getLocation(), "SpawnEgg")) { event.setCancelled(true); - messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); + messageManager.sendMessage(player, skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration() + .getString("Island.Settings.Permission.Message")); soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); player.updateInventory(); } - } else if (event.getItem().getType() == Material.ARMOR_STAND || event.getItem().getType().name().contains("BOAT") - || event.getItem().getType().name().contains("MINECART")) { + } else if (event.getItem().getType() == Material.ARMOR_STAND || event.getItem().getType().name().contains("BOAT") || event.getItem().getType().name().contains("MINECART")) { if (!islandManager.hasPermission(player, block.getLocation(), "EntityPlacement")) { event.setCancelled(true); - messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); + messageManager.sendMessage(player, skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration() + .getString("Island.Settings.Permission.Message")); soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); player.updateInventory(); @@ -633,8 +581,7 @@ public class Interact implements Listener { event.setCancelled(true); messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); + skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration().getString("Island.Settings.Permission.Message")); soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); } } @@ -646,32 +593,27 @@ public class Interact implements Listener { event.setCancelled(true); messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); + skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration().getString("Island.Settings.Permission.Message")); soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); } - } else if (block.getType() == Materials.STONE_PRESSURE_PLATE.parseMaterial() - || block.getType() == Materials.OAK_PRESSURE_PLATE.parseMaterial() - || block.getType() == Materials.SPRUCE_PRESSURE_PLATE.parseMaterial() - || block.getType() == Materials.BIRCH_PRESSURE_PLATE.parseMaterial() - || block.getType() == Materials.JUNGLE_PRESSURE_PLATE.parseMaterial() - || block.getType() == Materials.ACACIA_PRESSURE_PLATE.parseMaterial() - || block.getType() == Materials.DARK_OAK_PRESSURE_PLATE.parseMaterial() - || block.getType() == Materials.LIGHT_WEIGHTED_PRESSURE_PLATE.parseMaterial() + } else if (block.getType() == Materials.STONE_PRESSURE_PLATE.parseMaterial() || block.getType() == Materials.OAK_PRESSURE_PLATE.parseMaterial() + || block.getType() == Materials.SPRUCE_PRESSURE_PLATE.parseMaterial() || block.getType() == Materials.BIRCH_PRESSURE_PLATE.parseMaterial() + || block.getType() == Materials.JUNGLE_PRESSURE_PLATE.parseMaterial() || block.getType() == Materials.ACACIA_PRESSURE_PLATE.parseMaterial() + || block.getType() == Materials.DARK_OAK_PRESSURE_PLATE.parseMaterial() || block.getType() == Materials.LIGHT_WEIGHTED_PRESSURE_PLATE.parseMaterial() || block.getType() == Materials.HEAVY_WEIGHTED_PRESSURE_PLATE.parseMaterial()) { - if (!islandManager.hasPermission(player, block.getLocation(), "PressurePlate")) { - event.setCancelled(true); - } - } else if (block.getType() == Material.TRIPWIRE) { - if (!islandManager.hasPermission(player, block.getLocation(), "Redstone")) { - event.setCancelled(true); + if (!islandManager.hasPermission(player, block.getLocation(), "PressurePlate")) { + event.setCancelled(true); + } + } else + if (block.getType() == Material.TRIPWIRE) { + if (!islandManager.hasPermission(player, block.getLocation(), "Redstone")) { + event.setCancelled(true); - messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); - soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); + messageManager.sendMessage(player, skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration() + .getString("Island.Settings.Permission.Message")); + soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); + } } - } } } @@ -688,21 +630,15 @@ public class Interact implements Listener { ItemStack structureTool = StructureUtil.getTool(); if ((event.getItem().getType() == structureTool.getType()) && (event.getItem().hasItemMeta()) - && (event.getItem().getItemMeta().getDisplayName() - .equals(structureTool.getItemMeta().getDisplayName()))) { - if (player.hasPermission("fabledskyblock.admin.structure.selection") - || player.hasPermission("fabledskyblock.admin.structure.*") + && (event.getItem().getItemMeta().getDisplayName().equals(structureTool.getItemMeta().getDisplayName()))) { + if (player.hasPermission("fabledskyblock.admin.structure.selection") || player.hasPermission("fabledskyblock.admin.structure.*") || player.hasPermission("fabledskyblock.admin.*") || player.hasPermission("fabledskyblock.*")) { event.setCancelled(true); - skyblock.getPlayerDataManager().getPlayerData(player).getArea().setPosition(1, - event.getClickedBlock().getLocation()); + skyblock.getPlayerDataManager().getPlayerData(player).getArea().setPosition(1, event.getClickedBlock().getLocation()); - messageManager.sendMessage(player, - skyblock.getFileManager() - .getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Structure.Tool.Position.Message") - .replace("%position", "1")); + messageManager.sendMessage(player, skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration() + .getString("Island.Structure.Tool.Position.Message").replace("%position", "1")); soundManager.playSound(player, Sounds.WOOD_CLICK.bukkitSound(), 1.0F, 1.0F); } } @@ -710,21 +646,15 @@ public class Interact implements Listener { ItemStack structureTool = StructureUtil.getTool(); if ((event.getItem().getType() == structureTool.getType()) && (event.getItem().hasItemMeta()) - && (event.getItem().getItemMeta().getDisplayName() - .equals(structureTool.getItemMeta().getDisplayName()))) { - if (player.hasPermission("fabledskyblock.admin.structure.selection") - || player.hasPermission("fabledskyblock.admin.structure.*") + && (event.getItem().getItemMeta().getDisplayName().equals(structureTool.getItemMeta().getDisplayName()))) { + if (player.hasPermission("fabledskyblock.admin.structure.selection") || player.hasPermission("fabledskyblock.admin.structure.*") || player.hasPermission("fabledskyblock.admin.*") || player.hasPermission("fabledskyblock.*")) { event.setCancelled(true); - skyblock.getPlayerDataManager().getPlayerData(player).getArea().setPosition(2, - event.getClickedBlock().getLocation()); + skyblock.getPlayerDataManager().getPlayerData(player).getArea().setPosition(2, event.getClickedBlock().getLocation()); - messageManager.sendMessage(player, - skyblock.getFileManager() - .getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Structure.Tool.Position.Message") - .replace("%position", "2")); + messageManager.sendMessage(player, skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration() + .getString("Island.Structure.Tool.Position.Message").replace("%position", "2")); soundManager.playSound(player, Sounds.WOOD_CLICK.bukkitSound(), 1.0F, 1.0F); } } @@ -752,9 +682,8 @@ public class Interact implements Listener { if (!islandManager.hasPermission(player, entity.getLocation(), "Leash")) { event.setCancelled(true); - messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); + messageManager.sendMessage(player, skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration() + .getString("Island.Settings.Permission.Message")); soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); return; @@ -770,10 +699,8 @@ public class Interact implements Listener { if (!islandManager.hasPermission(player, horse.getLocation(), "HorseInventory")) { event.setCancelled(true); - messageManager.sendMessage(player, - skyblock.getFileManager() - .getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); + messageManager.sendMessage(player, skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration() + .getString("Island.Settings.Permission.Message")); soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); return; @@ -782,10 +709,8 @@ public class Interact implements Listener { if (!islandManager.hasPermission(player, horse.getLocation(), "MobRiding")) { event.setCancelled(true); - messageManager.sendMessage(player, - skyblock.getFileManager() - .getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); + messageManager.sendMessage(player, skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration() + .getString("Island.Settings.Permission.Message")); soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); return; @@ -795,9 +720,8 @@ public class Interact implements Listener { if (!islandManager.hasPermission(player, entity.getLocation(), "MobRiding")) { event.setCancelled(true); - messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); + messageManager.sendMessage(player, skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration() + .getString("Island.Settings.Permission.Message")); soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); return; @@ -807,16 +731,14 @@ public class Interact implements Listener { if (!islandManager.hasPermission(player, entity.getLocation(), "EntityPlacement")) { event.setCancelled(true); skyblock.getMessageManager().sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); + skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration().getString("Island.Settings.Permission.Message")); skyblock.getSoundManager().playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); } } else if (entity.getType().equals(EntityType.ITEM_FRAME)) { if (!skyblock.getIslandManager().hasPermission(player, entity.getLocation(), "Storage")) { event.setCancelled(true); skyblock.getMessageManager().sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); + skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration().getString("Island.Settings.Permission.Message")); skyblock.getSoundManager().playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); } } else if (entity.getType() == EntityType.COW || entity.getType() == EntityType.MUSHROOM_COW) { @@ -824,9 +746,8 @@ public class Interact implements Listener { if (!islandManager.hasPermission(player, entity.getLocation(), "Milking")) { event.setCancelled(true); - messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); + messageManager.sendMessage(player, skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration() + .getString("Island.Settings.Permission.Message")); soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); return; @@ -837,8 +758,7 @@ public class Interact implements Listener { event.setCancelled(true); messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); + skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration().getString("Island.Settings.Permission.Message")); soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); return; @@ -848,8 +768,7 @@ public class Interact implements Listener { event.setCancelled(true); messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); + skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration().getString("Island.Settings.Permission.Message")); soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); return; @@ -859,8 +778,7 @@ public class Interact implements Listener { event.setCancelled(true); messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); + skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration().getString("Island.Settings.Permission.Message")); soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); return; @@ -870,8 +788,7 @@ public class Interact implements Listener { event.setCancelled(true); messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); + skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration().getString("Island.Settings.Permission.Message")); soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); return; @@ -879,24 +796,20 @@ public class Interact implements Listener { } if (entity.getType() == EntityType.HORSE) { - if (!(is.getType() == Material.GOLDEN_APPLE || is.getType() == Material.GOLDEN_CARROT - || is.getType() == Material.SUGAR || is.getType() == Material.WHEAT + if (!(is.getType() == Material.GOLDEN_APPLE || is.getType() == Material.GOLDEN_CARROT || is.getType() == Material.SUGAR || is.getType() == Material.WHEAT || is.getType() == Material.APPLE || is.getType() == Material.HAY_BLOCK)) { return; } - } else if (entity.getType() == EntityType.SHEEP || entity.getType() == EntityType.COW - || entity.getType() == EntityType.MUSHROOM_COW) { + } else if (entity.getType() == EntityType.SHEEP || entity.getType() == EntityType.COW || entity.getType() == EntityType.MUSHROOM_COW) { if (!(is.getType() == Material.WHEAT)) { return; } } else if (entity.getType() == EntityType.PIG) { - if (!(is.getType() == Materials.CARROT.parseMaterial() - || is.getType() == Materials.POTATO.parseMaterial())) { + if (!(is.getType() == Materials.CARROT.parseMaterial() || is.getType() == Materials.POTATO.parseMaterial())) { return; } } else if (entity.getType() == EntityType.CHICKEN) { - if (!(is.getType() == Materials.WHEAT_SEEDS.parseMaterial() || is.getType() == Material.PUMPKIN_SEEDS - || is.getType() == Material.MELON_SEEDS)) { + if (!(is.getType() == Materials.WHEAT_SEEDS.parseMaterial() || is.getType() == Material.PUMPKIN_SEEDS || is.getType() == Material.MELON_SEEDS)) { if (NMSUtil.getVersionNumber() > 8) { if (!(is.getType() == Materials.BEETROOT_SEEDS.parseMaterial())) { return; @@ -906,25 +819,19 @@ public class Interact implements Listener { } } } else if (entity.getType() == EntityType.WOLF) { - if (!(is.getType() == Material.BONE || is.getType() == Materials.PORKCHOP.parseMaterial() - || is.getType() == Materials.BEEF.parseMaterial() - || is.getType() == Materials.CHICKEN.parseMaterial() || is.getType() == Material.RABBIT - || is.getType() == Material.MUTTON || is.getType() == Material.ROTTEN_FLESH - || is.getType() == Materials.COOKED_PORKCHOP.parseMaterial() - || is.getType() == Material.COOKED_BEEF || is.getType() == Material.COOKED_CHICKEN + if (!(is.getType() == Material.BONE || is.getType() == Materials.PORKCHOP.parseMaterial() || is.getType() == Materials.BEEF.parseMaterial() + || is.getType() == Materials.CHICKEN.parseMaterial() || is.getType() == Material.RABBIT || is.getType() == Material.MUTTON || is.getType() == Material.ROTTEN_FLESH + || is.getType() == Materials.COOKED_PORKCHOP.parseMaterial() || is.getType() == Material.COOKED_BEEF || is.getType() == Material.COOKED_CHICKEN || is.getType() == Material.COOKED_RABBIT || is.getType() == Material.COOKED_MUTTON)) { return; } } else if (entity.getType() == EntityType.OCELOT) { - if (!(is.getType() == Materials.COD.parseMaterial() || is.getType() == Materials.SALMON.parseMaterial() - || is.getType() == Materials.TROPICAL_FISH.parseMaterial() + if (!(is.getType() == Materials.COD.parseMaterial() || is.getType() == Materials.SALMON.parseMaterial() || is.getType() == Materials.TROPICAL_FISH.parseMaterial() || is.getType() == Materials.PUFFERFISH.parseMaterial())) { return; } } else if (entity.getType() == EntityType.RABBIT) { - if (!(is.getType() == Materials.DANDELION.parseMaterial() - || is.getType() == Materials.CARROTS.parseMaterial() - || is.getType() == Material.GOLDEN_CARROT)) { + if (!(is.getType() == Materials.DANDELION.parseMaterial() || is.getType() == Materials.CARROTS.parseMaterial() || is.getType() == Material.GOLDEN_CARROT)) { return; } } else { @@ -955,8 +862,7 @@ public class Interact implements Listener { event.setCancelled(true); messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); + skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration().getString("Island.Settings.Permission.Message")); soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); } } @@ -964,8 +870,7 @@ public class Interact implements Listener { @EventHandler public void onPlayerDamageVehicle(VehicleDamageEvent event) { - if (!(event.getAttacker() instanceof Player)) - return; + if (!(event.getAttacker() instanceof Player)) return; Player player = (Player) event.getAttacker(); @@ -973,16 +878,14 @@ public class Interact implements Listener { event.setCancelled(true); skyblock.getMessageManager().sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); + skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration().getString("Island.Settings.Permission.Message")); skyblock.getSoundManager().playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); } } @EventHandler public void onPlayerDestroyVehicle(VehicleDestroyEvent event) { - if (!(event.getAttacker() instanceof Player)) - return; + if (!(event.getAttacker() instanceof Player)) return; Player player = (Player) event.getAttacker(); @@ -990,13 +893,11 @@ public class Interact implements Listener { event.setCancelled(true); skyblock.getMessageManager().sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); + skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration().getString("Island.Settings.Permission.Message")); skyblock.getSoundManager().playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); } } - @EventHandler(ignoreCancelled = true) public void onPlayerArmorStandManipulate(PlayerArmorStandManipulateEvent event) { if (skyblock.getStackableManager() != null && skyblock.getStackableManager().isStacked(event.getRightClicked().getLocation().getBlock().getLocation())) { @@ -1004,22 +905,19 @@ public class Interact implements Listener { } } - @EventHandler public void onPlayerInteractAtEntity(PlayerInteractEntityEvent event) { Player player = event.getPlayer(); org.bukkit.entity.Entity entity = event.getRightClicked(); - if (!skyblock.getWorldManager().isIslandWorld(entity.getWorld())) - return; + if (!skyblock.getWorldManager().isIslandWorld(entity.getWorld())) return; if (entity instanceof ArmorStand) { if (!skyblock.getIslandManager().hasPermission(player, entity.getLocation(), "ArmorStandUse")) { event.setCancelled(true); skyblock.getMessageManager().sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.Settings.Permission.Message")); + skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration().getString("Island.Settings.Permission.Message")); skyblock.getSoundManager().playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); } } diff --git a/src/main/java/com/songoda/skyblock/listeners/Move.java b/src/main/java/com/songoda/skyblock/listeners/Move.java index 6931a6ec..05f2d937 100644 --- a/src/main/java/com/songoda/skyblock/listeners/Move.java +++ b/src/main/java/com/songoda/skyblock/listeners/Move.java @@ -18,202 +18,204 @@ import org.bukkit.attribute.Attribute; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; +import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerMoveEvent; +import org.bukkit.event.player.PlayerTeleportEvent; import org.bukkit.potion.PotionEffect; import java.io.File; public class Move implements Listener { - private final SkyBlock skyblock; + private final SkyBlock skyblock; - public Move(SkyBlock skyblock) { - this.skyblock = skyblock; - } + public Move(SkyBlock skyblock) { + this.skyblock = skyblock; + } - @SuppressWarnings("deprecation") - @EventHandler - public void onPlayerMove(PlayerMoveEvent event) { - Player player = event.getPlayer(); + @SuppressWarnings("deprecation") + @EventHandler + public void onPlayerMove(PlayerMoveEvent event) { + Player player = event.getPlayer(); - Location from = event.getFrom(); - Location to = event.getTo(); + Location from = event.getFrom(); + Location to = event.getTo(); - if (to == null || (from.getBlockX() == to.getBlockX() && from.getBlockY() == to.getBlockY() && from.getBlockZ() == to.getBlockZ())) { - return; - } + if (to == null || (from.getBlockX() == to.getBlockX() && from.getBlockY() == to.getBlockY() && from.getBlockZ() == to.getBlockZ())) { + return; + } - PlayerDataManager playerDataManager = skyblock.getPlayerDataManager(); - MessageManager messageManager = skyblock.getMessageManager(); - IslandManager islandManager = skyblock.getIslandManager(); - SoundManager soundManager = skyblock.getSoundManager(); - WorldManager worldManager = skyblock.getWorldManager(); - FileManager fileManager = skyblock.getFileManager(); + PlayerDataManager playerDataManager = skyblock.getPlayerDataManager(); + MessageManager messageManager = skyblock.getMessageManager(); + IslandManager islandManager = skyblock.getIslandManager(); + SoundManager soundManager = skyblock.getSoundManager(); + WorldManager worldManager = skyblock.getWorldManager(); + FileManager fileManager = skyblock.getFileManager(); - if (!worldManager.isIslandWorld(player.getWorld())) - return; + if (!worldManager.isIslandWorld(player.getWorld())) return; - IslandWorld world = worldManager.getIslandWorld(player.getWorld()); + IslandWorld world = worldManager.getIslandWorld(player.getWorld()); - if (world == IslandWorld.Nether || world == IslandWorld.End) { - if (!fileManager.getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration() - .getBoolean("Island.World." + world.name() + ".Enable")) { - Config config = fileManager.getConfig(new File(skyblock.getDataFolder(), "language.yml")); - FileConfiguration configLoad = config.getFileConfiguration(); + if (world == IslandWorld.Nether || world == IslandWorld.End) { + if (!fileManager.getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration().getBoolean("Island.World." + world.name() + ".Enable")) { + Config config = fileManager.getConfig(new File(skyblock.getDataFolder(), "language.yml")); + FileConfiguration configLoad = config.getFileConfiguration(); - messageManager.sendMessage(player, configLoad.getString("Island.World.Message") - .replace(configLoad.getString("Island.World.Word." + world.name()), world.name())); + messageManager.sendMessage(player, configLoad.getString("Island.World.Message").replace(configLoad.getString("Island.World.Word." + world.name()), world.name())); - if (playerDataManager.hasPlayerData(player)) { - PlayerData playerData = playerDataManager.getPlayerData(player); + if (playerDataManager.hasPlayerData(player)) { + PlayerData playerData = playerDataManager.getPlayerData(player); - if (playerData.getIsland() != null) { - Island island = islandManager - .getIsland(Bukkit.getServer().getOfflinePlayer(playerData.getIsland())); + if (playerData.getIsland() != null) { + Island island = islandManager.getIsland(Bukkit.getServer().getOfflinePlayer(playerData.getIsland())); - if (island != null) { - if (island.hasRole(IslandRole.Member, player.getUniqueId()) - || island.hasRole(IslandRole.Operator, player.getUniqueId()) - || island.hasRole(IslandRole.Owner, player.getUniqueId())) { - player.teleport(island.getLocation(IslandWorld.Normal, IslandEnvironment.Main)); - } else { - player.teleport(island.getLocation(IslandWorld.Normal, IslandEnvironment.Visitor)); - } + if (island != null) { + if (island.hasRole(IslandRole.Member, player.getUniqueId()) || island.hasRole(IslandRole.Operator, player.getUniqueId()) + || island.hasRole(IslandRole.Owner, player.getUniqueId())) { + player.teleport(island.getLocation(IslandWorld.Normal, IslandEnvironment.Main)); + } else { + player.teleport(island.getLocation(IslandWorld.Normal, IslandEnvironment.Visitor)); + } - player.setFallDistance(0.0F); - soundManager.playSound(player, Sounds.ENDERMAN_TELEPORT.bukkitSound(), 1.0F, 1.0F); + player.setFallDistance(0.0F); + soundManager.playSound(player, Sounds.ENDERMAN_TELEPORT.bukkitSound(), 1.0F, 1.0F); - return; - } - } - } + return; + } + } + } - LocationUtil.teleportPlayerToSpawn(player); - soundManager.playSound(player, Sounds.ENDERMAN_TELEPORT.bukkitSound(), 1.0F, 1.0F); - } - } + LocationUtil.teleportPlayerToSpawn(player); + soundManager.playSound(player, Sounds.ENDERMAN_TELEPORT.bukkitSound(), 1.0F, 1.0F); + } + } - if (playerDataManager.hasPlayerData(player)) { - PlayerData playerData = playerDataManager.getPlayerData(player); + if (playerDataManager.hasPlayerData(player)) { + PlayerData playerData = playerDataManager.getPlayerData(player); - if (playerData.getIsland() != null) { - Island island = islandManager - .getIsland(Bukkit.getServer().getOfflinePlayer(playerData.getIsland())); + if (playerData.getIsland() != null) { + Island island = islandManager.getIsland(Bukkit.getServer().getOfflinePlayer(playerData.getIsland())); - if (island != null) { - if (islandManager.isLocationAtIsland(island, to)) { - Config config = fileManager.getConfig(new File(skyblock.getDataFolder(), "config.yml")); - FileConfiguration configLoad = config.getFileConfiguration(); + if (island != null) { + if (islandManager.isLocationAtIsland(island, to)) { + Config config = fileManager.getConfig(new File(skyblock.getDataFolder(), "config.yml")); + FileConfiguration configLoad = config.getFileConfiguration(); - boolean keepItemsOnDeath; + boolean keepItemsOnDeath; - if (configLoad.getBoolean("Island.Settings.KeepItemsOnDeath.Enable")) { - keepItemsOnDeath = island.getSetting(IslandRole.Owner, "KeepItemsOnDeath").getStatus(); - } else { - keepItemsOnDeath = configLoad.getBoolean("Island.KeepItemsOnDeath.Enable"); - } + if (configLoad.getBoolean("Island.Settings.KeepItemsOnDeath.Enable")) { + keepItemsOnDeath = island.getSetting(IslandRole.Owner, "KeepItemsOnDeath").getStatus(); + } else { + keepItemsOnDeath = configLoad.getBoolean("Island.KeepItemsOnDeath.Enable"); + } - if (configLoad.getBoolean("Island.World." + world.name() + ".Liquid.Enable")) { - if (to.getY() <= configLoad.getInt("Island.World." + world.name() + ".Liquid.Height")) { - if (keepItemsOnDeath && configLoad.getBoolean("Island.Liquid.Teleport.Enable")) { - player.setFallDistance(0.0F); + if (configLoad.getBoolean("Island.World." + world.name() + ".Liquid.Enable")) { + if (to.getY() <= configLoad.getInt("Island.World." + world.name() + ".Liquid.Height")) { + if (keepItemsOnDeath && configLoad.getBoolean("Island.Liquid.Teleport.Enable")) { + player.setFallDistance(0.0F); - if (island.hasRole(IslandRole.Member, player.getUniqueId()) - || island.hasRole(IslandRole.Operator, player.getUniqueId()) - || island.hasRole(IslandRole.Owner, player.getUniqueId())) { - player.teleport( - island.getLocation(IslandWorld.Normal, IslandEnvironment.Main)); - } else { - player.teleport( - island.getLocation(IslandWorld.Normal, IslandEnvironment.Visitor)); - } + if (island.hasRole(IslandRole.Member, player.getUniqueId()) || island.hasRole(IslandRole.Operator, player.getUniqueId()) + || island.hasRole(IslandRole.Owner, player.getUniqueId())) { + player.teleport(island.getLocation(IslandWorld.Normal, IslandEnvironment.Main)); + } else { + player.teleport(island.getLocation(IslandWorld.Normal, IslandEnvironment.Visitor)); + } - player.setFallDistance(0.0F); - soundManager.playSound(player, Sounds.ENDERMAN_TELEPORT.bukkitSound(), 1.0F, - 1.0F); - } - return; - } - } + player.setFallDistance(0.0F); + soundManager.playSound(player, Sounds.ENDERMAN_TELEPORT.bukkitSound(), 1.0F, 1.0F); + } + return; + } + } - if (configLoad.getBoolean("Island.Void.Teleport.Enable")) { - if (to.getY() <= configLoad.getInt("Island.Void.Teleport.Offset")) { - if (configLoad.getBoolean("Island.Void.Teleport.ClearInventory")) { - player.getInventory().clear(); - player.setLevel(0); - player.setExp(0.0F); + if (configLoad.getBoolean("Island.Void.Teleport.Enable")) { + if (to.getY() <= configLoad.getInt("Island.Void.Teleport.Offset")) { + if (configLoad.getBoolean("Island.Void.Teleport.ClearInventory")) { + player.getInventory().clear(); + player.setLevel(0); + player.setExp(0.0F); - if (NMSUtil.getVersionNumber() > 8) { - player.setHealth( - player.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue()); - } else { - player.setHealth(player.getMaxHealth()); - } + if (NMSUtil.getVersionNumber() > 8) { + player.setHealth(player.getAttribute(Attribute.GENERIC_MAX_HEALTH).getValue()); + } else { + player.setHealth(player.getMaxHealth()); + } - player.setFoodLevel(20); + player.setFoodLevel(20); - for (PotionEffect potionEffect : player.getActivePotionEffects()) { - player.removePotionEffect(potionEffect.getType()); - } - } + for (PotionEffect potionEffect : player.getActivePotionEffects()) { + player.removePotionEffect(potionEffect.getType()); + } + } - player.setFallDistance(0.0F); + player.setFallDistance(0.0F); - if (configLoad.getBoolean("Island.Void.Teleport.Island")) { - if (island.hasRole(IslandRole.Member, player.getUniqueId()) - || island.hasRole(IslandRole.Operator, player.getUniqueId()) - || island.hasRole(IslandRole.Owner, player.getUniqueId())) { - player.teleport( - island.getLocation(IslandWorld.Normal, IslandEnvironment.Main)); - } else { - player.teleport( - island.getLocation(IslandWorld.Normal, IslandEnvironment.Visitor)); - } - } else { - LocationUtil.teleportPlayerToSpawn(player); - } + if (configLoad.getBoolean("Island.Void.Teleport.Island")) { + if (island.hasRole(IslandRole.Member, player.getUniqueId()) || island.hasRole(IslandRole.Operator, player.getUniqueId()) + || island.hasRole(IslandRole.Owner, player.getUniqueId())) { + player.teleport(island.getLocation(IslandWorld.Normal, IslandEnvironment.Main)); + } else { + player.teleport(island.getLocation(IslandWorld.Normal, IslandEnvironment.Visitor)); + } + } else { + LocationUtil.teleportPlayerToSpawn(player); + } - player.setFallDistance(0.0F); - soundManager.playSound(player, Sounds.ENDERMAN_TELEPORT.bukkitSound(), 1.0F, 1.0F); - } - } - } else { - if (!LocationUtil.isLocationAtLocationRadius(island.getLocation(world, IslandEnvironment.Island), to, island.getRadius() + 0.5)) { - if (island.getVisit().isVisitor(player.getUniqueId())) { - player.teleport(island.getLocation(world, IslandEnvironment.Visitor)); - } else { - player.teleport(island.getLocation(world, IslandEnvironment.Main)); - } + player.setFallDistance(0.0F); + soundManager.playSound(player, Sounds.ENDERMAN_TELEPORT.bukkitSound(), 1.0F, 1.0F); + } + } + } else { + if (!LocationUtil.isLocationAtLocationRadius(island.getLocation(world, IslandEnvironment.Island), to, island.getRadius() + 0.5)) { + if (island.getVisit().isVisitor(player.getUniqueId())) { + player.teleport(island.getLocation(world, IslandEnvironment.Visitor)); + } else { + player.teleport(island.getLocation(world, IslandEnvironment.Main)); + } - player.setFallDistance(0.0F); - messageManager.sendMessage(player, skyblock.getFileManager() - .getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.WorldBorder.Outside.Message")); - soundManager.playSound(player, Sounds.ENDERMAN_TELEPORT.bukkitSound(), 1.0F, 1.0F); - } - } + player.setFallDistance(0.0F); + messageManager.sendMessage(player, skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration() + .getString("Island.WorldBorder.Outside.Message")); + soundManager.playSound(player, Sounds.ENDERMAN_TELEPORT.bukkitSound(), 1.0F, 1.0F); + } + } - return; - } - } + return; + } + } - // Load the island they are now on if one exists - if (player.hasPermission("fabledskyblock.bypass")) { - Island loadedIsland = islandManager.loadIslandAtLocation(player.getLocation()); - if (loadedIsland != null) { - playerData.setIsland(loadedIsland.getOwnerUUID()); - return; - } - } + // Load the island they are now on if one exists + if (player.hasPermission("fabledskyblock.bypass")) { + Island loadedIsland = islandManager.loadIslandAtLocation(player.getLocation()); + if (loadedIsland != null) { + playerData.setIsland(loadedIsland.getOwnerUUID()); + return; + } + } + LocationUtil.teleportPlayerToSpawn(player); - LocationUtil.teleportPlayerToSpawn(player); + messageManager.sendMessage(player, + skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration().getString("Island.WorldBorder.Disappeared.Message")); + soundManager.playSound(player, Sounds.ENDERMAN_TELEPORT.bukkitSound(), 1.0F, 1.0F); + } + } - messageManager.sendMessage(player, - skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Island.WorldBorder.Disappeared.Message")); - soundManager.playSound(player, Sounds.ENDERMAN_TELEPORT.bukkitSound(), 1.0F, 1.0F); - } - } + @EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) + public void onTeleport(PlayerTeleportEvent e) { + + final Player player = e.getPlayer(); + final WorldManager worldManager = skyblock.getWorldManager(); + + if (!worldManager.isIslandWorld(e.getTo().getWorld())) return; + if (skyblock.getIslandManager().getIslandAtLocation(e.getTo()) != null) return; + + e.setCancelled(true); + + skyblock.getMessageManager().sendMessage(player, + skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration().getString("Island.WorldBorder.Disappeared.Message")); + skyblock.getSoundManager().playSound(player, Sounds.ENDERMAN_TELEPORT.bukkitSound(), 1.0F, 1.0F); + + } } diff --git a/src/main/java/com/songoda/skyblock/listeners/Portal.java b/src/main/java/com/songoda/skyblock/listeners/Portal.java index f623ea07..360a8cbf 100644 --- a/src/main/java/com/songoda/skyblock/listeners/Portal.java +++ b/src/main/java/com/songoda/skyblock/listeners/Portal.java @@ -48,26 +48,25 @@ public class Portal implements Listener { FileManager fileManager = skyblock.getFileManager(); SoundManager soundManager = skyblock.getSoundManager(); + if (from.getX() == to.getX() && from.getY() == to.getY() && from.getZ() == to.getZ()) return; + Island island = islandManager.getIslandAtLocation(to.getLocation()); - if (from.getX() == to.getX() && from.getY() == to.getY() && from.getZ() == to.getZ()) - return; if (island == null) return; - if ((to.getType().equals(Materials.NETHER_PORTAL.parseMaterial()) || - to.getType().equals(Materials.END_PORTAL.parseMaterial())) && - !islandManager.hasPermission(player, player.getLocation(), "Portal")) { + + if ((to.getType().equals(Materials.NETHER_PORTAL.parseMaterial()) || to.getType().equals(Materials.END_PORTAL.parseMaterial())) + && !islandManager.hasPermission(player, player.getLocation(), "Portal")) { event.setTo(LocationUtil.getRandomLocation(event.getFrom().getWorld(), 5000, 5000, true, true)); messageManager.sendMessage(player, - fileManager.getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration() - .getString("Island.Settings.Permission.Message")); + fileManager.getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration().getString("Island.Settings.Permission.Message")); soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); } + } @EventHandler(priority = EventPriority.LOW) public void onEntityPortalEnter(EntityPortalEnterEvent event) { - if (!(event.getEntity() instanceof Player)) - return; + if (!(event.getEntity() instanceof Player)) return; Player player = (Player) event.getEntity(); org.bukkit.block.Block block = event.getLocation().getBlock(); @@ -78,8 +77,7 @@ public class Portal implements Listener { WorldManager worldManager = skyblock.getWorldManager(); FileManager fileManager = skyblock.getFileManager(); - if (!worldManager.isIslandWorld(player.getWorld())) - return; + if (!worldManager.isIslandWorld(player.getWorld())) return; Island island = islandManager.getIslandAtLocation(player.getLocation()); @@ -90,23 +88,22 @@ public class Portal implements Listener { if (!islandManager.hasPermission(player, player.getLocation(), "Portal")) { messageManager.sendMessage(player, - fileManager.getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration() - .getString("Island.Settings.Permission.Message")); + fileManager.getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration().getString("Island.Settings.Permission.Message")); soundManager.playSound(player, Sounds.VILLAGER_NO.bukkitSound(), 1.0F, 1.0F); return; } IslandEnvironment spawnEnvironment; switch (island.getRole(player)) { - case Operator: - case Owner: - case Member: - case Coop: - spawnEnvironment = IslandEnvironment.Island; - break; + case Operator: + case Owner: + case Member: + case Coop: + spawnEnvironment = IslandEnvironment.Island; + break; - default: - spawnEnvironment = IslandEnvironment.Visitor; + default: + spawnEnvironment = IslandEnvironment.Visitor; } Tick tick; @@ -123,9 +120,7 @@ public class Portal implements Listener { tick.setLast(System.currentTimeMillis()); } if (tick.getTick() >= 100) { - messageManager.sendMessage(player, - fileManager.getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration() - .getString("Island.Portal.Stuck.Message")); + messageManager.sendMessage(player, fileManager.getConfig(new File(skyblock.getDataFolder(), "language.yml")).getFileConfiguration().getString("Island.Portal.Stuck.Message")); soundManager.playSound(player, Sounds.ENDERMAN_TELEPORT.bukkitSound(), 1.0F, 1.0F); LocationUtil.teleportPlayerToSpawn(player); return; @@ -137,39 +132,37 @@ public class Portal implements Listener { IslandWorld fromWorld = worldManager.getIslandWorld(player.getWorld()); IslandWorld toWorld = IslandWorld.Normal; - if (block.getType().equals(Materials.NETHER_PORTAL.parseMaterial())) - toWorld = fromWorld.equals(IslandWorld.Normal) ? IslandWorld.Nether : IslandWorld.Normal; - else if (block.getType().equals(Materials.END_PORTAL.parseMaterial())) - toWorld = fromWorld.equals(IslandWorld.Normal) ? IslandWorld.End : IslandWorld.Normal; + if (block.getType().equals(Materials.NETHER_PORTAL.parseMaterial())) toWorld = fromWorld.equals(IslandWorld.Normal) ? IslandWorld.Nether : IslandWorld.Normal; + else if (block.getType().equals(Materials.END_PORTAL.parseMaterial())) toWorld = fromWorld.equals(IslandWorld.Normal) ? IslandWorld.End : IslandWorld.Normal; switch (toWorld) { - case Nether: - if (configLoad.getBoolean("Island.World.Nether.Enable") && island.isRegionUnlocked(player, "Nether")) { - IslandWorld toWorldF = toWorld; - Bukkit.getScheduler().scheduleSyncDelayedTask(skyblock, () -> player.teleport(island.getLocation(toWorldF, spawnEnvironment)), 1L); - soundManager.playSound(player, Sounds.ENDERMAN_TELEPORT.bukkitSound(), 1.0F, 1.0F); - player.setFallDistance(0.0F); - tick.setTick(1); - } - break; - - case End: - if (configLoad.getBoolean("Island.World.End.Enable") && island.isRegionUnlocked(player, "End")) { - IslandWorld toWorldF = toWorld; - Bukkit.getScheduler().scheduleSyncDelayedTask(skyblock, () -> player.teleport(island.getLocation(toWorldF, spawnEnvironment)), 1L); - soundManager.playSound(player, Sounds.ENDERMAN_TELEPORT.bukkitSound(), 1.0F, 1.0F); - player.setFallDistance(0.0F); - tick.setTick(1); - } - break; - - default: + case Nether: + if (configLoad.getBoolean("Island.World.Nether.Enable") && island.isRegionUnlocked(player, "Nether")) { IslandWorld toWorldF = toWorld; Bukkit.getScheduler().scheduleSyncDelayedTask(skyblock, () -> player.teleport(island.getLocation(toWorldF, spawnEnvironment)), 1L); soundManager.playSound(player, Sounds.ENDERMAN_TELEPORT.bukkitSound(), 1.0F, 1.0F); player.setFallDistance(0.0F); tick.setTick(1); - break; + } + break; + + case End: + if (configLoad.getBoolean("Island.World.End.Enable") && island.isRegionUnlocked(player, "End")) { + IslandWorld toWorldF = toWorld; + Bukkit.getScheduler().scheduleSyncDelayedTask(skyblock, () -> player.teleport(island.getLocation(toWorldF, spawnEnvironment)), 1L); + soundManager.playSound(player, Sounds.ENDERMAN_TELEPORT.bukkitSound(), 1.0F, 1.0F); + player.setFallDistance(0.0F); + tick.setTick(1); + } + break; + + default: + IslandWorld toWorldF = toWorld; + Bukkit.getScheduler().scheduleSyncDelayedTask(skyblock, () -> player.teleport(island.getLocation(toWorldF, spawnEnvironment)), 1L); + soundManager.playSound(player, Sounds.ENDERMAN_TELEPORT.bukkitSound(), 1.0F, 1.0F); + player.setFallDistance(0.0F); + tick.setTick(1); + break; } } diff --git a/src/main/java/com/songoda/skyblock/listeners/Spawner.java b/src/main/java/com/songoda/skyblock/listeners/Spawner.java index 6419c9f7..ef2f6338 100644 --- a/src/main/java/com/songoda/skyblock/listeners/Spawner.java +++ b/src/main/java/com/songoda/skyblock/listeners/Spawner.java @@ -54,7 +54,7 @@ public class Spawner implements Listener { Object TileEntityMobSpawner = TileEntityMobSpawnerField.get(spawner); MobSpawner = TileEntityMobSpawner.getClass().getMethod("getSpawner") .invoke(TileEntityMobSpawner); - } catch (NoSuchFieldException e) { + } catch (NoSuchFieldException ignored) { Field snapshotField = spawner.getClass().getSuperclass().getDeclaredField("snapshot"); snapshotField.setAccessible(true); Object snapshot = snapshotField.get(spawner); @@ -92,6 +92,8 @@ public class Spawner implements Listener { e.printStackTrace(); } } + + spawner.update(); } return; diff --git a/src/main/java/com/songoda/skyblock/listeners/Teleport.java b/src/main/java/com/songoda/skyblock/listeners/Teleport.java index 5eee7653..4fc05a93 100644 --- a/src/main/java/com/songoda/skyblock/listeners/Teleport.java +++ b/src/main/java/com/songoda/skyblock/listeners/Teleport.java @@ -57,8 +57,7 @@ public class Teleport implements Listener { if (worldManager.isIslandWorld(player.getWorld())) { boolean isCause = false; - if (event.getCause() == TeleportCause.ENDER_PEARL || event.getCause() == TeleportCause.NETHER_PORTAL - || event.getCause() == TeleportCause.END_PORTAL) { + if (event.getCause() == TeleportCause.ENDER_PEARL || event.getCause() == TeleportCause.NETHER_PORTAL || event.getCause() == TeleportCause.END_PORTAL) { isCause = true; } else { if (NMSUtil.getVersionNumber() > 9) { @@ -90,27 +89,23 @@ public class Teleport implements Listener { if (island != null) { if (!island.getOwnerUUID().equals(playerData.getOwner())) { - if (!player.hasPermission("fabledskyblock.bypass") && !player.hasPermission("fabledskyblock.bypass.*") - && !player.hasPermission("fabledskyblock.*")) { + if (!player.hasPermission("fabledskyblock.bypass") && !player.hasPermission("fabledskyblock.bypass.*") && !player.hasPermission("fabledskyblock.*")) { if (!island.isOpen() && !island.isCoopPlayer(player.getUniqueId())) { event.setCancelled(true); - messageManager.sendMessage(player, - configLoad.getString("Island.Visit.Closed.Plugin.Message")); + messageManager.sendMessage(player, configLoad.getString("Island.Visit.Closed.Plugin.Message")); soundManager.playSound(player, Sounds.ANVIL_LAND.bukkitSound(), 1.0F, 1.0F); return; - } else if (fileManager.getConfig(new File(skyblock.getDataFolder(), "config.yml")) - .getFileConfiguration().getBoolean("Island.Visitor.Banning") + } else if (fileManager.getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration().getBoolean("Island.Visitor.Banning") && island.getBan().isBanned(player.getUniqueId())) { - event.setCancelled(true); + event.setCancelled(true); - messageManager.sendMessage(player, - configLoad.getString("Island.Visit.Banned.Teleport.Message")); - soundManager.playSound(player, Sounds.ANVIL_LAND.bukkitSound(), 1.0F, 1.0F); + messageManager.sendMessage(player, configLoad.getString("Island.Visit.Banned.Teleport.Message")); + soundManager.playSound(player, Sounds.ANVIL_LAND.bukkitSound(), 1.0F, 1.0F); - return; - } + return; + } } } @@ -124,8 +119,7 @@ public class Teleport implements Listener { } Bukkit.getServer().getPluginManager().callEvent(new PlayerIslandExitEvent(player, exitIsland)); - Bukkit.getServer().getPluginManager() - .callEvent(new PlayerIslandSwitchEvent(player, exitIsland, island.getAPIWrapper())); + Bukkit.getServer().getPluginManager().callEvent(new PlayerIslandSwitchEvent(player, exitIsland, island.getAPIWrapper())); playerData.setVisitTime(0); } @@ -133,8 +127,7 @@ public class Teleport implements Listener { if (worldManager.getIslandWorld(event.getTo().getWorld()) == IslandWorld.Normal) { if (!island.isWeatherSynchronized()) { player.setPlayerTime(island.getTime(), - fileManager.getConfig(new File(skyblock.getDataFolder(), "config.yml")) - .getFileConfiguration().getBoolean("Island.Weather.Time.Cycle")); + fileManager.getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration().getBoolean("Island.Weather.Time.Cycle")); player.setPlayerWeather(island.getWeather()); } } @@ -142,17 +135,14 @@ public class Teleport implements Listener { UUID islandOwnerUUID = playerData.getIsland(); playerData.setIsland(island.getOwnerUUID()); - if (islandOwnerUUID != null && islandManager.containsIsland(islandOwnerUUID) - && (playerData.getOwner() == null || !playerData.getOwner().equals(islandOwnerUUID))) { - islandManager.unloadIsland( - islandManager.getIsland(Bukkit.getServer().getOfflinePlayer(islandOwnerUUID)), null); + if (islandOwnerUUID != null && islandManager.containsIsland(islandOwnerUUID) && (playerData.getOwner() == null || !playerData.getOwner().equals(islandOwnerUUID))) { + islandManager.unloadIsland(islandManager.getIsland(Bukkit.getServer().getOfflinePlayer(islandOwnerUUID)), null); } Visit visit = island.getVisit(); if (!visit.isVisitor(player.getUniqueId())) { - Bukkit.getServer().getPluginManager() - .callEvent(new PlayerIslandEnterEvent(player, island.getAPIWrapper())); + Bukkit.getServer().getPluginManager().callEvent(new PlayerIslandEnterEvent(player, island.getAPIWrapper())); visit.addVisitor(player.getUniqueId()); visit.save(); @@ -180,10 +170,8 @@ public class Teleport implements Listener { UUID islandOwnerUUID = playerData.getIsland(); playerData.setIsland(null); - if (islandOwnerUUID != null && islandManager.containsIsland(islandOwnerUUID) - && (playerData.getOwner() == null || !playerData.getOwner().equals(islandOwnerUUID))) { - islandManager.unloadIsland( - islandManager.getIsland(Bukkit.getServer().getOfflinePlayer(islandOwnerUUID)), null); + if (islandOwnerUUID != null && islandManager.containsIsland(islandOwnerUUID) && (playerData.getOwner() == null || !playerData.getOwner().equals(islandOwnerUUID))) { + islandManager.unloadIsland(islandManager.getIsland(Bukkit.getServer().getOfflinePlayer(islandOwnerUUID)), null); } } } diff --git a/src/main/java/com/songoda/skyblock/menus/ControlPanel.java b/src/main/java/com/songoda/skyblock/menus/ControlPanel.java index 3ae34b5a..60d4c926 100644 --- a/src/main/java/com/songoda/skyblock/menus/ControlPanel.java +++ b/src/main/java/com/songoda/skyblock/menus/ControlPanel.java @@ -1,11 +1,7 @@ package com.songoda.skyblock.menus; -import com.songoda.skyblock.SkyBlock; -import com.songoda.skyblock.config.FileManager.Config; -import com.songoda.skyblock.island.Island; -import com.songoda.skyblock.utils.item.nInventoryUtil; -import com.songoda.skyblock.utils.version.Materials; -import com.songoda.skyblock.utils.version.Sounds; +import java.io.File; + import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; @@ -14,123 +10,116 @@ import org.bukkit.entity.Player; import org.bukkit.inventory.ItemFlag; import org.bukkit.inventory.ItemStack; -import java.io.File; +import com.songoda.skyblock.SkyBlock; +import com.songoda.skyblock.config.FileManager.Config; +import com.songoda.skyblock.island.Island; +import com.songoda.skyblock.utils.item.MenuClickRegistry; +import com.songoda.skyblock.utils.item.MenuClickRegistry.RegistryKey; +import com.songoda.skyblock.utils.item.nInventoryUtil; +import com.songoda.skyblock.utils.version.Materials; +import com.songoda.skyblock.utils.version.Sounds; -public class ControlPanel { +public final class ControlPanel { private static ControlPanel instance; public static ControlPanel getInstance() { - if (instance == null) { - instance = new ControlPanel(); - } + return instance == null ? instance = new ControlPanel() : instance; + } + + private ControlPanel() { + + MenuClickRegistry.getInstance().register((executors) -> { + + executors.put(RegistryKey.fromLanguageFile("Menu.ControlPanel.Item.Teleport.Displayname", Materials.OAK_DOOR), (inst, player, e) -> { + Bukkit.getServer().getScheduler().runTaskLater(inst, () -> Bukkit.getServer().dispatchCommand(player, "island teleport"), 1L); + }); + + executors.put(RegistryKey.fromLanguageFile("Menu.ControlPanel.Item.Lock.Displayname", Materials.IRON_DOOR), (inst, player, e) -> { + + final Island island = SkyBlock.getInstance().getIslandManager().getIsland((Player) player); + + if (island.isOpen()) { + Bukkit.getServer().getScheduler().runTaskLater(inst, () -> Bukkit.getServer().dispatchCommand(player, "island close"), 1L); + } else { + Bukkit.getServer().getScheduler().runTaskLater(inst, () -> Bukkit.getServer().dispatchCommand(player, "island open"), 1L); + } + }); + + executors.put(RegistryKey.fromLanguageFile("Menu.ControlPanel.Item.Barrier.Displayname", Materials.BLACK_STAINED_GLASS_PANE), (inst, player, e) -> { + inst.getSoundManager().playSound(player, Sounds.GLASS.bukkitSound(), 1.0F, 1.0F); + + e.setWillClose(false); + e.setWillDestroy(false); + }); + + executors.put(RegistryKey.fromLanguageFile("Menu.ControlPanel.Item.Level.Displayname", Materials.EXPERIENCE_BOTTLE), (inst, player, e) -> { + Bukkit.getServer().getScheduler().runTaskLater(inst, () -> Bukkit.getServer().dispatchCommand(player, "island level"), 1L); + }); + executors.put(RegistryKey.fromLanguageFile("Menu.ControlPanel.Item.Settings.Displayname", Materials.NAME_TAG), (inst, player, e) -> { + Bukkit.getServer().getScheduler().runTaskLater(inst, () -> Bukkit.getServer().dispatchCommand(player, "island settings"), 1L); + }); + executors.put(RegistryKey.fromLanguageFile("Menu.ControlPanel.Item.Members.Displayname", Materials.ITEM_FRAME), (inst, player, e) -> { + Bukkit.getServer().getScheduler().runTaskLater(inst, () -> Bukkit.getServer().dispatchCommand(player, "island members"), 1L); + }); + executors.put(RegistryKey.fromLanguageFile("Menu.ControlPanel.Item.Biome.Displayname", Materials.OAK_SAPLING), (inst, player, e) -> { + Bukkit.getServer().getScheduler().runTaskLater(inst, () -> Bukkit.getServer().dispatchCommand(player, "island biome"), 1L); + }); + executors.put(RegistryKey.fromLanguageFile("Menu.ControlPanel.Item.Weather.Displayname", Materials.CLOCK), (inst, player, e) -> { + Bukkit.getServer().getScheduler().runTaskLater(inst, () -> Bukkit.getServer().dispatchCommand(player, "island weather"), 1L); + }); + executors.put(RegistryKey.fromLanguageFile("Menu.ControlPanel.Item.Bans.Displayname", Materials.IRON_AXE), (inst, player, e) -> { + Bukkit.getServer().getScheduler().runTaskLater(inst, () -> Bukkit.getServer().dispatchCommand(player, "island bans"), 1L); + }); + executors.put(RegistryKey.fromLanguageFile("Menu.ControlPanel.Item.Visitors.Displayname", Materials.OAK_SIGN), (inst, player, e) -> { + Bukkit.getServer().getScheduler().runTaskLater(inst, () -> Bukkit.getServer().dispatchCommand(player, "island visitors"), 1L); + }); + executors.put(RegistryKey.fromLanguageFile("Menu.ControlPanel.Item.Upgrades.Displayname", Materials.ANVIL), (inst, player, e) -> { + Bukkit.getServer().getScheduler().runTaskLater(inst, () -> Bukkit.getServer().dispatchCommand(player, "island upgrades"), 1L); + }); + + }); - return instance; } public void open(Player player) { SkyBlock skyblock = SkyBlock.getInstance(); - Island island = skyblock.getIslandManager().getIsland(player); Config config = skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "language.yml")); FileConfiguration configLoad = config.getFileConfiguration(); nInventoryUtil nInv = new nInventoryUtil(player, event -> { - ItemStack is = event.getItem(); - - if ((is.getType() == Materials.OAK_DOOR.parseMaterial()) && (is.hasItemMeta()) - && (is.getItemMeta().getDisplayName().equals(ChatColor.translateAlternateColorCodes('&', - configLoad.getString("Menu.ControlPanel.Item.Teleport.Displayname"))))) { - Bukkit.getServer().getScheduler().runTaskLater(skyblock, () -> Bukkit.getServer().dispatchCommand(player, "island teleport"), 1L); - } else if ((is.getType() == Materials.IRON_DOOR.parseMaterial()) && (is.hasItemMeta()) - && (is.getItemMeta().getDisplayName().equals(ChatColor.translateAlternateColorCodes('&', - configLoad.getString("Menu.ControlPanel.Item.Lock.Displayname"))))) { - if (island.isOpen()) { - Bukkit.getServer().getScheduler().runTaskLater(skyblock, () -> Bukkit.getServer().dispatchCommand(player, "island close"), 1L); - } else { - Bukkit.getServer().getScheduler().runTaskLater(skyblock, () -> Bukkit.getServer().dispatchCommand(player, "island open"), 1L); - } - } else if ((is.getType() == Materials.BLACK_STAINED_GLASS_PANE.parseMaterial()) && (is.hasItemMeta()) - && (is.getItemMeta().getDisplayName().equals(ChatColor.translateAlternateColorCodes('&', - configLoad.getString("Menu.ControlPanel.Item.Barrier.Displayname"))))) { - skyblock.getSoundManager().playSound(player, Sounds.GLASS.bukkitSound(), 1.0F, 1.0F); - - event.setWillClose(false); - event.setWillDestroy(false); - } else if ((is.getType() == Materials.EXPERIENCE_BOTTLE.parseMaterial()) && (is.hasItemMeta()) - && (is.getItemMeta().getDisplayName().equals(ChatColor.translateAlternateColorCodes('&', - configLoad.getString("Menu.ControlPanel.Item.Level.Displayname"))))) { - Bukkit.getServer().getScheduler().runTaskLater(skyblock, () -> Bukkit.getServer().dispatchCommand(player, "island level"), 1L); - } else if ((is.getType() == Material.NAME_TAG) && (is.hasItemMeta()) - && (is.getItemMeta().getDisplayName().equals(ChatColor.translateAlternateColorCodes('&', - configLoad.getString("Menu.ControlPanel.Item.Settings.Displayname"))))) { - Bukkit.getServer().getScheduler().runTaskLater(skyblock, () -> Bukkit.getServer().dispatchCommand(player, "island settings"), 1L); - } else if ((is.getType() == Material.ITEM_FRAME) && (is.hasItemMeta()) - && (is.getItemMeta().getDisplayName().equals(ChatColor.translateAlternateColorCodes('&', - configLoad.getString("Menu.ControlPanel.Item.Members.Displayname"))))) { - Bukkit.getServer().getScheduler().runTaskLater(skyblock, () -> Bukkit.getServer().dispatchCommand(player, "island members"), 1L); - } else if ((is.getType() == Materials.OAK_SAPLING.parseMaterial()) && (is.hasItemMeta()) - && (is.getItemMeta().getDisplayName().equals(ChatColor.translateAlternateColorCodes('&', - configLoad.getString("Menu.ControlPanel.Item.Biome.Displayname"))))) { - Bukkit.getServer().getScheduler().runTaskLater(skyblock, () -> Bukkit.getServer().dispatchCommand(player, "island biome"), 1L); - } else if ((is.getType() == Materials.CLOCK.parseMaterial()) && (is.hasItemMeta()) - && (is.getItemMeta().getDisplayName().equals(ChatColor.translateAlternateColorCodes('&', - configLoad.getString("Menu.ControlPanel.Item.Weather.Displayname"))))) { - Bukkit.getServer().getScheduler().runTaskLater(skyblock, () -> Bukkit.getServer().dispatchCommand(player, "island weather"), 1L); - } else if ((is.getType() == Material.IRON_AXE) && (is.hasItemMeta()) - && (is.getItemMeta().getDisplayName().equals(ChatColor.translateAlternateColorCodes('&', - configLoad.getString("Menu.ControlPanel.Item.Bans.Displayname"))))) { - Bukkit.getServer().getScheduler().runTaskLater(skyblock, () -> Bukkit.getServer().dispatchCommand(player, "island bans"), 1L); - } else if ((is.getType() == Materials.OAK_SIGN.parseMaterial()) && (is.hasItemMeta()) - && (is.getItemMeta().getDisplayName().equals(ChatColor.translateAlternateColorCodes('&', - configLoad.getString("Menu.ControlPanel.Item.Visitors.Displayname"))))) { - Bukkit.getServer().getScheduler().runTaskLater(skyblock, () -> Bukkit.getServer().dispatchCommand(player, "island visitors"), 1L); - } else if ((is.getType() == Materials.ANVIL.parseMaterial()) && (is.hasItemMeta()) - && (is.getItemMeta().getDisplayName().equals(ChatColor.translateAlternateColorCodes('&', - configLoad.getString("Menu.ControlPanel.Item.Upgrades.Displayname"))))) { - Bukkit.getServer().getScheduler().runTaskLater(skyblock, () -> Bukkit.getServer().dispatchCommand(player, "island upgrades"), 1L); - } + MenuClickRegistry.getInstance().dispatch(player, event); }); // Teleport to island and open/close island - nInv.addItem(nInv.createItem(Materials.OAK_DOOR.parseItem(), - configLoad.getString("Menu.ControlPanel.Item.Teleport.Displayname"), + nInv.addItem(nInv.createItem(Materials.OAK_DOOR.parseItem(), configLoad.getString("Menu.ControlPanel.Item.Teleport.Displayname"), configLoad.getStringList("Menu.ControlPanel.Item.Teleport.Lore"), null, null, null), 1); - nInv.addItem(nInv.createItem(Materials.IRON_DOOR.parseItem(), - configLoad.getString("Menu.ControlPanel.Item.Lock.Displayname"), + nInv.addItem(nInv.createItem(Materials.IRON_DOOR.parseItem(), configLoad.getString("Menu.ControlPanel.Item.Lock.Displayname"), configLoad.getStringList("Menu.ControlPanel.Item.Lock.Lore"), null, null, null), 10); // Glass panes barriers - nInv.addItem(nInv.createItem(Materials.BLACK_STAINED_GLASS_PANE.parseItem(), - configLoad.getString("Menu.ControlPanel.Item.Barrier.Displayname"), null, null, null, null), 0, 2, 5, 8, 9, 11, 14, 17); + nInv.addItem(nInv.createItem(Materials.BLACK_STAINED_GLASS_PANE.parseItem(), configLoad.getString("Menu.ControlPanel.Item.Barrier.Displayname"), null, null, null, null), 0, 2, 5, 8, + 9, 11, 14, 17); // 4 Items at the left - nInv.addItem(nInv.createItem(new ItemStack(Materials.EXPERIENCE_BOTTLE.parseMaterial()), - configLoad.getString("Menu.ControlPanel.Item.Level.Displayname"), + nInv.addItem(nInv.createItem(new ItemStack(Materials.EXPERIENCE_BOTTLE.parseMaterial()), configLoad.getString("Menu.ControlPanel.Item.Level.Displayname"), configLoad.getStringList("Menu.ControlPanel.Item.Level.Lore"), null, null, null), 3); - nInv.addItem(nInv.createItem(new ItemStack(Material.NAME_TAG), - configLoad.getString("Menu.ControlPanel.Item.Settings.Displayname"), + nInv.addItem(nInv.createItem(new ItemStack(Material.NAME_TAG), configLoad.getString("Menu.ControlPanel.Item.Settings.Displayname"), configLoad.getStringList("Menu.ControlPanel.Item.Settings.Lore"), null, null, null), 4); - nInv.addItem(nInv.createItem(Materials.CLOCK.parseItem(), - configLoad.getString("Menu.ControlPanel.Item.Weather.Displayname"), + nInv.addItem(nInv.createItem(Materials.CLOCK.parseItem(), configLoad.getString("Menu.ControlPanel.Item.Weather.Displayname"), configLoad.getStringList("Menu.ControlPanel.Item.Weather.Lore"), null, null, null), 12); - nInv.addItem(nInv.createItem(Materials.OAK_SAPLING.parseItem(), - configLoad.getString("Menu.ControlPanel.Item.Biome.Displayname"), + nInv.addItem(nInv.createItem(Materials.OAK_SAPLING.parseItem(), configLoad.getString("Menu.ControlPanel.Item.Biome.Displayname"), configLoad.getStringList("Menu.ControlPanel.Item.Biome.Lore"), null, null, null), 13); // 4 Items at the right - nInv.addItem(nInv.createItem(new ItemStack(Material.ITEM_FRAME), - configLoad.getString("Menu.ControlPanel.Item.Members.Displayname"), + nInv.addItem(nInv.createItem(new ItemStack(Material.ITEM_FRAME), configLoad.getString("Menu.ControlPanel.Item.Members.Displayname"), configLoad.getStringList("Menu.ControlPanel.Item.Members.Lore"), null, null, null), 16); - nInv.addItem(nInv.createItem(new ItemStack(Material.IRON_AXE), - configLoad.getString("Menu.ControlPanel.Item.Bans.Displayname"), - configLoad.getStringList("Menu.ControlPanel.Item.Bans.Lore"), null, null, - new ItemFlag[]{ItemFlag.HIDE_ATTRIBUTES}), 6); - nInv.addItem(nInv.createItem(new ItemStack(Materials.OAK_SIGN.parseMaterial()), - configLoad.getString("Menu.ControlPanel.Item.Visitors.Displayname"), + nInv.addItem(nInv.createItem(new ItemStack(Material.IRON_AXE), configLoad.getString("Menu.ControlPanel.Item.Bans.Displayname"), + configLoad.getStringList("Menu.ControlPanel.Item.Bans.Lore"), null, null, new ItemFlag[] { ItemFlag.HIDE_ATTRIBUTES }), 6); + nInv.addItem(nInv.createItem(new ItemStack(Materials.OAK_SIGN.parseMaterial()), configLoad.getString("Menu.ControlPanel.Item.Visitors.Displayname"), configLoad.getStringList("Menu.ControlPanel.Item.Visitors.Lore"), null, null, null), 7); - nInv.addItem(nInv.createItem(new ItemStack(Materials.ANVIL.parseMaterial()), - configLoad.getString("Menu.ControlPanel.Item.Upgrades.Displayname"), + nInv.addItem(nInv.createItem(new ItemStack(Materials.ANVIL.parseMaterial()), configLoad.getString("Menu.ControlPanel.Item.Upgrades.Displayname"), configLoad.getStringList("Menu.ControlPanel.Item.Upgrades.Lore"), null, null, null), 15); nInv.setTitle(ChatColor.translateAlternateColorCodes('&', configLoad.getString("Menu.ControlPanel.Title"))); diff --git a/src/main/java/com/songoda/skyblock/placeholder/PlaceholderManager.java b/src/main/java/com/songoda/skyblock/placeholder/PlaceholderManager.java index 357c18c3..b944a73f 100644 --- a/src/main/java/com/songoda/skyblock/placeholder/PlaceholderManager.java +++ b/src/main/java/com/songoda/skyblock/placeholder/PlaceholderManager.java @@ -116,14 +116,7 @@ public class PlaceholderManager { .replace("%placeholder", "" + island.getRadius())); } } else if (placeholder.equalsIgnoreCase("fabledskyblock_island_level")) { - if (island == null) { - return ChatColor.translateAlternateColorCodes('&', - configLoad.getString("Placeholder.fabledskyblock_island_level.Empty.Message")); - } else { - return ChatColor.translateAlternateColorCodes('&', - configLoad.getString("Placeholder.fabledskyblock_island_level.Non-empty.Message") - .replace("%placeholder", "" + island.getLevel().getLevel())); - } + return island == null ? "0": Long.toString(island.getLevel().getLevel()); } else if (placeholder.equalsIgnoreCase("fabledskyblock_island_level_formatted")) { if (island == null) { return ChatColor.translateAlternateColorCodes('&', @@ -134,14 +127,7 @@ public class PlaceholderManager { "%placeholder", "" + NumberUtil.formatNumberBySuffix(island.getLevel().getLevel()))); } } else if (placeholder.equalsIgnoreCase("fabledskyblock_island_points")) { - if (island == null) { - return ChatColor.translateAlternateColorCodes('&', - configLoad.getString("Placeholder.fabledskyblock_island_points.Empty.Message")); - } else { - return ChatColor.translateAlternateColorCodes('&', - configLoad.getString("Placeholder.fabledskyblock_island_points.Non-empty.Message") - .replace("%placeholder", "" + island.getLevel().getPoints())); - } + return island == null ? "0": Long.toString(island.getLevel().getPoints()); } else if (placeholder.equalsIgnoreCase("fabledskyblock_island_votes")) { if (island == null) { return ChatColor.translateAlternateColorCodes('&', diff --git a/src/main/java/com/songoda/skyblock/playerdata/PlayerData.java b/src/main/java/com/songoda/skyblock/playerdata/PlayerData.java index 082d0010..1d5e0d23 100644 --- a/src/main/java/com/songoda/skyblock/playerdata/PlayerData.java +++ b/src/main/java/com/songoda/skyblock/playerdata/PlayerData.java @@ -4,6 +4,8 @@ import com.songoda.skyblock.SkyBlock; import com.songoda.skyblock.config.FileManager.Config; import com.songoda.skyblock.confirmation.Confirmation; import com.songoda.skyblock.utils.structure.Area; + +import org.bukkit.Bukkit; import org.bukkit.configuration.file.FileConfiguration; import org.bukkit.entity.Player; @@ -146,7 +148,7 @@ public class PlayerData { public String[] getTexture() { FileConfiguration configLoad = getConfig().getFileConfiguration(); - return new String[]{configLoad.getString("Texture.Signature"), configLoad.getString("Texture.Value")}; + return new String[] { configLoad.getString("Texture.Signature"), configLoad.getString("Texture.Value") }; } public void setTexture(String signature, String value) { @@ -161,6 +163,23 @@ public class PlayerData { public void setLastOnline(String date) { getConfig().getFileConfiguration().set("Statistics.Island.LastOnline", date); } + + public long getIslandCreationCount() { + return getConfig().getFileConfiguration().getLong("Statistics.Island.IslandCreationCount"); + } + + public long getIslandDeletionCount() { + return getConfig().getFileConfiguration().getLong("Statistics.Island.IslandDeleteCount"); + } + + public void setIslandCreationCount(long newNumber) { + getConfig().getFileConfiguration().set("Statistics.Island.IslandCreationCount", newNumber); + } + + public void setIslandDeletionCount(long newNumber) { + getConfig().getFileConfiguration().set("Statistics.Island.IslandDeleteCount", newNumber); + } + public Area getArea() { return area; @@ -197,7 +216,11 @@ public class PlayerData { private Config getConfig() { SkyBlock skyblock = SkyBlock.getInstance(); - return skyblock.getFileManager().getConfig( - new File(new File(skyblock.getDataFolder().toString() + "/player-data"), uuid.toString() + ".yml")); + return skyblock.getFileManager().getConfig(new File(new File(skyblock.getDataFolder().toString() + "/player-data"), uuid.toString() + ".yml")); } + + public Player getPlayer() { + return Bukkit.getPlayer(uuid); + } + } diff --git a/src/main/java/com/songoda/skyblock/playerdata/PlayerDataManager.java b/src/main/java/com/songoda/skyblock/playerdata/PlayerDataManager.java index 09b3d42a..74b923a5 100644 --- a/src/main/java/com/songoda/skyblock/playerdata/PlayerDataManager.java +++ b/src/main/java/com/songoda/skyblock/playerdata/PlayerDataManager.java @@ -117,12 +117,20 @@ public class PlayerDataManager { return playerDataStorage; } + public PlayerData getPlayerData(UUID uuid) { + return playerDataStorage.get(uuid); + } + + public boolean hasPlayerData(UUID uuid) { + return playerDataStorage.containsKey(uuid); + } + public PlayerData getPlayerData(Player player) { - return playerDataStorage.get(player.getUniqueId()); + return getPlayerData(player.getUniqueId()); } public boolean hasPlayerData(Player player) { - return playerDataStorage.containsKey(player.getUniqueId()); + return hasPlayerData(player.getUniqueId()); } public void storeIsland(Player player) { diff --git a/src/main/java/com/songoda/skyblock/scoreboard/Scoreboard.java b/src/main/java/com/songoda/skyblock/scoreboard/Scoreboard.java index 0138f2cc..6d4cc2ce 100644 --- a/src/main/java/com/songoda/skyblock/scoreboard/Scoreboard.java +++ b/src/main/java/com/songoda/skyblock/scoreboard/Scoreboard.java @@ -1,13 +1,10 @@ package com.songoda.skyblock.scoreboard; -import com.songoda.skyblock.SkyBlock; -import com.songoda.skyblock.island.Island; -import com.songoda.skyblock.island.IslandLevel; -import com.songoda.skyblock.island.IslandManager; -import com.songoda.skyblock.island.IslandRole; -import com.songoda.skyblock.placeholder.PlaceholderManager; -import com.songoda.skyblock.utils.NumberUtil; -import com.songoda.skyblock.utils.version.NMSUtil; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; import org.bukkit.Bukkit; import org.bukkit.ChatColor; @@ -18,13 +15,20 @@ import org.bukkit.scoreboard.DisplaySlot; import org.bukkit.scoreboard.Objective; import org.bukkit.scoreboard.Team; -import java.util.*; +import com.songoda.skyblock.SkyBlock; +import com.songoda.skyblock.island.Island; +import com.songoda.skyblock.island.IslandLevel; +import com.songoda.skyblock.island.IslandManager; +import com.songoda.skyblock.island.IslandRole; +import com.songoda.skyblock.placeholder.PlaceholderManager; +import com.songoda.skyblock.utils.NumberUtil; +import com.songoda.skyblock.utils.version.NMSUtil; public class Scoreboard { private final SkyBlock plugin; - private final Player player; + private String displayName; private List displayList; private Map displayVariables; @@ -72,8 +76,7 @@ public class Scoreboard { obj.setDisplaySlot(DisplaySlot.SIDEBAR); - String formattedDisplayName = ChatColor.translateAlternateColorCodes('&', - replaceDisplayName(displayName)); + String formattedDisplayName = ChatColor.translateAlternateColorCodes('&', replaceDisplayName(displayName)); int max = NMSUtil.getVersionNumber() > 8 ? 32 : 16; if (formattedDisplayName.length() > max) { obj.setDisplayName(ChatColor.RED + "Too long..."); @@ -100,8 +103,7 @@ public class Scoreboard { if (!player.isOnline()) cancel(); try { - String formattedDisplayName = ChatColor.translateAlternateColorCodes('&', - replaceDisplayName(displayName)); + String formattedDisplayName = ChatColor.translateAlternateColorCodes('&', replaceDisplayName(displayName)); if (formattedDisplayName.length() > max) { obj.setDisplayName(ChatColor.RED + "Too long..."); @@ -119,50 +121,37 @@ public class Scoreboard { } if (displayLine.length() >= 16) { - String prefixLine = displayLine.substring(0, - Math.min(displayLine.length(), 16)); - String suffixLine = displayLine.substring(16, - Math.min(displayLine.length(), displayLine.length())); + String prefixLine = displayLine.substring(0, Math.min(displayLine.length(), 16)); + String suffixLine = displayLine.substring(16, Math.min(displayLine.length(), displayLine.length())); if (prefixLine.substring(prefixLine.length() - 1).equals("&")) { - prefixLine = ChatColor.translateAlternateColorCodes('&', - prefixLine.substring(0, prefixLine.length() - 1)); - suffixLine = ChatColor.translateAlternateColorCodes('&', - "&" + suffixLine); + prefixLine = ChatColor.translateAlternateColorCodes('&', prefixLine.substring(0, prefixLine.length() - 1)); + suffixLine = ChatColor.translateAlternateColorCodes('&', "&" + suffixLine); } else { String lastColorCodes; if (prefixLine.contains("&")) { String[] colorCodes = prefixLine.split("&"); String lastColorCodeText = colorCodes[colorCodes.length - 1]; - lastColorCodes = "&" + lastColorCodeText.substring(0, - Math.min(lastColorCodeText.length(), 1)); + lastColorCodes = "&" + lastColorCodeText.substring(0, Math.min(lastColorCodeText.length(), 1)); - if ((colorCodes.length >= 2) && (lastColorCodes.equals("&l") - || lastColorCodes.equals("&m") - || lastColorCodes.equals("&n") - || lastColorCodes.equals("&o"))) { + if ((colorCodes.length >= 2) + && (lastColorCodes.equals("&l") || lastColorCodes.equals("&m") || lastColorCodes.equals("&n") || lastColorCodes.equals("&o"))) { lastColorCodeText = colorCodes[colorCodes.length - 2]; - lastColorCodes = "&" - + lastColorCodeText.substring(0, - Math.min(lastColorCodeText.length(), 1)) - + lastColorCodes; + lastColorCodes = "&" + lastColorCodeText.substring(0, Math.min(lastColorCodeText.length(), 1)) + lastColorCodes; } } else { lastColorCodes = "&f"; } - prefixLine = ChatColor.translateAlternateColorCodes('&', - prefixLine); - suffixLine = ChatColor.translateAlternateColorCodes('&', - lastColorCodes + suffixLine); + prefixLine = ChatColor.translateAlternateColorCodes('&', prefixLine); + suffixLine = ChatColor.translateAlternateColorCodes('&', lastColorCodes + suffixLine); } scoreboard.getTeam(ranStr + i1).setPrefix(prefixLine); scoreboard.getTeam(ranStr + i1).setSuffix(suffixLine); } else { - scoreboard.getTeam(ranStr + i1).setPrefix( - ChatColor.translateAlternateColorCodes('&', displayLine)); + scoreboard.getTeam(ranStr + i1).setPrefix(ChatColor.translateAlternateColorCodes('&', displayLine)); } } @@ -181,8 +170,7 @@ public class Scoreboard { } private String replaceDisplayName(String displayName) { - displayName = displayName.replace("%players_online", "" + Bukkit.getServer().getOnlinePlayers().size()) - .replace("%players_max", "" + Bukkit.getServer().getMaxPlayers()); + displayName = displayName.replace("%players_online", "" + Bukkit.getServer().getOnlinePlayers().size()).replace("%players_max", "" + Bukkit.getServer().getMaxPlayers()); return displayName; } @@ -192,8 +180,7 @@ public class Scoreboard { IslandManager islandManager = skyblock.getIslandManager(); - displayLine = displayLine.replace("%players_online", "" + Bukkit.getServer().getOnlinePlayers().size()) - .replace("%players_max", "" + Bukkit.getServer().getMaxPlayers()); + displayLine = displayLine.replace("%players_online", "" + Bukkit.getServer().getOnlinePlayers().size()).replace("%players_max", "" + Bukkit.getServer().getMaxPlayers()); Island island = islandManager.getIsland(player); @@ -201,15 +188,11 @@ public class Scoreboard { IslandLevel level = island.getLevel(); if (island.getRole(IslandRole.Member).size() == 0 && island.getRole(IslandRole.Operator).size() == 0) { - displayLine = displayLine - .replace("%island_level", "" + NumberUtil.formatNumberByDecimal(level.getLevel())) - .replace("%island_members", ChatColor.RED + "0").replace("%island_role", ChatColor.RED + "null") - .replace("%island_visitors", "" + islandManager.getVisitorsAtIsland(island).size()) - .replace("%island_size", "" + island.getSize()) - .replace("%island_radius", "" + island.getRadius()); + displayLine = displayLine.replace("%island_level", "" + NumberUtil.formatNumberByDecimal(level.getLevel())).replace("%island_members", ChatColor.RED + "0") + .replace("%island_role", ChatColor.RED + "null").replace("%island_visitors", "" + islandManager.getVisitorsAtIsland(island).size()) + .replace("%island_size", "" + island.getSize()).replace("%island_radius", "" + island.getRadius()); } else { - int islandMembers = 1 + island.getRole(IslandRole.Member).size() - + island.getRole(IslandRole.Operator).size(); + int islandMembers = 1 + island.getRole(IslandRole.Member).size() + island.getRole(IslandRole.Operator).size(); String islandRole = ""; if (island.hasRole(IslandRole.Owner, player.getUniqueId())) { @@ -220,26 +203,20 @@ public class Scoreboard { islandRole = displayVariables.get("%member"); } - displayLine = displayLine - .replace("%island_points", "" + NumberUtil.formatNumberByDecimal(level.getPoints())) - .replace("%island_level", "" + NumberUtil.formatNumberByDecimal(level.getLevel())) - .replace("%island_members", "" + islandMembers).replace("%island_role", islandRole) - .replace("%island_visitors", "" + islandManager.getVisitorsAtIsland(island).size()) - .replace("%island_size", "" + island.getSize()) + displayLine = displayLine.replace("%island_points", "" + NumberUtil.formatNumberByDecimal(level.getPoints())) + .replace("%island_level", "" + NumberUtil.formatNumberByDecimal(level.getLevel())).replace("%island_members", "" + islandMembers).replace("%island_role", islandRole) + .replace("%island_visitors", "" + islandManager.getVisitorsAtIsland(island).size()).replace("%island_size", "" + island.getSize()) .replace("%island_radius", "" + island.getRadius()); } } else { - displayLine = displayLine.replace("%island_points", ChatColor.RED + "0") - .replace("%island_level", ChatColor.RED + "0").replace("%island_members", ChatColor.RED + "0") - .replace("%island_role", ChatColor.RED + "null").replace("%island_size", ChatColor.RED + "0") - .replace("%island_radius", ChatColor.RED + "0"); + displayLine = displayLine.replace("%island_points", ChatColor.RED + "0").replace("%island_level", ChatColor.RED + "0").replace("%island_members", ChatColor.RED + "0") + .replace("%island_role", ChatColor.RED + "null").replace("%island_size", ChatColor.RED + "0").replace("%island_radius", ChatColor.RED + "0"); } PlaceholderManager placeholderManager = skyblock.getPlaceholderManager(); if (placeholderManager.isPlaceholderAPIEnabled()) { - displayLine = me.clip.placeholderapi.PlaceholderAPI.setPlaceholders(player, displayLine.replace("&", "clr")) - .replace("clr", "&"); + displayLine = me.clip.placeholderapi.PlaceholderAPI.setPlaceholders(player, displayLine.replace("&", "clr")).replace("clr", "&"); } return displayLine; diff --git a/src/main/java/com/songoda/skyblock/scoreboard/ScoreboardManager.java b/src/main/java/com/songoda/skyblock/scoreboard/ScoreboardManager.java index dae09cf9..63db0ff3 100644 --- a/src/main/java/com/songoda/skyblock/scoreboard/ScoreboardManager.java +++ b/src/main/java/com/songoda/skyblock/scoreboard/ScoreboardManager.java @@ -1,99 +1,204 @@ package com.songoda.skyblock.scoreboard; +import java.io.File; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.entity.Player; +import org.bukkit.scheduler.BukkitRunnable; +import org.bukkit.scoreboard.Objective; +import org.bukkit.scoreboard.Team; +import org.bukkit.scoreboard.Team.Option; + import com.songoda.skyblock.SkyBlock; import com.songoda.skyblock.config.FileManager; import com.songoda.skyblock.config.FileManager.Config; import com.songoda.skyblock.island.Island; import com.songoda.skyblock.island.IslandManager; import com.songoda.skyblock.island.IslandRole; -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.entity.Player; -import org.bukkit.scheduler.BukkitRunnable; +import com.songoda.skyblock.utils.version.NMSUtil; -import java.io.File; -import java.util.HashMap; -import java.util.Map; -import java.util.UUID; - -public class ScoreboardManager { +public class ScoreboardManager extends BukkitRunnable { + private final static int VERSION = NMSUtil.getVersionNumber(); private final SkyBlock skyblock; - private Map scoreboardStorage = new HashMap<>(); + private final Map scoreboardStorage; + + private int runTicks = 0; + + private List teamNames; + private List objectiveNames; public ScoreboardManager(SkyBlock skyblock) { this.skyblock = skyblock; + this.scoreboardStorage = new HashMap<>(); + this.teamNames = new ArrayList<>(); + this.objectiveNames = new ArrayList<>(); + this.runTaskTimer(skyblock, 20, 40); + } - new BukkitRunnable() { - @Override - public void run() { - IslandManager islandManager = skyblock.getIslandManager(); - FileManager fileManager = skyblock.getFileManager(); + @SuppressWarnings("deprecation") + @Override + public void run() { - if (fileManager.getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration() - .getBoolean("Island.Scoreboard.Enable")) { - Config config = fileManager.getConfig(new File(skyblock.getDataFolder(), "language.yml")); + if (runTicks++ == 0) { + IslandManager islandManager = skyblock.getIslandManager(); + FileManager fileManager = skyblock.getFileManager(); - for (Player all : Bukkit.getOnlinePlayers()) { - Scoreboard scoreboard = new Scoreboard(skyblock, all); - Island island = islandManager.getIsland(all); + if (fileManager.getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration().getBoolean("Island.Scoreboard.Enable")) { + Config config = fileManager.getConfig(new File(skyblock.getDataFolder(), "language.yml")); - if (island == null) { - scoreboard.setDisplayName(ChatColor.translateAlternateColorCodes('&', - config.getFileConfiguration().getString("Scoreboard.Tutorial.Displayname"))); - scoreboard.setDisplayList( - config.getFileConfiguration().getStringList("Scoreboard.Tutorial.Displaylines")); - } else { - if (island.getRole(IslandRole.Member).size() == 0 - && island.getRole(IslandRole.Operator).size() == 0) { - scoreboard.setDisplayName(ChatColor.translateAlternateColorCodes('&', - config.getFileConfiguration().getString("Scoreboard.Island.Solo.Displayname"))); + for (Player all : Bukkit.getOnlinePlayers()) { + Scoreboard scoreboard = new Scoreboard(skyblock, all); + Island island = islandManager.getIsland(all); - if (islandManager.getVisitorsAtIsland(island).size() == 0) { - scoreboard.setDisplayList(config.getFileConfiguration() - .getStringList("Scoreboard.Island.Solo.Empty.Displaylines")); - } else { - scoreboard.setDisplayList(config.getFileConfiguration() - .getStringList("Scoreboard.Island.Solo.Occupied.Displaylines")); - } + if (island == null) { + scoreboard.setDisplayName(ChatColor.translateAlternateColorCodes('&', config.getFileConfiguration().getString("Scoreboard.Tutorial.Displayname"))); + scoreboard.setDisplayList(config.getFileConfiguration().getStringList("Scoreboard.Tutorial.Displaylines")); + } else { + if (island.getRole(IslandRole.Member).size() == 0 && island.getRole(IslandRole.Operator).size() == 0) { + scoreboard.setDisplayName(ChatColor.translateAlternateColorCodes('&', config.getFileConfiguration().getString("Scoreboard.Island.Solo.Displayname"))); + + if (islandManager.getVisitorsAtIsland(island).size() == 0) { + scoreboard.setDisplayList(config.getFileConfiguration().getStringList("Scoreboard.Island.Solo.Empty.Displaylines")); } else { - scoreboard.setDisplayName(ChatColor.translateAlternateColorCodes('&', - config.getFileConfiguration().getString("Scoreboard.Island.Team.Displayname"))); - - if (islandManager.getVisitorsAtIsland(island).size() == 0) { - scoreboard.setDisplayList(config.getFileConfiguration() - .getStringList("Scoreboard.Island.Team.Empty.Displaylines")); - } else { - scoreboard.setDisplayList(config.getFileConfiguration() - .getStringList("Scoreboard.Island.Team.Occupied.Displaylines")); - } - - Map displayVariables = new HashMap<>(); - displayVariables.put("%owner", - config.getFileConfiguration().getString("Scoreboard.Island.Team.Word.Owner")); - displayVariables.put("%operator", config.getFileConfiguration() - .getString("Scoreboard.Island.Team.Word.Operator")); - displayVariables.put("%member", - config.getFileConfiguration().getString("Scoreboard.Island.Team.Word.Member")); - - scoreboard.setDisplayVariables(displayVariables); + scoreboard.setDisplayList(config.getFileConfiguration().getStringList("Scoreboard.Island.Solo.Occupied.Displaylines")); } - } + } else { + scoreboard.setDisplayName(ChatColor.translateAlternateColorCodes('&', config.getFileConfiguration().getString("Scoreboard.Island.Team.Displayname"))); - scoreboard.run(); - storeScoreboard(all, scoreboard); + if (islandManager.getVisitorsAtIsland(island).size() == 0) { + scoreboard.setDisplayList(config.getFileConfiguration().getStringList("Scoreboard.Island.Team.Empty.Displaylines")); + } else { + scoreboard.setDisplayList(config.getFileConfiguration().getStringList("Scoreboard.Island.Team.Occupied.Displaylines")); + } + + Map displayVariables = new HashMap<>(); + displayVariables.put("%owner", config.getFileConfiguration().getString("Scoreboard.Island.Team.Word.Owner")); + displayVariables.put("%operator", config.getFileConfiguration().getString("Scoreboard.Island.Team.Word.Operator")); + displayVariables.put("%member", config.getFileConfiguration().getString("Scoreboard.Island.Team.Word.Member")); + + scoreboard.setDisplayVariables(displayVariables); + } } + + scoreboard.run(); + storeScoreboard(all, scoreboard); } } - }.runTaskLater(skyblock, 20L); + return; + } + + final org.bukkit.scoreboard.Scoreboard primary = Bukkit.getScoreboardManager().getMainScoreboard(); + final Collection players = Bukkit.getOnlinePlayers(); + final Set objectives = primary.getObjectives(); + final Set teams = primary.getTeams(); + + for (Player player : players) { + + /* + * Unregister all teams or objectives that are no longer present in the main + * scoreboard. + */ + + final org.bukkit.scoreboard.Scoreboard board = player.getScoreboard(); + + for (String name : objectiveNames) { + + if (primary.getObjective(name) != null) continue; + + final Objective objective = board.getObjective(name); + + if (objective != null) objective.unregister(); + + } + + for (String name : teamNames) { + + if (primary.getTeam(name) != null) continue; + + final Team team = board.getTeam(name); + + if (team != null) team.unregister(); + } + + } + + /* + * Update the objective/team names. + */ + + objectiveNames.clear(); + teamNames.clear(); + + objectives.forEach(objective -> { + if (primary.getObjective(objective.getName()) != null) objectiveNames.add(objective.getName()); + }); + teams.forEach(team -> { + if (primary.getTeam(team.getName()) != null) teamNames.add(team.getName()); + }); + + /* + * Update or add any missing information to the player's scoreboard. + */ + + for (Player player : players) { + + final org.bukkit.scoreboard.Scoreboard playerBoard = player.getScoreboard(); + + for (Objective primaryObjective : objectives) { + + Objective obj = playerBoard.getObjective(primaryObjective.getName()); + + if (obj == null) obj = playerBoard.registerNewObjective(primaryObjective.getName(), primaryObjective.getCriteria()); + + obj.setDisplayName(primaryObjective.getDisplayName()); + obj.setDisplaySlot(primaryObjective.getDisplaySlot()); + obj.setRenderType(primaryObjective.getRenderType()); + } + + for (Team primaryTeam : teams) { + + Team obj = playerBoard.getTeam(primaryTeam.getName()); + + if (obj == null) obj = playerBoard.registerNewTeam(primaryTeam.getName()); + + obj.setAllowFriendlyFire(primaryTeam.allowFriendlyFire()); + obj.setCanSeeFriendlyInvisibles(primaryTeam.canSeeFriendlyInvisibles()); + if (VERSION > 11) obj.setColor(primaryTeam.getColor()); + obj.setDisplayName(primaryTeam.getDisplayName()); + obj.setNameTagVisibility(primaryTeam.getNameTagVisibility()); + obj.setPrefix(primaryTeam.getPrefix()); + obj.setSuffix(primaryTeam.getSuffix()); + + for (String primaryEntry : primaryTeam.getEntries()) { + obj.addEntry(primaryEntry); + } + + if (VERSION > 8) { + for (Option option : Option.values()) { + obj.setOption(option, primaryTeam.getOption(option)); + } + } + + } + + } + } public void resendScoreboard() { IslandManager islandManager = skyblock.getIslandManager(); FileManager fileManager = skyblock.getFileManager(); - if (!fileManager.getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration() - .getBoolean("Island.Scoreboard.Enable")) return; + if (!fileManager.getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration().getBoolean("Island.Scoreboard.Enable")) return; Config config = fileManager.getConfig(new File(skyblock.getDataFolder(), "language.yml")); for (Player all : Bukkit.getOnlinePlayers()) { @@ -104,42 +209,30 @@ public class ScoreboardManager { Island island = islandManager.getIsland(all); if (island == null) { - scoreboard.setDisplayName(ChatColor.translateAlternateColorCodes('&', - config.getFileConfiguration().getString("Scoreboard.Tutorial.Displayname"))); - scoreboard.setDisplayList( - config.getFileConfiguration().getStringList("Scoreboard.Tutorial.Displaylines")); + scoreboard.setDisplayName(ChatColor.translateAlternateColorCodes('&', config.getFileConfiguration().getString("Scoreboard.Tutorial.Displayname"))); + scoreboard.setDisplayList(config.getFileConfiguration().getStringList("Scoreboard.Tutorial.Displaylines")); } else { - if (island.getRole(IslandRole.Member).size() == 0 - && island.getRole(IslandRole.Operator).size() == 0) { - scoreboard.setDisplayName(ChatColor.translateAlternateColorCodes('&', - config.getFileConfiguration().getString("Scoreboard.Island.Solo.Displayname"))); + if (island.getRole(IslandRole.Member).size() == 0 && island.getRole(IslandRole.Operator).size() == 0) { + scoreboard.setDisplayName(ChatColor.translateAlternateColorCodes('&', config.getFileConfiguration().getString("Scoreboard.Island.Solo.Displayname"))); if (islandManager.getVisitorsAtIsland(island).size() == 0) { - scoreboard.setDisplayList(config.getFileConfiguration() - .getStringList("Scoreboard.Island.Solo.Empty.Displaylines")); + scoreboard.setDisplayList(config.getFileConfiguration().getStringList("Scoreboard.Island.Solo.Empty.Displaylines")); } else { - scoreboard.setDisplayList(config.getFileConfiguration() - .getStringList("Scoreboard.Island.Solo.Occupied.Displaylines")); + scoreboard.setDisplayList(config.getFileConfiguration().getStringList("Scoreboard.Island.Solo.Occupied.Displaylines")); } } else { - scoreboard.setDisplayName(ChatColor.translateAlternateColorCodes('&', - config.getFileConfiguration().getString("Scoreboard.Island.Team.Displayname"))); + scoreboard.setDisplayName(ChatColor.translateAlternateColorCodes('&', config.getFileConfiguration().getString("Scoreboard.Island.Team.Displayname"))); if (islandManager.getVisitorsAtIsland(island).size() == 0) { - scoreboard.setDisplayList(config.getFileConfiguration() - .getStringList("Scoreboard.Island.Team.Empty.Displaylines")); + scoreboard.setDisplayList(config.getFileConfiguration().getStringList("Scoreboard.Island.Team.Empty.Displaylines")); } else { - scoreboard.setDisplayList(config.getFileConfiguration() - .getStringList("Scoreboard.Island.Team.Occupied.Displaylines")); + scoreboard.setDisplayList(config.getFileConfiguration().getStringList("Scoreboard.Island.Team.Occupied.Displaylines")); } Map displayVariables = new HashMap<>(); - displayVariables.put("%owner", - config.getFileConfiguration().getString("Scoreboard.Island.Team.Word.Owner")); - displayVariables.put("%operator", - config.getFileConfiguration().getString("Scoreboard.Island.Team.Word.Operator")); - displayVariables.put("%member", - config.getFileConfiguration().getString("Scoreboard.Island.Team.Word.Member")); + displayVariables.put("%owner", config.getFileConfiguration().getString("Scoreboard.Island.Team.Word.Owner")); + displayVariables.put("%operator", config.getFileConfiguration().getString("Scoreboard.Island.Team.Word.Operator")); + displayVariables.put("%member", config.getFileConfiguration().getString("Scoreboard.Island.Team.Word.Member")); scoreboard.setDisplayVariables(displayVariables); } diff --git a/src/main/java/com/songoda/skyblock/stackable/Stackable.java b/src/main/java/com/songoda/skyblock/stackable/Stackable.java index 8c9543fe..abd3db11 100644 --- a/src/main/java/com/songoda/skyblock/stackable/Stackable.java +++ b/src/main/java/com/songoda/skyblock/stackable/Stackable.java @@ -15,6 +15,7 @@ import org.bukkit.entity.ArmorStand; import org.bukkit.entity.Entity; import org.bukkit.entity.EntityType; import org.bukkit.inventory.ItemStack; +import org.bukkit.metadata.FixedMetadataValue; import java.io.File; import java.util.UUID; @@ -91,14 +92,19 @@ public class Stackable { } private void updateDisplay() { - // The chunk needs to be loaded otherwise the getNearbyEntities() in removeDisplay() won't find anything - if (!this.location.getWorld().isChunkLoaded(this.location.getBlockX() >> 4, this.location.getBlockZ() >> 4)) - this.location.getChunk().load(); + // The chunk needs to be loaded otherwise the getNearbyEntities() in + // removeDisplay() won't find anything + if (!this.location.getWorld().isChunkLoaded(this.location.getBlockX() >> 4, this.location.getBlockZ() >> 4)) this.location.getChunk().load(); if (this.size > 1) { - this.createDisplay(); - this.display.setCustomName(this.getCustomName()); - this.display.setCustomNameVisible(true); + + if (display == null || !display.isValid()) { + this.createDisplay(); + } else { + this.display.setCustomName(this.getCustomName()); + this.display.setCustomNameVisible(true); + } + } else { this.removeDisplay(); } @@ -119,6 +125,7 @@ public class Stackable { as.setHelmet(new ItemStack(this.material)); as.setCustomName(this.getCustomName()); as.setCustomNameVisible(true); + as.setMetadata("StackableArmorStand", new FixedMetadataValue(SkyBlock.getInstance(), "")); this.display = as; } @@ -129,14 +136,13 @@ public class Stackable { // Find any stragglers for (Entity entity : this.location.getWorld().getNearbyEntities(this.location.clone().add(0.5, 0.55, 0.5), 0.25, 0.5, 0.25)) - if (entity instanceof ArmorStand) - entity.remove(); + if (entity instanceof ArmorStand) entity.remove(); } private void save() { File configFile = new File(SkyBlock.getInstance().getDataFolder().toString() + "/island-data"); - FileManager.Config config = SkyBlock.getInstance().getFileManager().getConfig(new File(configFile, - SkyBlock.getInstance().getIslandManager().getIslandAtLocation(this.location).getOwnerUUID() + ".yml")); + FileManager.Config config = SkyBlock.getInstance().getFileManager() + .getConfig(new File(configFile, SkyBlock.getInstance().getIslandManager().getIslandAtLocation(this.location).getOwnerUUID() + ".yml")); FileConfiguration configLoad = config.getFileConfiguration(); if (this.getSize() == 0) { @@ -150,10 +156,10 @@ public class Stackable { } private String getCustomName() { - return ChatColor.translateAlternateColorCodes('&', SkyBlock.getInstance().getFileManager() - .getConfig(new File(SkyBlock.getInstance().getDataFolder(), "language.yml")) - .getFileConfiguration().getString("Hologram.Stackable.Message")) - .replace("%block", WordUtils.capitalize(this.material.name().toLowerCase()).replace("_", " ")) - .replace("%amount", NumberUtil.formatNumber(this.size)); + return ChatColor + .translateAlternateColorCodes('&', + SkyBlock.getInstance().getFileManager().getConfig(new File(SkyBlock.getInstance().getDataFolder(), "language.yml")).getFileConfiguration() + .getString("Hologram.Stackable.Message")) + .replace("%block", WordUtils.capitalize(this.material.name().toLowerCase()).replace("_", " ")).replace("%amount", NumberUtil.formatNumber(this.size)); } } diff --git a/src/main/java/com/songoda/skyblock/stackable/StackableManager.java b/src/main/java/com/songoda/skyblock/stackable/StackableManager.java index d2e0e270..a3ba3544 100644 --- a/src/main/java/com/songoda/skyblock/stackable/StackableManager.java +++ b/src/main/java/com/songoda/skyblock/stackable/StackableManager.java @@ -1,15 +1,21 @@ package com.songoda.skyblock.stackable; -import com.songoda.skyblock.SkyBlock; -import com.songoda.skyblock.config.FileManager; +import java.io.File; +import java.util.Collections; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + import org.bukkit.Location; import org.bukkit.Material; -import org.bukkit.block.Block; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.file.FileConfiguration; -import java.io.File; -import java.util.*; +import com.songoda.skyblock.SkyBlock; +import com.songoda.skyblock.config.FileManager; public class StackableManager { diff --git a/src/main/java/com/songoda/skyblock/usercache/UserCacheManager.java b/src/main/java/com/songoda/skyblock/usercache/UserCacheManager.java index f0fca750..aebcb486 100644 --- a/src/main/java/com/songoda/skyblock/usercache/UserCacheManager.java +++ b/src/main/java/com/songoda/skyblock/usercache/UserCacheManager.java @@ -1,12 +1,5 @@ package com.songoda.skyblock.usercache; -import com.songoda.skyblock.SkyBlock; -import com.songoda.skyblock.config.FileManager; -import com.songoda.skyblock.config.FileManager.Config; -import com.songoda.skyblock.utils.player.NameFetcher; -import org.bukkit.Bukkit; -import org.bukkit.configuration.file.FileConfiguration; - import java.io.File; import java.io.IOException; import java.util.HashSet; @@ -14,7 +7,15 @@ import java.util.Set; import java.util.UUID; import java.util.logging.Level; -public class UserCacheManager { +import org.bukkit.Bukkit; +import org.bukkit.configuration.file.FileConfiguration; + +import com.songoda.skyblock.SkyBlock; +import com.songoda.skyblock.config.FileManager; +import com.songoda.skyblock.config.FileManager.Config; +import com.songoda.skyblock.utils.player.NameFetcher; + +public final class UserCacheManager { private final SkyBlock skyblock; private final Config config; @@ -23,74 +24,62 @@ public class UserCacheManager { this.skyblock = skyblock; this.config = skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "usercache.yml")); - FileManager fileManager = skyblock.getFileManager(); - File configFile = new File(skyblock.getDataFolder().toString() + "/island-data"); + final FileManager fileManager = skyblock.getFileManager(); + final File configFile = new File(skyblock.getDataFolder().toString() + "/island-data"); Bukkit.getServer().getScheduler().runTaskAsynchronously(skyblock, () -> { if (configFile.exists()) { int usersIgnored = 0; - Bukkit.getServer().getLogger().log(Level.INFO, - "SkyBlock | Info: Fetching user information from island data. This may take a while..."); + Bukkit.getServer().getLogger().log(Level.INFO, "SkyBlock | Info: Fetching user information from island data. This may take a while..."); for (File fileList : configFile.listFiles()) { - if (fileList != null && fileList.getName().contains(".yml") - && fileList.getName().length() > 35) { - UUID islandOwnerUUID = null; - try { - Config config = new Config(fileManager, fileList); - FileConfiguration configLoad = config.getFileConfiguration(); + if (fileList == null) continue; - islandOwnerUUID = UUID.fromString(fileList.getName().replace(".yml", "")); + final String fileName = fileList.getName(); - if (islandOwnerUUID == null) { - islandOwnerUUID = UUID.fromString(fileList.getName().replaceFirst("[.][^.]+$", "")); + if (fileName.length() < 35 || !fileName.endsWith(".yml")) continue; - if (islandOwnerUUID == null) { - continue; - } - } + try { + final FileConfiguration configLoad = new Config(fileManager, fileList).getFileConfiguration(); + final String ownerUUIDString = fileName.substring(0, fileName.indexOf('.')); - Set islandMembers = new HashSet<>(); - islandMembers.add(islandOwnerUUID); + System.out.println(ownerUUIDString); - if (configLoad.getString("Members") != null) { - for (String memberList : configLoad.getStringList("Members")) { - islandMembers.add(UUID.fromString(memberList)); - } - } + Set islandMembers = new HashSet<>(); + islandMembers.add(UUID.fromString(ownerUUIDString)); - if (configLoad.getString("Operators") != null) { - for (String operatorList : configLoad.getStringList("Operators")) { - islandMembers.add(UUID.fromString(operatorList)); - } - } - - for (UUID islandMemberList : islandMembers) { - if (!hasUser(islandMemberList)) { - NameFetcher.Names[] names = NameFetcher.getNames(islandMemberList); - - if (names.length >= 1) { - addUser(islandMemberList, names[0].getName()); - } - } - } - } catch (Exception e) { - usersIgnored++; + for (String memberList : configLoad.getStringList("Members")) { + islandMembers.add(UUID.fromString(memberList)); } + + for (String operatorList : configLoad.getStringList("Operators")) { + islandMembers.add(UUID.fromString(operatorList)); + } + + for (UUID islandMemberList : islandMembers) { + if (!hasUser(islandMemberList)) { + NameFetcher.Names[] names = NameFetcher.getNames(islandMemberList); + + if (names.length >= 1) { + addUser(islandMemberList, names[0].getName()); + } + } + } + } catch (Exception e) { + usersIgnored++; } + } save(); if (usersIgnored != 0) { Bukkit.getServer().getLogger().log(Level.INFO, - "SkyBlock | Info: Finished fetching user information from island data. There were " - + usersIgnored + " users that were skipped."); + "SkyBlock | Info: Finished fetching user information from island data. There were " + usersIgnored + " users that were skipped."); } else { - Bukkit.getServer().getLogger().log(Level.INFO, - "SkyBlock | Info: Finished fetching user information from island data."); + Bukkit.getServer().getLogger().log(Level.INFO, "SkyBlock | Info: Finished fetching user information from island data. No users were ignored."); } } }); diff --git a/src/main/java/com/songoda/skyblock/utils/item/MenuClickRegistry.java b/src/main/java/com/songoda/skyblock/utils/item/MenuClickRegistry.java new file mode 100644 index 00000000..05c821b2 --- /dev/null +++ b/src/main/java/com/songoda/skyblock/utils/item/MenuClickRegistry.java @@ -0,0 +1,115 @@ +package com.songoda.skyblock.utils.item; + +import java.io.File; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; +import org.bukkit.inventory.meta.ItemMeta; + +import com.songoda.skyblock.SkyBlock; +import com.songoda.skyblock.utils.StringUtil; +import com.songoda.skyblock.utils.item.nInventoryUtil.ClickEvent; +import com.songoda.skyblock.utils.version.Materials; + +public final class MenuClickRegistry { + + private static MenuClickRegistry instance; + + public static MenuClickRegistry getInstance() { + return instance == null ? instance = new MenuClickRegistry() : instance; + } + + private Set populators; + private Map executors; + + private MenuClickRegistry() { + this.executors = new HashMap<>(); + this.populators = new HashSet<>(); + } + + public void register(MenuPopulator populator) { + populator.populate(executors); + populators.add(populator); + } + + public void reloadAll() { + executors.clear(); + for (MenuPopulator populator : populators) { + populator.populate(executors); + } + } + + public void dispatch(Player clicker, ClickEvent e) { + + final ItemStack item = e.getItem(); + + if (item == null) return; + + final ItemMeta meta = item.getItemMeta(); + + if (meta == null) return; + + @SuppressWarnings("deprecation") + final MenuExecutor executor = executors.get(RegistryKey.fromName(meta.getDisplayName(), Materials.getMaterials(item.getType(), (byte) item.getDurability()))); + + System.out.println(executors.size()); + + if (executor == null) return; + + executor.onClick(SkyBlock.getInstance(), clicker, e); + } + + public static interface MenuPopulator { + + void populate(Map executors); + + } + + public static interface MenuExecutor { + + void onClick(SkyBlock skyblock, Player clicker, ClickEvent e); + + } + + public static class RegistryKey { + + private static final File path = new File(SkyBlock.getInstance().getDataFolder(), "language.yml"); + + private final String name; + private final Materials type; + + private RegistryKey(String name, Materials type) { + this.name = name; + this.type = type; + } + + @Override + public int hashCode() { + return Objects.hash(name, type); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (!(obj instanceof RegistryKey)) return false; + + final RegistryKey other = (RegistryKey) obj; + + return Objects.equals(name, other.name) && type == other.type; + } + + public static RegistryKey fromName(String name, Materials type) { + return new RegistryKey(name, type); + } + + public static RegistryKey fromLanguageFile(String namePath, Materials type) { + return new RegistryKey(StringUtil.color(SkyBlock.getInstance().getFileManager().getConfig(path).getFileConfiguration().getString(namePath)), type); + } + } + +} diff --git a/src/main/java/com/songoda/skyblock/utils/item/nInventoryUtil.java b/src/main/java/com/songoda/skyblock/utils/item/nInventoryUtil.java index da052b5d..f5418db5 100644 --- a/src/main/java/com/songoda/skyblock/utils/item/nInventoryUtil.java +++ b/src/main/java/com/songoda/skyblock/utils/item/nInventoryUtil.java @@ -24,6 +24,7 @@ import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Map.Entry; public class nInventoryUtil { @@ -55,8 +56,7 @@ public class nInventoryUtil { return; } - ClickEvent clickEvent = new ClickEvent(event.getClick(), event.getSlot(), - event.getCurrentItem()); + ClickEvent clickEvent = new ClickEvent(event.getClick(), event.getSlot(), event.getCurrentItem()); handler.onClick(clickEvent); if (!clickEvent.getCancelled()) { @@ -115,8 +115,7 @@ public class nInventoryUtil { return items; } - public Item createItem(ItemStack is, String itemDisplayname, List itemLore, Placeholder[] placeholders, - Enchantment[] itemEnchantments, ItemFlag[] itemFlags) { + public Item createItem(ItemStack is, String itemDisplayname, List itemLore, Placeholder[] placeholders, Enchantment[] itemEnchantments, ItemFlag[] itemFlags) { return new Item(is, itemDisplayname, itemLore, placeholders, itemEnchantments, itemFlags); } @@ -136,7 +135,6 @@ public class nInventoryUtil { public void setRows(int rows) { if (rows > 6 || rows < 0) { size = 9; - return; } @@ -162,9 +160,8 @@ public class nInventoryUtil { } } - for (int i = 0; i < items.size(); i++) { - int slot = (int) items.keySet().toArray()[i]; - inv.setItem(slot, items.get(slot)); + for(Entry entry : items.entrySet()) { + inv.setItem(entry.getKey(), entry.getValue()); } } @@ -193,7 +190,7 @@ public class nInventoryUtil { void onClick(ClickEvent event); } - public class Item { + public static class Item { private ItemStack is; private String itemDisplayname; @@ -202,8 +199,7 @@ public class nInventoryUtil { private Enchantment[] itemEnchantments; private ItemFlag[] itemFlags; - public Item(ItemStack is, String itemDisplayname, List itemLore, Placeholder[] placeholders, - Enchantment[] itemEnchantments, ItemFlag[] itemFlags) { + public Item(ItemStack is, String itemDisplayname, List itemLore, Placeholder[] placeholders, Enchantment[] itemEnchantments, ItemFlag[] itemFlags) { this.is = is; this.itemDisplayname = ChatColor.translateAlternateColorCodes('&', itemDisplayname); this.itemLore = itemLore; @@ -214,14 +210,13 @@ public class nInventoryUtil { public void setLore() { if (itemLore != null) { - ArrayList formattedItemLore = new ArrayList<>(); + List formattedItemLore = new ArrayList<>(itemLore.size()); for (String itemLoreList : itemLore) { if (placeholders != null) { for (Placeholder placeholderList : placeholders) { if (itemLoreList.contains(placeholderList.getPlaceholder())) { - itemLoreList = ChatColor.translateAlternateColorCodes('&', itemLoreList - .replace(placeholderList.getPlaceholder(), placeholderList.getResult())); + itemLoreList = ChatColor.translateAlternateColorCodes('&', itemLoreList.replace(placeholderList.getPlaceholder(), placeholderList.getResult())); } } } diff --git a/src/main/java/com/songoda/skyblock/utils/player/NameFetcher.java b/src/main/java/com/songoda/skyblock/utils/player/NameFetcher.java index e99c736e..9d18a20e 100644 --- a/src/main/java/com/songoda/skyblock/utils/player/NameFetcher.java +++ b/src/main/java/com/songoda/skyblock/utils/player/NameFetcher.java @@ -1,15 +1,18 @@ package com.songoda.skyblock.utils.player; -import com.google.gson.Gson; - import java.io.IOException; -import java.net.MalformedURLException; import java.net.URL; import java.util.Date; import java.util.Scanner; import java.util.UUID; -public class NameFetcher { +import com.google.gson.Gson; + +public final class NameFetcher { + + private NameFetcher() { + + } public static Names[] getNames(UUID uuid) throws IOException { if (uuid == null) { @@ -18,17 +21,14 @@ public class NameFetcher { Names[] names = null; - Scanner jsonScanner = new Scanner( - (new URL("https://api.mojang.com/user/profiles/" + uuid.toString().replaceAll("-", "") + "/names")) - .openConnection().getInputStream(), - "UTF-8"); + Scanner jsonScanner = new Scanner((new URL("https://api.mojang.com/user/profiles/" + uuid.toString().replaceAll("-", "") + "/names")).openConnection().getInputStream(), "UTF-8"); names = new Gson().fromJson(jsonScanner.next(), Names[].class); jsonScanner.close(); return names; } - public class Names { + public static class Names { public String name; public long changedToAt; diff --git a/src/main/java/com/songoda/skyblock/utils/player/PlayerUtil.java b/src/main/java/com/songoda/skyblock/utils/player/PlayerUtil.java new file mode 100644 index 00000000..b52a8cc8 --- /dev/null +++ b/src/main/java/com/songoda/skyblock/utils/player/PlayerUtil.java @@ -0,0 +1,79 @@ +package com.songoda.skyblock.utils.player; + +import java.util.Set; + +import org.bukkit.entity.Player; +import org.bukkit.permissions.PermissionAttachmentInfo; + +public final class PlayerUtil { + + private PlayerUtil() { + + } + + /** + * This method will only parse positive numbers and will skip any non digit. + * + *

+ * An example: + *

+ * int number = getPositiveNumber("abc-123", 0, "abc-123".length()) + * will return 123 + * + * @throws IndexOutOfBoundsException if (input.length() < start || + * input.length() > end) evaluates to true. + * @return a positive number for the given input String at the start and end + * index. + */ + public static int getPositiveNumber(String input, int start, int end) { + + if (input.length() < start || input.length() > end) throw new IndexOutOfBoundsException(""); + + int num = 0; + + for (int i = start; i < end; i++) { + + final char ch = input.charAt(i); + + if (!Character.isDigit(ch)) continue; + + final int digit = Character.getNumericValue(ch); + + num = num * 10 + digit; + } + + return num; + + } + + public static int getNumberFromPermission(Player player, String permission, boolean bypassPermission, int def) { + + final Set permissions = player.getEffectivePermissions(); + + if (bypassPermission && player.hasPermission(permission + ".bypass")) return Integer.MAX_VALUE; + + boolean set = false; + int highest = 0; + + for (PermissionAttachmentInfo info : permissions) { + + final String perm = info.getPermission(); + + if (!perm.startsWith(permission)) continue; + + final int index = perm.lastIndexOf('.'); + + if (index == -1 || index == perm.length()) continue; + + final int number = getPositiveNumber(perm, index, perm.length()); + + if (number >= highest) { + highest = number; + set = true; + } + } + + return set ? highest : def; + } + +} diff --git a/src/main/java/com/songoda/skyblock/utils/version/NMSUtil.java b/src/main/java/com/songoda/skyblock/utils/version/NMSUtil.java index 8d886c21..816fae2c 100644 --- a/src/main/java/com/songoda/skyblock/utils/version/NMSUtil.java +++ b/src/main/java/com/songoda/skyblock/utils/version/NMSUtil.java @@ -7,19 +7,32 @@ import java.lang.reflect.Field; public class NMSUtil { + private static final String version; + private static final int versionNumber; + private static final int versionReleaseNumber; + + static { + + String packageName = Bukkit.getServer().getClass().getPackage().getName(); + version = packageName.substring(packageName.lastIndexOf('.') + 1) + "."; + + String name = version.substring(3); + versionNumber = Integer.parseInt(name.substring(0, name.length() - 4)); + + versionReleaseNumber = Integer.parseInt(version.substring(version.length() - 2).replace(".", "")); + + } + public static String getVersion() { - String name = Bukkit.getServer().getClass().getPackage().getName(); - return name.substring(name.lastIndexOf('.') + 1) + "."; + return version; } public static int getVersionNumber() { - String name = getVersion().substring(3); - return Integer.valueOf(name.substring(0, name.length() - 4)); + return versionNumber; } public static int getVersionReleaseNumber() { - String NMSVersion = getVersion(); - return Integer.valueOf(NMSVersion.substring(NMSVersion.length() - 2).replace(".", "")); + return versionReleaseNumber; } public static Class getNMSClass(String className) { diff --git a/src/main/java/com/songoda/skyblock/utils/version/Sounds.java b/src/main/java/com/songoda/skyblock/utils/version/Sounds.java index 541d0a3f..9aaee733 100644 --- a/src/main/java/com/songoda/skyblock/utils/version/Sounds.java +++ b/src/main/java/com/songoda/skyblock/utils/version/Sounds.java @@ -25,11 +25,13 @@ public enum Sounds { FIRE("FIRE", "BLOCK_FIRE_AMBIENT", "BLOCK_FIRE_AMBIENT"), FIRE_IGNITE("FIRE_IGNITE", "ITEM_FLINTANDSTEEL_USE", "ITEM_FLINTANDSTEEL_USE"), FIZZ("FIZZ", "BLOCK_FIRE_EXTINGUISH", "BLOCK_FIRE_EXTINGUISH"), - FUSE("FUSE", "ENTITY_TNT_PRIMED", "ENTITY_TNT_PRIMED"), GLASS("GLASS", "BLOCK_GLASS_BREAK", "BLOCK_GLASS_BREAK"), + FUSE("FUSE", "ENTITY_TNT_PRIMED", "ENTITY_TNT_PRIMED"), + GLASS("GLASS", "BLOCK_GLASS_BREAK", "BLOCK_GLASS_BREAK"), HURT_FLESH("HURT_FLESH", "ENTITY_PLAYER_HURT", "ENTITY_PLAYER_HURT"), ITEM_BREAK("ITEM_BREAK", "ENTITY_ITEM_BREAK", "ENTITY_ITEM_BREAK"), ITEM_PICKUP("ITEM_PICKUP", "ENTITY_ITEM_PICKUP", "ENTITY_ITEM_PICKUP"), - LAVA("LAVA", "BLOCK_LAVA_AMBIENT", "BLOCK_LAVA_AMBIENT"), LAVA_POP("LAVA_POP", "BLOCK_LAVA_POP", "BLOCK_LAVA_POP"), + LAVA("LAVA", "BLOCK_LAVA_AMBIENT", "BLOCK_LAVA_AMBIENT"), + LAVA_POP("LAVA_POP", "BLOCK_LAVA_POP", "BLOCK_LAVA_POP"), LEVEL_UP("LEVEL_UP", "ENTITY_PLAYER_LEVELUP", "ENTITY_PLAYER_LEVELUP"), MINECART_BASE("MINECART_BASE", "ENTITY_MINECART_RIDING", "ENTITY_MINECART_RIDING"), MINECART_INSIDE("MINECART_INSIDE", "ENTITY_MINECART_RIDING", "ENTITY_MINECART_RIDING"), @@ -163,8 +165,7 @@ public enum Sounds { FIREWORK_BLAST("FIREWORK_BLAST", "ENTITY_FIREWORK_BLAST", "ENTITY_FIREWORK_ROCKET_BLAST"), FIREWORK_BLAST2("FIREWORK_BLAST2", "ENTITY_FIREWORK_BLAST_FAR", "ENTITY_FIREWORK_ROCKET_BLAST_FAR"), FIREWORK_LARGE_BLAST("FIREWORK_LARGE_BLAST", "ENTITY_FIREWORK_LARGE_BLAST", "ENTITY_FIREWORK_ROCKET_LARGE_BLAST"), - FIREWORK_LARGE_BLAST2("FIREWORK_LARGE_BLAST2", "ENTITY_FIREWORK_LARGE_BLAST_FAR", - "ENTITY_FIREWORK_ROCKET_LARGE_BLAST_FAR"), + FIREWORK_LARGE_BLAST2("FIREWORK_LARGE_BLAST2", "ENTITY_FIREWORK_LARGE_BLAST_FAR", "ENTITY_FIREWORK_ROCKET_LARGE_BLAST_FAR"), FIREWORK_TWINKLE("FIREWORK_TWINKLE", "ENTITY_FIREWORK_TWINKLE", "ENTITY_FIREWORK_ROCKET_TWINKLE"), FIREWORK_TWINKLE2("FIREWORK_TWINKLE2", "ENTITY_FIREWORK_TWINKLE_FAR", "ENTITY_FIREWORK_ROCKET_TWINKLE_FAR"), FIREWORK_LAUNCH("FIREWORK_LAUNCH", "ENTITY_FIREWORK_LAUNCH", "ENTITY_FIREWORK_ROCKET_LAUNCH"), diff --git a/src/main/java/com/songoda/skyblock/utils/world/LocationUtil.java b/src/main/java/com/songoda/skyblock/utils/world/LocationUtil.java index ca2afb80..4cbdfe7f 100644 --- a/src/main/java/com/songoda/skyblock/utils/world/LocationUtil.java +++ b/src/main/java/com/songoda/skyblock/utils/world/LocationUtil.java @@ -26,8 +26,7 @@ import java.util.logging.Level; public final class LocationUtil { public static boolean isLocationLocation(Location location1, Location location2) { - return location1.getBlockX() == location2.getBlockX() && location1.getBlockY() == location2.getBlockY() - && location1.getBlockZ() == location2.getBlockZ(); + return location1.getBlockX() == location2.getBlockX() && location1.getBlockY() == location2.getBlockY() && location1.getBlockZ() == location2.getBlockZ(); } public static boolean isLocationAffectingIslandSpawn(Location location, Island island, IslandWorld world) { @@ -36,13 +35,14 @@ public final class LocationUtil { } private static boolean isLocationAffectingLocation(Location location1, Location location2) { - Location headHeight = location2.clone().add(0, 1, 0); - Location feetHeight = location2.clone(); - Location groundHeight = location2.clone().add(0, -1, 0); + location2 = location2.clone(); - return isLocationLocation(headHeight, location1) - || isLocationLocation(feetHeight, location1) - || isLocationLocation(groundHeight, location1); + /* + * First isLocationLocation() call is HeadHeight, second feetHeight, and the + * final one is GroundHeight. + */ + return isLocationLocation(location2.add(0, 1, 0), location1) || isLocationLocation(location2.subtract(0, 1, 0), location1) + || isLocationLocation(location2.subtract(0, 1, 0), location1); } public static boolean isLocationAtLocationRadius(Location location1, Location location2, double radius) { @@ -58,19 +58,20 @@ public final class LocationUtil { } public static List getLocations(Location minLocation, Location maxLocation) { - List locations = new ArrayList<>(); - int MinX = Math.min(maxLocation.getBlockX(), minLocation.getBlockX()); - int MinY = Math.min(maxLocation.getBlockY(), minLocation.getBlockY()); - int MinZ = Math.min(maxLocation.getBlockZ(), minLocation.getBlockZ()); + int minX = Math.min(maxLocation.getBlockX(), minLocation.getBlockX()); + int minY = Math.min(maxLocation.getBlockY(), minLocation.getBlockY()); + int minZ = Math.min(maxLocation.getBlockZ(), minLocation.getBlockZ()); - int MaxX = Math.max(maxLocation.getBlockX(), minLocation.getBlockX()); - int MaxY = Math.max(maxLocation.getBlockY(), minLocation.getBlockY()); - int MaxZ = Math.max(maxLocation.getBlockZ(), minLocation.getBlockZ()); + int maxX = Math.max(maxLocation.getBlockX(), minLocation.getBlockX()); + int maxY = Math.max(maxLocation.getBlockY(), minLocation.getBlockY()); + int maxZ = Math.max(maxLocation.getBlockZ(), minLocation.getBlockZ()); - for (int x = MinX; x <= MaxX; x++) { - for (int y = MinY; y <= MaxY; y++) { - for (int z = MinZ; z <= MaxZ; z++) { + List locations = new ArrayList<>(maxX + maxY + maxZ + 3); + + for (int x = minX; x <= maxX; x++) { + for (int y = minY; y <= maxY; y++) { + for (int z = minZ; z <= maxZ; z++) { locations.add(new Location(minLocation.getWorld(), x, y, z)); } } @@ -88,8 +89,8 @@ public final class LocationUtil { int MaxY = Math.max(maxLocation.getBlockY(), minLocation.getBlockY()); int MaxZ = Math.max(maxLocation.getBlockZ(), minLocation.getBlockZ()); - return MinX < targetLocation.getX() && MaxX > targetLocation.getX() && MinY < targetLocation.getY() - && MaxY > targetLocation.getY() && MinZ < targetLocation.getZ() && MaxZ > targetLocation.getZ(); + return MinX < targetLocation.getX() && MaxX > targetLocation.getX() && MinY < targetLocation.getY() && MaxY > targetLocation.getY() && MinZ < targetLocation.getZ() + && MaxZ > targetLocation.getZ(); } public static Location getHighestBlock(Location location) { @@ -110,28 +111,25 @@ public final class LocationUtil { int maxY = 0; boolean followY = false; + final int blockX = location.getBlockX(); + final int blockZ = location.getBlockZ(); + final World world = location.getWorld(); + for (int y = 0; y < location.getWorld().getMaxHeight(); y++) { - Location loc = new Location(location.getWorld(), location.getBlockX(), y, location.getBlockZ()); - Block block = loc.getBlock().getRelative(BlockFace.UP); + final Block block = world.getBlockAt(blockX, y, blockZ).getRelative(BlockFace.UP); if (isNether) { - if (y < 127 && (block.getType() == Material.LAVA - || block.getType() == Materials.LEGACY_STATIONARY_LAVA.getPostMaterial() - || block.getType() == Material.AIR)) { + if (y < 127 && (block.getType() == Material.LAVA || block.getType() == Materials.LEGACY_STATIONARY_LAVA.getPostMaterial() || block.getType() == Material.AIR)) { maxY = y; break; } } else { - if (block.getType() == Materials.OAK_LEAVES.parseMaterial() - || block.getType() == Materials.ACACIA_LEAVES.parseMaterial()) { + if (block.getType() == Materials.OAK_LEAVES.parseMaterial() || block.getType() == Materials.ACACIA_LEAVES.parseMaterial()) { break; } - if (block.getType() == Material.AIR - || block.getType() == Materials.LEGACY_STATIONARY_WATER.getPostMaterial() - || block.getType() == Material.WATER - || block.getType() == Materials.LEGACY_STATIONARY_LAVA.getPostMaterial() - || block.getType() == Material.LAVA) { + if (block.getType() == Material.AIR || block.getType() == Materials.LEGACY_STATIONARY_WATER.getPostMaterial() || block.getType() == Material.WATER + || block.getType() == Materials.LEGACY_STATIONARY_LAVA.getPostMaterial() || block.getType() == Material.LAVA) { if (!followY) { maxY = y; followY = true; @@ -191,8 +189,7 @@ public final class LocationUtil { Location spawnLocation = getSpawnLocation(); if (spawnLocation == null) { - Bukkit.getServer().getLogger().log(Level.WARNING, - "SkyBlock | Error: The location for the spawn point could not be found."); + Bukkit.getServer().getLogger().log(Level.WARNING, "SkyBlock | Error: The location for the spawn point could not be found."); return; } @@ -230,8 +227,7 @@ public final class LocationUtil { return null; } - public static Location getRandomLocation(World world, int xRange, int zRange, boolean loadChunk, - boolean ignoreLiquid) { + public static Location getRandomLocation(World world, int xRange, int zRange, boolean loadChunk, boolean ignoreLiquid) { Random rnd = new Random(); int rndX = rnd.nextInt(xRange); @@ -242,16 +238,14 @@ public final class LocationUtil { double rndY = -1; if (world.getEnvironment() == Environment.NETHER) { - + Location rndLoc = new Location(world, rndX, 0, rndZ); - + for (int i = 120; i > 0; i--) { rndLoc.setY(i); - if (rndLoc.getBlock().getType() != Material.AIR - && rndLoc.clone().add(0.0D, 1.0D, 0.0D).getBlock().getType() == Material.AIR - && rndLoc.clone().add(0.0D, 2.0D, 0.0D).getBlock().getType() == Material.AIR - && rndLoc.clone().add(0.0D, 3.0D, 0.0D).getBlock().getType() == Material.AIR + if (rndLoc.getBlock().getType() != Material.AIR && rndLoc.clone().add(0.0D, 1.0D, 0.0D).getBlock().getType() == Material.AIR + && rndLoc.clone().add(0.0D, 2.0D, 0.0D).getBlock().getType() == Material.AIR && rndLoc.clone().add(0.0D, 3.0D, 0.0D).getBlock().getType() == Material.AIR && rndLoc.clone().add(0.0D, 4.0D, 0.0D).getBlock().getType() == Material.AIR) { rndY = i; break; diff --git a/src/main/java/com/songoda/skyblock/utils/world/block/BlockUtil.java b/src/main/java/com/songoda/skyblock/utils/world/block/BlockUtil.java index 64b01165..9271c98e 100644 --- a/src/main/java/com/songoda/skyblock/utils/world/block/BlockUtil.java +++ b/src/main/java/com/songoda/skyblock/utils/world/block/BlockUtil.java @@ -21,548 +21,531 @@ import java.util.List; @SuppressWarnings("deprecation") public final class BlockUtil { - public static BlockData convertBlockToBlockData(Block block, int x, int y, int z) { - BlockData blockData = new BlockData(block.getType().toString(), block.getData(), x, y, z, - block.getBiome().toString()); - - int NMSVersion = NMSUtil.getVersionNumber(); - blockData.setVersion(NMSVersion); - - if (NMSVersion > 12) { - blockData.setBlockData(block.getBlockData().getAsString()); - } - - BlockState blockState = block.getState(); - MaterialData materialData = blockState.getData(); - - if (blockState instanceof Banner) { - Banner banner = (Banner) blockState; - blockData.setBaseColor(banner.getBaseColor().toString()); - - List patterns = new ArrayList<>(); - - for (Pattern patternList : banner.getPatterns()) { - patterns.add(patternList.getPattern().toString() + ":" + patternList.getColor().toString()); - } - - blockData.setPatterns(patterns); - blockData.setStateType(BlockStateType.BANNER.toString()); - } else if (blockState instanceof Beacon) { - Beacon beacon = (Beacon) blockState; - String primaryEffectName = beacon.getPrimaryEffect() != null ? beacon.getPrimaryEffect().toString() : "null"; - String secondaryEffectName = beacon.getSecondaryEffect() != null ? beacon.getSecondaryEffect().toString() : "null"; - - blockData.setPotionEffect(primaryEffectName + ":" + secondaryEffectName); - blockData.setStateType(BlockStateType.BEACON.toString()); - } else if (blockState instanceof BrewingStand) { - BrewingStand brewingStand = (BrewingStand) blockState; - blockData.setBrewingTime(brewingStand.getBrewingTime()); - blockData.setFuelLevel(brewingStand.getFuelLevel()); - blockData.setStateType(BlockStateType.BREWINGSTAND.toString()); - } else if (blockState instanceof Furnace) { - Furnace furnace = (Furnace) blockState; - blockData.setBurnTime(furnace.getBurnTime()); - blockData.setCookTime(furnace.getCookTime()); - - for (int i = 0; i < furnace.getInventory().getSize(); i++) { - ItemStack is = furnace.getInventory().getItem(i); - - if (is != null && is.getType() != Material.AIR) { - blockData.addItem(i, ItemStackUtil.serializeItemStack(is)); - } - } - - blockData.setStateType(BlockStateType.FURNACE.toString()); - } else if (blockState instanceof Chest) { - Chest chest = (Chest) blockState; - - for (int i = 0; i < chest.getInventory().getSize(); i++) { - ItemStack is = chest.getInventory().getItem(i); - - if (is != null && is.getType() != Material.AIR) { - blockData.addItem(i, ItemStackUtil.serializeItemStack(is)); - } - } - - blockData.setStateType(BlockStateType.CHEST.toString()); - } else if (blockState instanceof Dispenser) { - Dispenser dispenser = (Dispenser) blockState; - - for (int i = 0; i < dispenser.getInventory().getSize(); i++) { - ItemStack is = dispenser.getInventory().getItem(i); - - if (is != null && is.getType() != Material.AIR) { - blockData.addItem(i, ItemStackUtil.serializeItemStack(is)); - } - } - - blockData.setStateType(BlockStateType.DISPENSER.toString()); - } else if (blockState instanceof Dropper) { - Dropper dropper = (Dropper) blockState; - - for (int i = 0; i < dropper.getInventory().getSize(); i++) { - ItemStack is = dropper.getInventory().getItem(i); - - if (is != null && is.getType() != Material.AIR) { - blockData.addItem(i, ItemStackUtil.serializeItemStack(is)); - } - } - - blockData.setStateType(BlockStateType.DROPPER.toString()); - } else if (blockState instanceof Hopper) { - Hopper hopper = (Hopper) blockState; - - for (int i = 0; i < hopper.getInventory().getSize(); i++) { - ItemStack is = hopper.getInventory().getItem(i); - - if (is != null && is.getType() != Material.AIR) { - blockData.addItem(i, ItemStackUtil.serializeItemStack(is)); - } - } - - blockData.setStateType(BlockStateType.HOPPER.toString()); - } else if (blockState instanceof CommandBlock) { - CommandBlock commandBlock = (CommandBlock) blockState; - blockData.setCommand(commandBlock.getCommand()); - blockData.setCommandBlockName(commandBlock.getName()); - blockData.setStateType(BlockStateType.COMMANDBLOCK.toString()); - } else if (blockState instanceof CreatureSpawner) { - CreatureSpawner creatureSpawner = (CreatureSpawner) blockState; - - if (creatureSpawner.getSpawnedType() != null) { - blockData.setEntity(creatureSpawner.getSpawnedType().toString()); - } - - blockData.setDelay(creatureSpawner.getDelay()); - blockData.setStateType(BlockStateType.CREATURESPAWNER.toString()); - } else if (blockState instanceof Jukebox) { - Jukebox jukebox = (Jukebox) blockState; - - if (jukebox.getPlaying() != null) { - blockData.setPlaying(jukebox.getPlaying().toString()); - } - - blockData.setStateType(BlockStateType.JUKEBOX.toString()); - } else if (blockState instanceof Sign) { - Sign sign = (Sign) blockState; - - String[] signLines = sign.getLines(); - - if (signLines != null) { - List correctedSignLines = new ArrayList<>(); - - for (String signLineList : signLines) { - for (ChatColor chatColorList : ChatColor.values()) { - signLineList = signLineList.replace(chatColorList + "", - "&" + chatColorList.toString().substring(chatColorList.toString().length() - 1)); - } - - correctedSignLines.add(signLineList); - } - - signLines = correctedSignLines.toArray(new String[correctedSignLines.size()]); - } - - blockData.setSignLines(signLines); - blockData.setStateType(BlockStateType.SIGN.toString()); - } else if (blockState instanceof Skull) { - Skull skull = (Skull) blockState; - blockData.setSkullOwner(skull.getOwner()); - blockData.setSkullType(skull.getSkullType().toString()); - blockData.setRotateFace(skull.getRotation().toString()); - blockData.setStateType(BlockStateType.SKULL.toString()); - } else { - if (NMSVersion > 8) { - if (blockState instanceof EndGateway) { - EndGateway endGateway = (EndGateway) blockState; - blockData.setExactTeleport(endGateway.isExactTeleport()); - - Location location = endGateway.getExitLocation(); - blockData.setExitLocation(location.getX() + ":" + location.getY() + ":" + location.getZ() + ":" - + location.getWorld().getName()); - blockData.setStateType(BlockStateType.ENDGATEWAY.toString()); - } - - if (NMSVersion > 10) { - if (blockState instanceof ShulkerBox) { - ShulkerBox shulkerBox = (ShulkerBox) blockState; - - for (int i = 0; i < shulkerBox.getInventory().getSize(); i++) { - ItemStack is = shulkerBox.getInventory().getItem(i); - - if (is != null && is.getType() != Material.AIR) { - blockData.addItem(i, ItemStackUtil.serializeItemStack(is)); - } - } - - blockData.setStateType(BlockStateType.SHULKERBOX.toString()); - } - } - } - } - - if (materialData instanceof Stairs) { - blockData.setFacing(((Stairs) materialData).getFacing().toString()); - blockData.setDataType(BlockDataType.STAIRS.toString()); - } else if (materialData instanceof org.bukkit.material.FlowerPot) { - if (NMSVersion >= 8 && NMSVersion <= 12) { - try { - World world = block.getWorld(); - - Class blockPositionClass = NMSUtil.getNMSClass("BlockPosition"); - - Object worldHandle = world.getClass().getMethod("getHandle").invoke(world); - Object blockPosition = blockPositionClass.getConstructor(int.class, int.class, int.class) - .newInstance(block.getX(), block.getY(), block.getZ()); - Object tileEntity = worldHandle.getClass().getMethod("getTileEntity", blockPositionClass) - .invoke(worldHandle, blockPosition); - - Field aField = tileEntity.getClass().getDeclaredField("a"); - aField.setAccessible(true); - - Object item = aField.get(tileEntity); - - if (item != null) { - Object itemStackNMS = NMSUtil.getNMSClass("ItemStack") - .getConstructor(NMSUtil.getNMSClass("Item")).newInstance(item); - - ItemStack itemStack = (ItemStack) NMSUtil.getCraftClass("inventory.CraftItemStack") - .getMethod("asBukkitCopy", itemStackNMS.getClass()).invoke(null, itemStackNMS); - - Field fField = tileEntity.getClass().getDeclaredField("f"); - fField.setAccessible(true); - - int data = (int) fField.get(tileEntity); - - blockData.setFlower(itemStack.getType().name() + ":" + data); - } - } catch (Exception e) { - e.printStackTrace(); - } - } else { - org.bukkit.material.FlowerPot flowerPot = (org.bukkit.material.FlowerPot) materialData; - - if (flowerPot.getContents() != null && flowerPot.getContents().getItemType() != Material.AIR) { - blockData.setFlower( - flowerPot.getContents().getItemType().toString() + ":" + flowerPot.getContents().getData()); - } - } - - blockData.setDataType(BlockDataType.FLOWERPOT.toString()); - } - - return blockData; - } - - public static void convertBlockDataToBlock(Block block, BlockData blockData) { - int NMSVersion = NMSUtil.getVersionNumber(); - - Material material = null; - - if (NMSVersion > 12 && blockData.getVersion() > 12 && blockData.getBlockData() != null) { - block.setBlockData(Bukkit.getServer().createBlockData(blockData.getBlockData())); - } else { - material = MaterialUtil.getMaterial(NMSVersion, blockData.getVersion(), - blockData.getMaterial(), block.getData()); - setBlockFast(block.getWorld(), block.getX(), block.getY(), block.getZ(), material, blockData.getData()); - } - - // TODO Create a class to support biome changes - // block.setBiome(Biome.valueOf(blockData.getBiome().toUpperCase())); - - BlockStateType blockTypeState = BlockStateType.valueOf(blockData.getStateType()); - - if (blockTypeState == BlockStateType.BANNER) { - Banner banner = (Banner) block.getState(); - banner.setBaseColor(DyeColor.valueOf(blockData.getBaseColor().toUpperCase())); - - for (String patternList : blockData.getPatterns()) { - String[] pattern = patternList.split(":"); - banner.addPattern(new Pattern(DyeColor.valueOf(pattern[1].toUpperCase()), - PatternType.valueOf(pattern[0].toUpperCase()))); - } - } else if (blockTypeState == BlockStateType.BEACON) { - Beacon beacon = (Beacon) block.getState(); - String[] potionEffect = blockData.getPotionEffect().split(":"); - if (!potionEffect[0].equals("null")) { - beacon.setPrimaryEffect(PotionEffectType.getByName(potionEffect[0].toUpperCase())); - } - - if (!potionEffect[1].equals("null")) { - beacon.setSecondaryEffect(PotionEffectType.getByName(potionEffect[1].toUpperCase())); - } - } else if (blockTypeState == BlockStateType.BREWINGSTAND) { - BrewingStand brewingStand = (BrewingStand) block.getState(); - brewingStand.setBrewingTime(blockData.getBrewingTime()); - brewingStand.setFuelLevel(blockData.getFuelLevel()); - } else if (blockTypeState == BlockStateType.COMMANDBLOCK) { - CommandBlock commandBlock = (CommandBlock) block.getState(); - commandBlock.setCommand(blockData.getCommand()); - commandBlock.setName(blockData.getCommandBlockName()); - } else if (blockTypeState == BlockStateType.CHEST) { - Chest chest = (Chest) block.getState(); - - for (Integer slotList : blockData.getInventory().keySet()) { - if (slotList < chest.getInventory().getSize()) { - ItemStack is = ItemStackUtil.deserializeItemStack(blockData.getInventory().get(slotList)); - chest.getInventory().setItem(slotList, is); - } - } - } else if (blockTypeState == BlockStateType.DISPENSER) { - Dispenser dispenser = (Dispenser) block.getState(); - - for (Integer slotList : blockData.getInventory().keySet()) { - if (slotList < dispenser.getInventory().getSize()) { - ItemStack is = ItemStackUtil.deserializeItemStack(blockData.getInventory().get(slotList)); - dispenser.getInventory().setItem(slotList, is); - } - } - } else if (blockTypeState == BlockStateType.DROPPER) { - Dropper dropper = (Dropper) block.getState(); - - for (Integer slotList : blockData.getInventory().keySet()) { - if (slotList < dropper.getInventory().getSize()) { - ItemStack is = ItemStackUtil.deserializeItemStack(blockData.getInventory().get(slotList)); - dropper.getInventory().setItem(slotList, is); - } - } - } else if (blockTypeState == BlockStateType.HOPPER) { - Hopper hopper = (Hopper) block.getState(); - - for (Integer slotList : blockData.getInventory().keySet()) { - if (slotList < hopper.getInventory().getSize()) { - ItemStack is = ItemStackUtil.deserializeItemStack(blockData.getInventory().get(slotList)); - hopper.getInventory().setItem(slotList, is); - } - } - } else if (blockTypeState == BlockStateType.CREATURESPAWNER) { - CreatureSpawner creatureSpawner = (CreatureSpawner) block.getState(); - - if (blockData.getEntity() != null) { - creatureSpawner.setSpawnedType(EntityType.valueOf(blockData.getEntity().toUpperCase())); - } - - creatureSpawner.setDelay(blockData.getDelay()); - } else if (blockTypeState == BlockStateType.FURNACE) { - Furnace furnace = (Furnace) block.getState(); - furnace.setBurnTime(blockData.getBurnTime()); - furnace.setCookTime(blockData.getCookTime()); - - for (Integer slotList : blockData.getInventory().keySet()) { - if (slotList < furnace.getInventory().getSize()) { - ItemStack is = ItemStackUtil.deserializeItemStack(blockData.getInventory().get(slotList)); - furnace.getInventory().setItem(slotList, is); - } - } - } else if (blockTypeState == BlockStateType.JUKEBOX) { - Jukebox jukebox = (Jukebox) block.getState(); - - if (blockData.getPlaying() != null) { - jukebox.setPlaying(Material.valueOf(blockData.getPlaying().toUpperCase())); - } - } else if (blockTypeState == BlockStateType.SIGN) { - Sign sign = (Sign) block.getState(); - - for (int i = 0; i < blockData.getSignLines().length; i++) { - sign.setLine(i, ChatColor.translateAlternateColorCodes('&', blockData.getSignLines()[i])); - } - } else if (blockTypeState == BlockStateType.SKULL) { - Skull skull = (Skull) block.getState(); - - skull.setRotation(BlockFace.valueOf(blockData.getRotateFace().toUpperCase())); - skull.setSkullType(SkullType.valueOf(blockData.getSkullType().toUpperCase())); - - if (NMSVersion > 9) { - skull.setOwningPlayer(Bukkit.getServer().getOfflinePlayer(blockData.getSkullOwner())); - } else { - skull.setOwner(blockData.getSkullOwner()); - } - } else { - if (NMSVersion > 8) { - if (blockTypeState == BlockStateType.ENDGATEWAY) { - EndGateway endGateway = (EndGateway) block.getState(); - endGateway.setExactTeleport(blockData.isExactTeleport()); - - String[] exitLocation = blockData.getExitLocation().split(":"); - World exitLocationWorld = Bukkit.getServer().getWorld(exitLocation[3]); - - double exitLocationX = Double.parseDouble(exitLocation[0]); - double exitLocationY = Double.parseDouble(exitLocation[1]); - double exitLocationZ = Double.parseDouble(exitLocation[2]); - - endGateway.setExitLocation( - new Location(exitLocationWorld, exitLocationX, exitLocationY, exitLocationZ)); - } - - if (NMSVersion > 9) { - if (NMSVersion > 10) { - if (blockTypeState == BlockStateType.SHULKERBOX) { - ShulkerBox shulkerBox = (ShulkerBox) block.getState(); - - for (Integer slotList : blockData.getInventory().keySet()) { - if (slotList < shulkerBox.getInventory().getSize()) { - ItemStack is = ItemStackUtil - .deserializeItemStack(blockData.getInventory().get(slotList)); - shulkerBox.getInventory().setItem(slotList, is); - } - } - } - } - } - } - } - - BlockDataType blockDataType = BlockDataType.valueOf(blockData.getDataType()); - - if (blockDataType == BlockDataType.STAIRS) { - Stairs stairs = (Stairs) block.getState().getData(); - stairs.setFacingDirection(BlockFace.valueOf(blockData.getFacing())); - block.getState().setData(stairs); - } else if (blockDataType == BlockDataType.FLOWERPOT) { - if (NMSVersion >= 8 && NMSVersion <= 12) { - if (block.getLocation().clone().subtract(0.0D, 1.0D, 0.0D).getBlock().getType() == Material.AIR) { - setBlockFast(block.getWorld(), block.getX(), block.getY() - 1, block.getZ(), Material.STONE, - (byte) 0); - } - - if (blockData.getFlower() != null && !blockData.getFlower().isEmpty()) { - try { - String[] flower = blockData.getFlower().split(":"); - int materialData = Integer.parseInt(flower[1]); - - material = MaterialUtil.getMaterial(NMSVersion, - blockData.getVersion(), flower[0].toUpperCase(), materialData); - - if (material != null) { - ItemStack is = new ItemStack(material, 1, (byte) materialData); - - World world = block.getWorld(); - - Class blockPositionClass = NMSUtil.getNMSClass("BlockPosition"); - - Object worldHandle = world.getClass().getMethod("getHandle").invoke(world); - Object blockPosition = blockPositionClass.getConstructor(int.class, int.class, int.class) - .newInstance(block.getX(), block.getY(), block.getZ()); - Object tileEntity = worldHandle.getClass().getMethod("getTileEntity", blockPositionClass) - .invoke(worldHandle, blockPosition); - Object itemStack = NMSUtil.getCraftClass("inventory.CraftItemStack") - .getMethod("asNMSCopy", is.getClass()).invoke(null, is); - Object item = itemStack.getClass().getMethod("getItem").invoke(itemStack); - Object data = itemStack.getClass().getMethod("getData").invoke(itemStack); - - Field aField = tileEntity.getClass().getDeclaredField("a"); - aField.setAccessible(true); - aField.set(tileEntity, item); - - Field fField = tileEntity.getClass().getDeclaredField("f"); - fField.setAccessible(true); - fField.set(tileEntity, data); - - tileEntity.getClass().getMethod("update").invoke(tileEntity); - } - } catch (Exception e) { - e.printStackTrace(); - } - } - } else { - if (blockData.getFlower() != null && !blockData.getFlower().isEmpty()) { - org.bukkit.material.FlowerPot flowerPot = (org.bukkit.material.FlowerPot) block.getState() - .getData(); - String[] flower = blockData.getFlower().split(":"); - material = null; - - if (blockData.getVersion() > 12) { - if (NMSVersion > 12) { - material = Material.valueOf(flower[0].toUpperCase()); - } - } else { - if (NMSVersion < 13) { - material = Material.valueOf(flower[0].toUpperCase()); - } - } - - if (material != null) { - flowerPot.setContents(new MaterialData(material, (byte) Integer.parseInt(flower[1]))); - } - - block.getState().setData(flowerPot); - } - } - } - - if (NMSVersion < 13) { - block.getState().update(); - } - - if (blockData.getMaterial().equals("DOUBLE_PLANT")) { - Block topBlock = block.getLocation().clone().add(0.0D, 1.0D, 0.0D).getBlock(); - Block bottomBlock = block.getLocation().clone().subtract(0.0D, 1.0D, 0.0D).getBlock(); - - if (bottomBlock.getType() == Material.AIR && !topBlock.getType().name().equals("DOUBLE_PLANT")) { - bottomBlock.setType(Materials.LEGACY_DOUBLE_PLANT.getPostMaterial()); - - if (NMSVersion < 13) { - try { - bottomBlock.getClass().getMethod("setData", byte.class).invoke(bottomBlock, (byte) 2); - } catch (Exception e) { - e.printStackTrace(); - } - } - } - } - } - - public static List getNearbyBlocks(Location loc, int rx, int ry, int rz) { - List nearbyBlocks = new ArrayList<>(); - - for (int x = -(rx); x <= rx; x++) { - for (int y = -(ry); y <= ry; y++) { - for (int z = -(rz); z <= rz; z++) { - nearbyBlocks.add( - new Location(loc.getWorld(), loc.getX() + x, loc.getY() + y, loc.getZ() + z).getBlock()); - } - } - } - - return nearbyBlocks; - } - - private static Class IBlockDataClass = NMSUtil.getNMSClass("IBlockData"); - private static Class blocksClass = NMSUtil.getNMSClass("Blocks"); - - private static void setBlockFast(World world, int x, int y, int z, Material material, byte data) { - try { - Object worldHandle = world.getClass().getMethod("getHandle").invoke(world); - Object chunk = worldHandle.getClass().getMethod("getChunkAt", int.class, int.class).invoke(worldHandle, - x >> 4, z >> 4); - Object blockPosition = NMSUtil.getNMSClass("BlockPosition").getConstructor(int.class, int.class, int.class) - .newInstance(x & 0xF, y, z & 0xF); - - if (NMSUtil.getVersionNumber() > 12) { - Object block = blocksClass.getField(material.name()).get(null); - Object IBlockData = block.getClass().getMethod("getBlockData").invoke(block); - worldHandle.getClass().getMethod("setTypeAndData", blockPosition.getClass(), IBlockDataClass, int.class) - .invoke(worldHandle, blockPosition, IBlockData, 2); - - try { - chunk.getClass().getMethod("a", blockPosition.getClass(), IBlockDataClass, boolean.class) - .invoke(chunk, blockPosition, IBlockData, true); - } catch (Exception e) { - chunk.getClass().getMethod("setType", blockPosition.getClass(), IBlockDataClass, boolean.class) - .invoke(chunk, blockPosition, IBlockData, true); - } - } else { - Object IBlockData = NMSUtil.getNMSClass("Block").getMethod("getByCombinedId", int.class).invoke(null, - material.getId() + (data << 12)); - worldHandle.getClass().getMethod("setTypeAndData", blockPosition.getClass(), IBlockDataClass, int.class) - .invoke(worldHandle, blockPosition, IBlockData, 3); - chunk.getClass().getMethod("a", blockPosition.getClass(), IBlockDataClass).invoke(chunk, blockPosition, - IBlockData); - } - } catch (Exception e) { - Block block = world.getBlockAt(x, y, z); - block.getState().setRawData(data); - block.setType(material); - } - } + public static BlockData convertBlockToBlockData(Block block, int x, int y, int z) { + BlockData blockData = new BlockData(block.getType().toString(), block.getData(), x, y, z, block.getBiome().toString()); + + int NMSVersion = NMSUtil.getVersionNumber(); + blockData.setVersion(NMSVersion); + + if (NMSVersion > 12) { + blockData.setBlockData(block.getBlockData().getAsString()); + } + + BlockState blockState = block.getState(); + MaterialData materialData = blockState.getData(); + + if (blockState instanceof Banner) { + Banner banner = (Banner) blockState; + blockData.setBaseColor(banner.getBaseColor().toString()); + + final List bannerPatterns = banner.getPatterns(); + final List stringPatterns = new ArrayList<>(bannerPatterns.size()); + + for (Pattern patternList : bannerPatterns) { + stringPatterns.add(patternList.getPattern().toString() + ":" + patternList.getColor().toString()); + } + + blockData.setPatterns(stringPatterns); + blockData.setStateType(BlockStateType.BANNER.toString()); + } else if (blockState instanceof Beacon) { + Beacon beacon = (Beacon) blockState; + String primaryEffectName = beacon.getPrimaryEffect() != null ? beacon.getPrimaryEffect().toString() : "null"; + String secondaryEffectName = beacon.getSecondaryEffect() != null ? beacon.getSecondaryEffect().toString() : "null"; + + blockData.setPotionEffect(primaryEffectName + ":" + secondaryEffectName); + blockData.setStateType(BlockStateType.BEACON.toString()); + } else if (blockState instanceof BrewingStand) { + BrewingStand brewingStand = (BrewingStand) blockState; + blockData.setBrewingTime(brewingStand.getBrewingTime()); + blockData.setFuelLevel(brewingStand.getFuelLevel()); + blockData.setStateType(BlockStateType.BREWINGSTAND.toString()); + } else if (blockState instanceof Furnace) { + Furnace furnace = (Furnace) blockState; + blockData.setBurnTime(furnace.getBurnTime()); + blockData.setCookTime(furnace.getCookTime()); + + for (int i = 0; i < furnace.getInventory().getSize(); i++) { + ItemStack is = furnace.getInventory().getItem(i); + + if (is != null && is.getType() != Material.AIR) { + blockData.addItem(i, ItemStackUtil.serializeItemStack(is)); + } + } + + blockData.setStateType(BlockStateType.FURNACE.toString()); + } else if (blockState instanceof Chest) { + Chest chest = (Chest) blockState; + + for (int i = 0; i < chest.getInventory().getSize(); i++) { + ItemStack is = chest.getInventory().getItem(i); + + if (is != null && is.getType() != Material.AIR) { + blockData.addItem(i, ItemStackUtil.serializeItemStack(is)); + } + } + + blockData.setStateType(BlockStateType.CHEST.toString()); + } else if (blockState instanceof Dispenser) { + Dispenser dispenser = (Dispenser) blockState; + + for (int i = 0; i < dispenser.getInventory().getSize(); i++) { + ItemStack is = dispenser.getInventory().getItem(i); + + if (is != null && is.getType() != Material.AIR) { + blockData.addItem(i, ItemStackUtil.serializeItemStack(is)); + } + } + + blockData.setStateType(BlockStateType.DISPENSER.toString()); + } else if (blockState instanceof Dropper) { + Dropper dropper = (Dropper) blockState; + + for (int i = 0; i < dropper.getInventory().getSize(); i++) { + ItemStack is = dropper.getInventory().getItem(i); + + if (is != null && is.getType() != Material.AIR) { + blockData.addItem(i, ItemStackUtil.serializeItemStack(is)); + } + } + + blockData.setStateType(BlockStateType.DROPPER.toString()); + } else if (blockState instanceof Hopper) { + Hopper hopper = (Hopper) blockState; + + for (int i = 0; i < hopper.getInventory().getSize(); i++) { + ItemStack is = hopper.getInventory().getItem(i); + + if (is != null && is.getType() != Material.AIR) { + blockData.addItem(i, ItemStackUtil.serializeItemStack(is)); + } + } + + blockData.setStateType(BlockStateType.HOPPER.toString()); + } else if (blockState instanceof CommandBlock) { + CommandBlock commandBlock = (CommandBlock) blockState; + blockData.setCommand(commandBlock.getCommand()); + blockData.setCommandBlockName(commandBlock.getName()); + blockData.setStateType(BlockStateType.COMMANDBLOCK.toString()); + } else if (blockState instanceof CreatureSpawner) { + CreatureSpawner creatureSpawner = (CreatureSpawner) blockState; + + if (creatureSpawner.getSpawnedType() != null) { + blockData.setEntity(creatureSpawner.getSpawnedType().toString()); + } + + blockData.setDelay(creatureSpawner.getDelay()); + blockData.setStateType(BlockStateType.CREATURESPAWNER.toString()); + } else if (blockState instanceof Jukebox) { + Jukebox jukebox = (Jukebox) blockState; + + if (jukebox.getPlaying() != null) { + blockData.setPlaying(jukebox.getPlaying().toString()); + } + + blockData.setStateType(BlockStateType.JUKEBOX.toString()); + } else if (blockState instanceof Sign) { + Sign sign = (Sign) blockState; + + String[] signLines = sign.getLines(); + + if (signLines != null) { + List correctedSignLines = new ArrayList<>(); + + for (String signLineList : signLines) { + for (ChatColor chatColorList : ChatColor.values()) { + signLineList = signLineList.replace(chatColorList + "", "&" + chatColorList.toString().substring(chatColorList.toString().length() - 1)); + } + + correctedSignLines.add(signLineList); + } + + signLines = correctedSignLines.toArray(new String[correctedSignLines.size()]); + } + + blockData.setSignLines(signLines); + blockData.setStateType(BlockStateType.SIGN.toString()); + } else if (blockState instanceof Skull) { + Skull skull = (Skull) blockState; + blockData.setSkullOwner(skull.getOwner()); + blockData.setSkullType(skull.getSkullType().toString()); + blockData.setRotateFace(skull.getRotation().toString()); + blockData.setStateType(BlockStateType.SKULL.toString()); + } else { + if (NMSVersion > 8) { + if (blockState instanceof EndGateway) { + EndGateway endGateway = (EndGateway) blockState; + blockData.setExactTeleport(endGateway.isExactTeleport()); + + Location location = endGateway.getExitLocation(); + blockData.setExitLocation(location.getX() + ":" + location.getY() + ":" + location.getZ() + ":" + location.getWorld().getName()); + blockData.setStateType(BlockStateType.ENDGATEWAY.toString()); + } + + if (NMSVersion > 10) { + if (blockState instanceof ShulkerBox) { + ShulkerBox shulkerBox = (ShulkerBox) blockState; + + for (int i = 0; i < shulkerBox.getInventory().getSize(); i++) { + ItemStack is = shulkerBox.getInventory().getItem(i); + + if (is != null && is.getType() != Material.AIR) { + blockData.addItem(i, ItemStackUtil.serializeItemStack(is)); + } + } + + blockData.setStateType(BlockStateType.SHULKERBOX.toString()); + } + } + } + } + + if (materialData instanceof Stairs) { + blockData.setFacing(((Stairs) materialData).getFacing().toString()); + blockData.setDataType(BlockDataType.STAIRS.toString()); + } else if (materialData instanceof org.bukkit.material.FlowerPot) { + if (NMSVersion >= 8 && NMSVersion <= 12) { + try { + World world = block.getWorld(); + + Class blockPositionClass = NMSUtil.getNMSClass("BlockPosition"); + + Object worldHandle = world.getClass().getMethod("getHandle").invoke(world); + Object blockPosition = blockPositionClass.getConstructor(int.class, int.class, int.class).newInstance(block.getX(), block.getY(), block.getZ()); + Object tileEntity = worldHandle.getClass().getMethod("getTileEntity", blockPositionClass).invoke(worldHandle, blockPosition); + + Field aField = tileEntity.getClass().getDeclaredField("a"); + aField.setAccessible(true); + + Object item = aField.get(tileEntity); + + if (item != null) { + Object itemStackNMS = NMSUtil.getNMSClass("ItemStack").getConstructor(NMSUtil.getNMSClass("Item")).newInstance(item); + + ItemStack itemStack = (ItemStack) NMSUtil.getCraftClass("inventory.CraftItemStack").getMethod("asBukkitCopy", itemStackNMS.getClass()).invoke(null, itemStackNMS); + + Field fField = tileEntity.getClass().getDeclaredField("f"); + fField.setAccessible(true); + + int data = (int) fField.get(tileEntity); + + blockData.setFlower(itemStack.getType().name() + ":" + data); + } + } catch (Exception e) { + e.printStackTrace(); + } + } else { + org.bukkit.material.FlowerPot flowerPot = (org.bukkit.material.FlowerPot) materialData; + + if (flowerPot.getContents() != null && flowerPot.getContents().getItemType() != Material.AIR) { + blockData.setFlower(flowerPot.getContents().getItemType().toString() + ":" + flowerPot.getContents().getData()); + } + } + + blockData.setDataType(BlockDataType.FLOWERPOT.toString()); + } + + return blockData; + } + + public static void convertBlockDataToBlock(Block block, BlockData blockData) { + int NMSVersion = NMSUtil.getVersionNumber(); + + Material material = null; + + if (NMSVersion > 12 && blockData.getVersion() > 12 && blockData.getBlockData() != null) { + block.setBlockData(Bukkit.getServer().createBlockData(blockData.getBlockData())); + } else { + material = MaterialUtil.getMaterial(NMSVersion, blockData.getVersion(), blockData.getMaterial(), block.getData()); + setBlockFast(block.getWorld(), block.getX(), block.getY(), block.getZ(), material, blockData.getData()); + } + + // TODO Create a class to support biome changes + // block.setBiome(Biome.valueOf(blockData.getBiome().toUpperCase())); + + BlockStateType blockTypeState = BlockStateType.valueOf(blockData.getStateType()); + + BlockState state = block.getState(); + + if (blockTypeState == BlockStateType.BANNER) { + Banner banner = (Banner) state; + banner.setBaseColor(DyeColor.valueOf(blockData.getBaseColor().toUpperCase())); + + for (String patternList : blockData.getPatterns()) { + String[] pattern = patternList.split(":"); + banner.addPattern(new Pattern(DyeColor.valueOf(pattern[1].toUpperCase()), PatternType.valueOf(pattern[0].toUpperCase()))); + } + state.update(); + } else if (blockTypeState == BlockStateType.BEACON) { + Beacon beacon = (Beacon) state; + String[] potionEffect = blockData.getPotionEffect().split(":"); + if (!potionEffect[0].equals("null")) { + beacon.setPrimaryEffect(PotionEffectType.getByName(potionEffect[0].toUpperCase())); + } + + if (!potionEffect[1].equals("null")) { + beacon.setSecondaryEffect(PotionEffectType.getByName(potionEffect[1].toUpperCase())); + } + state.update(); + } else if (blockTypeState == BlockStateType.BREWINGSTAND) { + BrewingStand brewingStand = (BrewingStand) state; + brewingStand.setBrewingTime(blockData.getBrewingTime()); + brewingStand.setFuelLevel(blockData.getFuelLevel()); + state.update(); + } else if (blockTypeState == BlockStateType.COMMANDBLOCK) { + CommandBlock commandBlock = (CommandBlock) state; + commandBlock.setCommand(blockData.getCommand()); + commandBlock.setName(blockData.getCommandBlockName()); + state.update(); + } else if (blockTypeState == BlockStateType.CHEST) { + Chest chest = (Chest) state; + + for (Integer slotList : blockData.getInventory().keySet()) { + if (slotList < chest.getInventory().getSize()) { + ItemStack is = ItemStackUtil.deserializeItemStack(blockData.getInventory().get(slotList)); + chest.getInventory().setItem(slotList, is); + } + } + } else if (blockTypeState == BlockStateType.DISPENSER) { + Dispenser dispenser = (Dispenser) state; + + for (Integer slotList : blockData.getInventory().keySet()) { + if (slotList < dispenser.getInventory().getSize()) { + ItemStack is = ItemStackUtil.deserializeItemStack(blockData.getInventory().get(slotList)); + dispenser.getInventory().setItem(slotList, is); + } + } + } else if (blockTypeState == BlockStateType.DROPPER) { + Dropper dropper = (Dropper) state; + + for (Integer slotList : blockData.getInventory().keySet()) { + if (slotList < dropper.getInventory().getSize()) { + ItemStack is = ItemStackUtil.deserializeItemStack(blockData.getInventory().get(slotList)); + dropper.getInventory().setItem(slotList, is); + } + } + } else if (blockTypeState == BlockStateType.HOPPER) { + Hopper hopper = (Hopper) state; + + for (Integer slotList : blockData.getInventory().keySet()) { + if (slotList < hopper.getInventory().getSize()) { + ItemStack is = ItemStackUtil.deserializeItemStack(blockData.getInventory().get(slotList)); + hopper.getInventory().setItem(slotList, is); + } + } + } else if (blockTypeState == BlockStateType.CREATURESPAWNER) { + CreatureSpawner creatureSpawner = (CreatureSpawner) state; + + if (blockData.getEntity() != null) { + creatureSpawner.setSpawnedType(EntityType.valueOf(blockData.getEntity().toUpperCase())); + } + + creatureSpawner.setDelay(blockData.getDelay()); + state.update(); + } else if (blockTypeState == BlockStateType.FURNACE) { + Furnace furnace = (Furnace) state; + furnace.setBurnTime(blockData.getBurnTime()); + furnace.setCookTime(blockData.getCookTime()); + + state.update(); + + for (Integer slotList : blockData.getInventory().keySet()) { + if (slotList < furnace.getInventory().getSize()) { + ItemStack is = ItemStackUtil.deserializeItemStack(blockData.getInventory().get(slotList)); + furnace.getInventory().setItem(slotList, is); + } + } + } else if (blockTypeState == BlockStateType.JUKEBOX) { + Jukebox jukebox = (Jukebox) state; + + if (blockData.getPlaying() != null) { + jukebox.setPlaying(Material.valueOf(blockData.getPlaying().toUpperCase())); + } + state.update(); + } else if (blockTypeState == BlockStateType.SIGN) { + Sign sign = (Sign) state; + + for (int i = 0; i < blockData.getSignLines().length; i++) { + sign.setLine(i, ChatColor.translateAlternateColorCodes('&', blockData.getSignLines()[i])); + } + state.update(); + } else if (blockTypeState == BlockStateType.SKULL) { + Skull skull = (Skull) state; + + skull.setRotation(BlockFace.valueOf(blockData.getRotateFace().toUpperCase())); + skull.setSkullType(SkullType.valueOf(blockData.getSkullType().toUpperCase())); + + if (NMSVersion > 9) { + skull.setOwningPlayer(Bukkit.getServer().getOfflinePlayer(blockData.getSkullOwner())); + } else { + skull.setOwner(blockData.getSkullOwner()); + } + state.update(); + } else { + if (NMSVersion > 8) { + if (blockTypeState == BlockStateType.ENDGATEWAY) { + EndGateway endGateway = (EndGateway) state; + endGateway.setExactTeleport(blockData.isExactTeleport()); + + String[] exitLocation = blockData.getExitLocation().split(":"); + World exitLocationWorld = Bukkit.getServer().getWorld(exitLocation[3]); + + double exitLocationX = Double.parseDouble(exitLocation[0]); + double exitLocationY = Double.parseDouble(exitLocation[1]); + double exitLocationZ = Double.parseDouble(exitLocation[2]); + + endGateway.setExitLocation(new Location(exitLocationWorld, exitLocationX, exitLocationY, exitLocationZ)); + state.update(); + } + + if (NMSVersion > 9) { + if (NMSVersion > 10) { + if (blockTypeState == BlockStateType.SHULKERBOX) { + ShulkerBox shulkerBox = (ShulkerBox) state; + + for (Integer slotList : blockData.getInventory().keySet()) { + if (slotList < shulkerBox.getInventory().getSize()) { + ItemStack is = ItemStackUtil.deserializeItemStack(blockData.getInventory().get(slotList)); + shulkerBox.getInventory().setItem(slotList, is); + } + } + } + } + } + } + } + + BlockDataType blockDataType = BlockDataType.valueOf(blockData.getDataType()); + + if (blockDataType == BlockDataType.STAIRS) { + Stairs stairs = (Stairs) state.getData(); + stairs.setFacingDirection(BlockFace.valueOf(blockData.getFacing())); + state.setData(stairs); + } else if (blockDataType == BlockDataType.FLOWERPOT) { + if (NMSVersion >= 8 && NMSVersion <= 12) { + if (block.getLocation().clone().subtract(0.0D, 1.0D, 0.0D).getBlock().getType() == Material.AIR) { + setBlockFast(block.getWorld(), block.getX(), block.getY() - 1, block.getZ(), Material.STONE, (byte) 0); + } + + if (blockData.getFlower() != null && !blockData.getFlower().isEmpty()) { + try { + String[] flower = blockData.getFlower().split(":"); + int materialData = Integer.parseInt(flower[1]); + + material = MaterialUtil.getMaterial(NMSVersion, blockData.getVersion(), flower[0].toUpperCase(), materialData); + + if (material != null) { + ItemStack is = new ItemStack(material, 1, (byte) materialData); + + World world = block.getWorld(); + + Class blockPositionClass = NMSUtil.getNMSClass("BlockPosition"); + + Object worldHandle = world.getClass().getMethod("getHandle").invoke(world); + Object blockPosition = blockPositionClass.getConstructor(int.class, int.class, int.class).newInstance(block.getX(), block.getY(), block.getZ()); + Object tileEntity = worldHandle.getClass().getMethod("getTileEntity", blockPositionClass).invoke(worldHandle, blockPosition); + Object itemStack = NMSUtil.getCraftClass("inventory.CraftItemStack").getMethod("asNMSCopy", is.getClass()).invoke(null, is); + Object item = itemStack.getClass().getMethod("getItem").invoke(itemStack); + Object data = itemStack.getClass().getMethod("getData").invoke(itemStack); + + Field aField = tileEntity.getClass().getDeclaredField("a"); + aField.setAccessible(true); + aField.set(tileEntity, item); + + Field fField = tileEntity.getClass().getDeclaredField("f"); + fField.setAccessible(true); + fField.set(tileEntity, data); + + tileEntity.getClass().getMethod("update").invoke(tileEntity); + } + } catch (Exception e) { + e.printStackTrace(); + } + } + } else { + if (blockData.getFlower() != null && !blockData.getFlower().isEmpty()) { + org.bukkit.material.FlowerPot flowerPot = (org.bukkit.material.FlowerPot) state.getData(); + String[] flower = blockData.getFlower().split(":"); + material = null; + + if (blockData.getVersion() > 12) { + if (NMSVersion > 12) { + material = Material.valueOf(flower[0].toUpperCase()); + } + } else { + if (NMSVersion < 13) { + material = Material.valueOf(flower[0].toUpperCase()); + } + } + + if (material != null) { + flowerPot.setContents(new MaterialData(material, (byte) Integer.parseInt(flower[1]))); + } + + state.setData(flowerPot); + } + } + } + + if (blockData.getMaterial().equals("DOUBLE_PLANT")) { + Block topBlock = block.getLocation().add(0.0D, 1.0D, 0.0D).getBlock(); + Block bottomBlock = block.getLocation().subtract(0.0D, 1.0D, 0.0D).getBlock(); + + if (bottomBlock.getType() == Material.AIR && !topBlock.getType().name().equals("DOUBLE_PLANT")) { + bottomBlock.setType(Materials.LEGACY_DOUBLE_PLANT.getPostMaterial()); + + if (NMSVersion < 13) { + try { + bottomBlock.getClass().getMethod("setData", byte.class).invoke(bottomBlock, (byte) 2); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } + } + + public static List getNearbyBlocks(Location loc, int rx, int ry, int rz) { + final List nearbyBlocks = new ArrayList<>((rx + ry + rz) * 2); + + for (int x = -(rx); x <= rx; x++) { + for (int y = -(ry); y <= ry; y++) { + for (int z = -(rz); z <= rz; z++) { + nearbyBlocks.add(new Location(loc.getWorld(), loc.getX() + x, loc.getY() + y, loc.getZ() + z).getBlock()); + } + } + } + + return nearbyBlocks; + } + + private static Class IBlockDataClass = NMSUtil.getNMSClass("IBlockData"); + private static Class blocksClass = NMSUtil.getNMSClass("Blocks"); + + private static void setBlockFast(World world, int x, int y, int z, Material material, byte data) { + try { + Object worldHandle = world.getClass().getMethod("getHandle").invoke(world); + Object chunk = worldHandle.getClass().getMethod("getChunkAt", int.class, int.class).invoke(worldHandle, x >> 4, z >> 4); + Object blockPosition = NMSUtil.getNMSClass("BlockPosition").getConstructor(int.class, int.class, int.class).newInstance(x & 0xF, y, z & 0xF); + + if (NMSUtil.getVersionNumber() > 12) { + Object block = blocksClass.getField(material.name()).get(null); + Object IBlockData = block.getClass().getMethod("getBlockData").invoke(block); + worldHandle.getClass().getMethod("setTypeAndData", blockPosition.getClass(), IBlockDataClass, int.class).invoke(worldHandle, blockPosition, IBlockData, 2); + + try { + chunk.getClass().getMethod("a", blockPosition.getClass(), IBlockDataClass, boolean.class).invoke(chunk, blockPosition, IBlockData, true); + } catch (Exception ignored) { + chunk.getClass().getMethod("setType", blockPosition.getClass(), IBlockDataClass, boolean.class).invoke(chunk, blockPosition, IBlockData, true); + } + } else { + Object IBlockData = NMSUtil.getNMSClass("Block").getMethod("getByCombinedId", int.class).invoke(null, material.getId() + (data << 12)); + worldHandle.getClass().getMethod("setTypeAndData", blockPosition.getClass(), IBlockDataClass, int.class).invoke(worldHandle, blockPosition, IBlockData, 3); + chunk.getClass().getMethod("a", blockPosition.getClass(), IBlockDataClass).invoke(chunk, blockPosition, IBlockData); + } + } catch (Exception e) { + Block block = world.getBlockAt(x, y, z); + block.getState().setRawData(data); + block.setType(material); + } + } } diff --git a/src/main/java/com/songoda/skyblock/visit/VisitManager.java b/src/main/java/com/songoda/skyblock/visit/VisitManager.java index 08a36c2d..9b25704c 100644 --- a/src/main/java/com/songoda/skyblock/visit/VisitManager.java +++ b/src/main/java/com/songoda/skyblock/visit/VisitManager.java @@ -173,11 +173,7 @@ public class VisitManager { } public Visit getIsland(UUID islandOwnerUUID) { - if (hasIsland(islandOwnerUUID)) { - return visitStorage.get(islandOwnerUUID); - } - - return null; + return visitStorage.get(islandOwnerUUID); } public HashMap getIslands() { diff --git a/src/main/java/com/songoda/skyblock/visit/VisitTask.java b/src/main/java/com/songoda/skyblock/visit/VisitTask.java index c0c014d8..e79d4560 100644 --- a/src/main/java/com/songoda/skyblock/visit/VisitTask.java +++ b/src/main/java/com/songoda/skyblock/visit/VisitTask.java @@ -1,10 +1,9 @@ package com.songoda.skyblock.visit; +import org.bukkit.scheduler.BukkitRunnable; + import com.songoda.skyblock.playerdata.PlayerData; import com.songoda.skyblock.playerdata.PlayerDataManager; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.scheduler.BukkitRunnable; public class VisitTask extends BukkitRunnable { @@ -16,13 +15,9 @@ public class VisitTask extends BukkitRunnable { @Override public void run() { - for (Player all : Bukkit.getOnlinePlayers()) { - if (playerDataManager.hasPlayerData(all)) { - PlayerData playerData = playerDataManager.getPlayerData(all); - - if (playerData.getIsland() != null) { - playerData.setVisitTime(playerData.getVisitTime() + 1); - } + for (PlayerData playerData : playerDataManager.getPlayerData().values()) { + if (playerData.getIsland() != null) { + playerData.setVisitTime(playerData.getVisitTime() + 1); } } } diff --git a/src/main/java/com/songoda/skyblock/world/WorldManager.java b/src/main/java/com/songoda/skyblock/world/WorldManager.java index dc8236b0..315a30f8 100644 --- a/src/main/java/com/songoda/skyblock/world/WorldManager.java +++ b/src/main/java/com/songoda/skyblock/world/WorldManager.java @@ -44,28 +44,22 @@ public class WorldManager { endWorld = Bukkit.getServer().getWorld(endWorldName); if (normalWorld == null) { - Bukkit.getServer().getLogger().log(Level.INFO, - "SkyBlock | Info: Generating VoidWorld '" + normalWorldName + "'."); - normalWorld = WorldCreator.name(normalWorldName).type(WorldType.FLAT).environment(normalWorldEnvironment) - .generator(new VoidGenerator()).createWorld(); + Bukkit.getServer().getLogger().log(Level.INFO, "SkyBlock | Info: Generating VoidWorld '" + normalWorldName + "'."); + normalWorld = WorldCreator.name(normalWorldName).type(WorldType.FLAT).environment(normalWorldEnvironment).generator(new VoidGenerator()).createWorld(); Bukkit.getServer().getScheduler().runTask(skyblock, () -> registerMultiverse(normalWorldName, normalWorldEnvironment)); } if (netherWorld == null && netherWorldEnabled) { - Bukkit.getServer().getLogger().log(Level.INFO, - "SkyBlock | Info: Generating VoidWorld '" + netherWorldName + "'."); - netherWorld = WorldCreator.name(netherWorldName).type(WorldType.FLAT).environment(netherWorldEnvironment) - .generator(new VoidGenerator()).createWorld(); + Bukkit.getServer().getLogger().log(Level.INFO, "SkyBlock | Info: Generating VoidWorld '" + netherWorldName + "'."); + netherWorld = WorldCreator.name(netherWorldName).type(WorldType.FLAT).environment(netherWorldEnvironment).generator(new VoidGenerator()).createWorld(); Bukkit.getServer().getScheduler().runTask(skyblock, () -> registerMultiverse(netherWorldName, netherWorldEnvironment)); } if (endWorld == null && endWorldEnabled) { - Bukkit.getServer().getLogger().log(Level.INFO, - "SkyBlock | Info: Generating VoidWorld '" + endWorldName + "'."); - endWorld = WorldCreator.name(endWorldName).type(WorldType.FLAT).environment(endWorldEnvironment) - .generator(new VoidGenerator()).createWorld(); + Bukkit.getServer().getLogger().log(Level.INFO, "SkyBlock | Info: Generating VoidWorld '" + endWorldName + "'."); + endWorld = WorldCreator.name(endWorldName).type(WorldType.FLAT).environment(endWorldEnvironment).generator(new VoidGenerator()).createWorld(); Bukkit.getServer().getScheduler().runTask(skyblock, () -> registerMultiverse(endWorldName, endWorldEnvironment)); } @@ -73,10 +67,8 @@ public class WorldManager { public void registerMultiverse(String worldName, World.Environment environment) { if (Bukkit.getServer().getPluginManager().getPlugin("Multiverse-Core") != null) { - Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), - "mv import " + worldName + " " + environment.name().toLowerCase() + " -g " + skyblock.getName()); - Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), - "mv modify set generator " + skyblock.getName() + " " + worldName); + Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv import " + worldName + " " + environment.name().toLowerCase() + " -g " + skyblock.getName()); + Bukkit.getServer().dispatchCommand(Bukkit.getServer().getConsoleSender(), "mv modify set generator " + skyblock.getName() + " " + worldName); } } @@ -97,27 +89,21 @@ public class WorldManager { return null; } - if (normalWorld != null && normalWorld.getName().equals(world.getName())) - return IslandWorld.Normal; + if (normalWorld != null && normalWorld.getName().equals(world.getName())) return IslandWorld.Normal; - if (netherWorld != null && netherWorld.getName().equals(world.getName())) - return IslandWorld.Nether; + if (netherWorld != null && netherWorld.getName().equals(world.getName())) return IslandWorld.Nether; - if (endWorld != null && endWorld.getName().equals(world.getName())) - return IslandWorld.End; + if (endWorld != null && endWorld.getName().equals(world.getName())) return IslandWorld.End; return null; } public boolean isIslandWorld(World world) { - if (world == null) - return false; + if (world == null) return false; - if (normalWorld != null && normalWorld.getName().equals(world.getName())) - return true; + if (normalWorld != null && normalWorld.getName().equals(world.getName())) return true; - if (netherWorld != null && netherWorld.getName().equals(world.getName())) - return true; + if (netherWorld != null && netherWorld.getName().equals(world.getName())) return true; return endWorld != null && endWorld.getName().equals(world.getName()); } diff --git a/src/main/java/com/songoda/skyblock/world/generator/VoidGenerator.java b/src/main/java/com/songoda/skyblock/world/generator/VoidGenerator.java index 41ad509a..abc6ee82 100644 --- a/src/main/java/com/songoda/skyblock/world/generator/VoidGenerator.java +++ b/src/main/java/com/songoda/skyblock/world/generator/VoidGenerator.java @@ -1,40 +1,41 @@ package com.songoda.skyblock.world.generator; -import com.songoda.skyblock.SkyBlock; -import com.songoda.skyblock.config.FileManager.Config; -import com.songoda.skyblock.island.IslandWorld; -import com.songoda.skyblock.utils.version.Materials; -import org.bukkit.Material; -import org.bukkit.World; -import org.bukkit.configuration.file.FileConfiguration; -import org.bukkit.generator.BlockPopulator; -import org.bukkit.generator.ChunkGenerator; - import java.io.File; import java.util.Arrays; import java.util.List; import java.util.Random; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.configuration.Configuration; +import org.bukkit.configuration.ConfigurationSection; +import org.bukkit.generator.BlockPopulator; +import org.bukkit.generator.ChunkGenerator; + +import com.songoda.skyblock.SkyBlock; +import com.songoda.skyblock.island.IslandWorld; +import com.songoda.skyblock.utils.version.Materials; + public class VoidGenerator extends ChunkGenerator { @Override public ChunkData generateChunkData(World world, Random random, int chunkX, int chunkZ, BiomeGrid biome) { - ChunkData chunkData = createChunkData(world); + final ChunkData chunkData = createChunkData(world); - SkyBlock skyblock = SkyBlock.getInstance(); - - Config config = skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")); - FileConfiguration configLoad = config.getFileConfiguration(); + final SkyBlock skyblock = SkyBlock.getInstance(); + final Configuration configLoad = skyblock.getFileManager().getConfig(new File(skyblock.getDataFolder(), "config.yml")).getFileConfiguration(); + final ConfigurationSection worldSection = configLoad.getConfigurationSection("Island.World"); for (IslandWorld worldList : IslandWorld.values()) { if (world.getEnvironment() == worldList.getUncheckedEnvironment()) { - if (configLoad.getBoolean("Island.World." + worldList.name() + ".Liquid.Enable")) { - if (configLoad.getBoolean("Island.World." + worldList.name() + ".Liquid.Lava")) { - setBlock(chunkData, Materials.LEGACY_STATIONARY_LAVA.parseMaterial(), - configLoad.getInt("Island.World." + worldList.name() + ".Liquid.Height")); + + ConfigurationSection section = worldSection.getConfigurationSection(worldList.name()); + + if (section.getBoolean("Liquid.Enable")) { + if (section.getBoolean("Liquid.Lava")) { + setBlock(chunkData, Materials.LEGACY_STATIONARY_LAVA.parseMaterial(), section.getInt("Liquid.Height")); } else { - setBlock(chunkData, Materials.LEGACY_STATIONARY_WATER.parseMaterial(), - configLoad.getInt("Island.World." + worldList.name() + ".Liquid.Height")); + setBlock(chunkData, Materials.LEGACY_STATIONARY_WATER.parseMaterial(), section.getInt("Liquid.Height")); } } diff --git a/src/main/resources/language.yml b/src/main/resources/language.yml index 4afc7667..04fd15b6 100644 --- a/src/main/resources/language.yml +++ b/src/main/resources/language.yml @@ -806,6 +806,7 @@ Command: Message: '&bSkyBlock &8| &cError&8: &eYou must close your Island before deleting it.' Sender: Message: '&bSkyBlock &8| &aInfo&8: &eYou are no longer an Island Owner.' + MaxDeletionMessage: '&bSkyBlock &8| &cError&8: &eYou have reach the maximum island deletions. Sorry.' Broadcast: Message: '&bSkyBlock &8| &aInfo&8: &eThe Island Owner has disbanded the Island.' Money: @@ -3109,11 +3110,6 @@ Placeholder: Message: '&f&oUnclaimed' Non-empty: Message: '&f[%position] %player [%level]' - fabledskyblock_island_points: - Non-empty: - Message: '&f%placeholder' - Empty: - Message: '&c0' fabledskyblock_island_visitors: Non-empty: Message: '&f%placeholder' @@ -3194,11 +3190,6 @@ Placeholder: Message: '&f&oNone' Non-empty: Message: '&f%placeholder' - fabledskyblock_island_level: - Empty: - Message: '&c0' - Non-empty: - Message: '&f%placeholder' fabledskyblock_island_level_formatted: Empty: Message: '&c0' @@ -3376,6 +3367,7 @@ Island: Message: '&bSkyBlock &8| &cError&8: &eYou must wait &c&o%time &ebefore creating an Island.' Error: Message: '&bSkyBlock &8| &cError&8: &eThe main spawn point must be set before you are able to create an Island by performing the command ''&f&o/island admin setspawn&e''.' + MaxCreationMessage: '&bSkyBlock &8| &cError&8: &eYou have reach the maximum island creations. Sorry.' Upgrade: Owner: Message: '&bSkyBlock &8| &cError&8: &eYou are not an Island Owner.'