From 9705fedd04c9e5431d69fb30dbe343c8f1037918 Mon Sep 17 00:00:00 2001 From: Tastybento Date: Tue, 26 Dec 2017 08:41:37 -0800 Subject: [PATCH] Reworked using new Command API --- plugin.yml | 12 + src/bskyblock/addin/level/CalculateLevel.java | 103 ---- src/bskyblock/addin/level/ChunkScanner.java | 345 +++++++++++++ src/bskyblock/addin/level/Level.java | 50 +- .../addin/level/LevelCalcByChunk.java | 484 ------------------ src/bskyblock/addin/level/LevelPlugin.java | 13 +- src/bskyblock/addin/level/LevelPresenter.java | 98 ++++ src/bskyblock/addin/level/TopTen.java | 9 +- .../addin/level/commands/AdminLevel.java | 44 ++ .../addin/level/commands/AdminTop.java | 39 ++ .../addin/level/commands/Commands.java | 190 ------- .../addin/level/commands/IslandLevel.java | 48 ++ .../addin/level/commands/IslandTop.java | 27 + .../addin/level/config/LocaleManager.java | 28 - .../level/event/IslandPostLevelEvent.java | 4 +- .../level/event/IslandPreLevelEvent.java | 4 +- 16 files changed, 646 insertions(+), 852 deletions(-) delete mode 100644 src/bskyblock/addin/level/CalculateLevel.java create mode 100644 src/bskyblock/addin/level/ChunkScanner.java delete mode 100644 src/bskyblock/addin/level/LevelCalcByChunk.java create mode 100644 src/bskyblock/addin/level/LevelPresenter.java create mode 100644 src/bskyblock/addin/level/commands/AdminLevel.java create mode 100644 src/bskyblock/addin/level/commands/AdminTop.java delete mode 100644 src/bskyblock/addin/level/commands/Commands.java create mode 100644 src/bskyblock/addin/level/commands/IslandLevel.java create mode 100644 src/bskyblock/addin/level/commands/IslandTop.java delete mode 100644 src/bskyblock/addin/level/config/LocaleManager.java diff --git a/plugin.yml b/plugin.yml index 1897429..f2bbac8 100755 --- a/plugin.yml +++ b/plugin.yml @@ -9,4 +9,16 @@ depend: [BSkyBlock] permissions: bskyblock.intopten: description: Player is in the top ten. + default: true + bskyblock.island.level: + description: Player can use level command + default: true + bskyblock.island.topten: + description: Player can use top ten command + default: true + bskyblock.admin.level: + description: Player can use admin level command + default: true + bskyblock.admin.topten: + description: Player can use admin top ten command default: true \ No newline at end of file diff --git a/src/bskyblock/addin/level/CalculateLevel.java b/src/bskyblock/addin/level/CalculateLevel.java deleted file mode 100644 index 715b81d..0000000 --- a/src/bskyblock/addin/level/CalculateLevel.java +++ /dev/null @@ -1,103 +0,0 @@ -package bskyblock.addin.level; - -import java.util.Calendar; -import java.util.HashMap; -import java.util.UUID; - -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import us.tastybento.bskyblock.config.Settings; -import us.tastybento.bskyblock.util.Util; -import us.tastybento.bskyblock.util.VaultHelper; - -public class CalculateLevel extends LevelPlugin { - - private int levelWait; - // Level calc cool down - private HashMap levelWaitTime = new HashMap(); - - public CalculateLevel(Level plugin) { - super(plugin); - } - - /** - * Calculates the island level - * - * @param sender - * - Player object of player who is asking - * @param targetPlayer - * - UUID of the player's island that is being requested - * @return - true if successful. - */ - public boolean calculateIslandLevel(final CommandSender sender, final UUID targetPlayer) { - return calculateIslandLevel(sender, targetPlayer, false); - } - - /** - * Calculates the island level - * @param sender - asker of the level info - * @param targetPlayer - * @param report - if true, a detailed report will be provided - * @return - false if this is cannot be done - */ - public boolean calculateIslandLevel(final CommandSender sender, final UUID targetPlayer, boolean report) { - if (sender instanceof Player) { - Player asker = (Player)sender; - // Player asking for their own island calc - if (asker.getUniqueId().equals(targetPlayer) || asker.isOp() || VaultHelper.hasPerm(asker, Settings.PERMPREFIX + "mod.info")) { - // Newer better system - uses chunks - if (!onLevelWaitTime(asker) || levelWait <= 0 || asker.isOp() || VaultHelper.hasPerm(asker, Settings.PERMPREFIX + "mod.info")) { - Util.sendMessage(asker, ChatColor.GREEN + "Calculating level, please wait..."); - setLevelWaitTime(asker); - new LevelCalcByChunk(plugin, bSkyBlock, targetPlayer, asker, report); - } else { - Util.sendMessage(asker, ChatColor.YELLOW + String.valueOf(getLevelWaitTime(asker))); - } - - } else { - // Asking for the level of another player - Util.sendMessage(asker, ChatColor.GREEN + plugin.getLocale(asker.getUniqueId()).get("island.islandLevelIs").replace("[level]", String.valueOf(plugin.getIslandLevel(targetPlayer)))); - } - } else { - // Console request - //Util.sendMessage(sender, ChatColor.GREEN + bSkyBlock.myLocale().levelCalculating); - new LevelCalcByChunk(plugin, bSkyBlock, targetPlayer, sender, report); - } - return true; - } - - /** - * Sets cool down for the level command - * - * @param player - */ - private void setLevelWaitTime(final Player player) { - levelWaitTime.put(player.getUniqueId(), Long.valueOf(Calendar.getInstance().getTimeInMillis() + levelWait * 1000)); - } - - private boolean onLevelWaitTime(final Player player) { - if (levelWaitTime.containsKey(player.getUniqueId())) { - if (levelWaitTime.get(player.getUniqueId()).longValue() > Calendar.getInstance().getTimeInMillis()) { - return true; - } - - return false; - } - - return false; - } - - private long getLevelWaitTime(final Player player) { - if (levelWaitTime.containsKey(player.getUniqueId())) { - if (levelWaitTime.get(player.getUniqueId()).longValue() > Calendar.getInstance().getTimeInMillis()) { - return (levelWaitTime.get(player.getUniqueId()).longValue() - Calendar.getInstance().getTimeInMillis()) / 1000; - } - - return 0L; - } - - return 0L; - } -} diff --git a/src/bskyblock/addin/level/ChunkScanner.java b/src/bskyblock/addin/level/ChunkScanner.java new file mode 100644 index 0000000..ae84abc --- /dev/null +++ b/src/bskyblock/addin/level/ChunkScanner.java @@ -0,0 +1,345 @@ +package bskyblock.addin.level; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +import org.bukkit.Chunk; +import org.bukkit.ChunkSnapshot; +import org.bukkit.Material; +import org.bukkit.World; +import org.bukkit.material.MaterialData; + +import com.google.common.collect.HashMultiset; +import com.google.common.collect.Multiset; +import com.google.common.collect.Multiset.Entry; +import com.google.common.collect.Multisets; + +import bskyblock.addin.level.config.Settings; +import us.tastybento.bskyblock.BSkyBlock; +import us.tastybento.bskyblock.api.commands.User; +import us.tastybento.bskyblock.database.objects.Island; + +/** + * A class that calculates the level of an island very quickly by copying island + * chunks to a list and then processing asynchronously. + * + * @author tastybento + * + */ +public class ChunkScanner { + private static final boolean DEBUG = false; + protected static final boolean LEVEL_LOGGING = false; + private final Level plugin; + private final Set finalChunk; + private final Results result; + private final Optional asker; + + + public ChunkScanner(Level plugin, Island island) { + this.plugin = plugin; + // Get the chunks to scan + finalChunk = getIslandChunks(island); + this.asker = Optional.empty(); + // Create new level result + result = new Results(); + runAsyncCount(island); + } + + /** + * Calculates the level of an island + * @param plugin + * @param island - island that is being calculated + * @param asker - the user who wants the report + */ + public ChunkScanner(Level plugin, Island island, User asker) { + this.plugin = plugin; + // Get the chunks to scan + finalChunk = getIslandChunks(island); + this.asker = Optional.of(asker); + // Create new level result + result = new Results(); + runAsyncCount(island); + } + + private void runAsyncCount(Island island) { + // Run AsyncTask to count blocks in the chunk snapshots + plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() { + + @SuppressWarnings("deprecation") + @Override + public void run() { + // Copy the limits hashmap + HashMap limitCount = new HashMap(Settings.blockLimits); + // Calculate the island score + for (ChunkSnapshot chunk: finalChunk) { + for (int x = 0; x< 16; x++) { + // Check if the block coord is inside the protection zone and if not, don't count it + if (chunk.getX() * 16 + x < island.getMinProtectedX() || chunk.getX() * 16 + x >= island.getMinProtectedX() + (island.getProtectionRange() * 2)) { + if (DEBUG) + plugin.getLogger().info("Block is outside protected area - x = " + (chunk.getX() * 16 + x)); + continue; + } + for (int z = 0; z < 16; z++) { + // Check if the block coord is inside the protection zone and if not, don't count it + if (chunk.getZ() * 16 + z < island.getMinProtectedZ() || chunk.getZ() * 16 + z >= island.getMinProtectedZ() + (island.getProtectionRange() * 2)) { + if (DEBUG) + plugin.getLogger().info("Block is outside protected area - z = " + (chunk.getZ() * 16 + z)); + continue; + } + + for (int y = 0; y < island.getWorld().getMaxHeight(); y++) { + Material type = chunk.getBlockType(x, y, z); + // Currently, there is no alternative to using block data (Dec 2017) + MaterialData md = new MaterialData(type, (byte) chunk.getBlockData(x, y, z)); + MaterialData generic = new MaterialData(type); + if (!type.equals(Material.AIR)) { // AIR + if (DEBUG) + plugin.getLogger().info("Block is inside protected area " + (chunk.getX() * 16) + "," + (chunk.getZ() * 16 + z)); + if (DEBUG) + plugin.getLogger().info("Block is " + md + "[" + generic +"]"); + if (limitCount.containsKey(md) && Settings.blockValues.containsKey(md)) { + int count = limitCount.get(md); + if (DEBUG) + plugin.getLogger().info("DEBUG: Count for non-generic " + md + " is " + count); + if (count > 0) { + limitCount.put(md, --count); + if (Settings.seaHeight > 0 && y<=Settings.seaHeight) { + result.underWaterBlockCount += Settings.blockValues.get(md); + result.uwCount.add(md); + } else { + result.rawBlockCount += Settings.blockValues.get(md); + result.mdCount.add(md); + } + } else { + result.ofCount.add(md); + } + } else if (limitCount.containsKey(generic) && Settings.blockValues.containsKey(generic)) { + int count = limitCount.get(generic); + if (DEBUG) + plugin.getLogger().info("DEBUG: Count for generic " + generic + " is " + count); + if (count > 0) { + limitCount.put(generic, --count); + if (Settings.seaHeight > 0 && y<=Settings.seaHeight) { + result.underWaterBlockCount += Settings.blockValues.get(generic); + result.uwCount.add(md); + } else { + result.rawBlockCount += Settings.blockValues.get(generic); + result.mdCount.add(md); + } + } else { + result.ofCount.add(md); + } + } else if (Settings.blockValues.containsKey(md)) { + if (DEBUG) + plugin.getLogger().info("DEBUG: Adding " + md + " = " + Settings.blockValues.get(md)); + if (Settings.seaHeight > 0 && y<=Settings.seaHeight) { + result.underWaterBlockCount += Settings.blockValues.get(md); + result.uwCount.add(md); + } else { + result.rawBlockCount += Settings.blockValues.get(md); + result.mdCount.add(md); + } + } else if (Settings.blockValues.containsKey(generic)) { + if (DEBUG) + plugin.getLogger().info("DEBUG: Adding " + generic + " = " + Settings.blockValues.get(generic)); + if (Settings.seaHeight > 0 && y<=Settings.seaHeight) { + result.underWaterBlockCount += Settings.blockValues.get(generic); + result.uwCount.add(md); + } else { + result.rawBlockCount += Settings.blockValues.get(generic); + result.mdCount.add(md); + } + } else { + result.ncCount.add(md); + } + } + } + } + } + } + + result.rawBlockCount += (long)((double)result.underWaterBlockCount * Settings.underWaterMultiplier); + if (DEBUG) + plugin.getLogger().info("DEBUG: block count = "+result.rawBlockCount); + // Set the death penalty + result.deathHandicap = BSkyBlock.getPlugin().getPlayers().getDeaths(island.getOwner()) * Settings.deathpenalty; + // Set final score + result.score = (result.rawBlockCount / Settings.levelCost) - result.deathHandicap; + + // Return to main thread + plugin.getServer().getScheduler().runTask(plugin, new Runnable() { + + @Override + public void run() { + // Run any modifications + + // All done. + if (asker.isPresent()) { + // Tell the asker the result + if (asker.get().isPlayer() && asker.get().isOnline()) { + asker.get().sendLegacyMessage("Your level is " + result.score); + } else { + // Console + sendConsoleReport(asker); + } + } + } + + private void sendConsoleReport(Optional asker) { + List reportLines = new ArrayList<>(); + // provide counts + reportLines.add("Level Log for island at " + island.getCenter()); + reportLines.add("Island owner UUID = " + island.getOwner()); + reportLines.add("Total block value count = " + String.format("%,d",result.rawBlockCount)); + reportLines.add("Level cost = " + Settings.levelCost); + //reportLines.add("Level multiplier = " + levelMultiplier + " (Player must be online to get a permission multiplier)"); + //reportLines.add("Schematic level handicap = " + levelHandicap + " (level is reduced by this amount)"); + reportLines.add("Deaths handicap = " + result.deathHandicap); + reportLines.add("Level calculated = " + result.score); + reportLines.add("=================================="); + int total = 0; + if (!result.uwCount.isEmpty()) { + reportLines.add("Underwater block count (Multiplier = x" + Settings.underWaterMultiplier + ") value"); + reportLines.add("Total number of underwater blocks = " + String.format("%,d",result.uwCount.size())); + Iterable> entriesSortedByCount = + Multisets.copyHighestCountFirst(result.uwCount).entrySet(); + Iterator> it = entriesSortedByCount.iterator(); + while (it.hasNext()) { + Entry en = it.next(); + MaterialData type = en.getElement(); + + int value = 0; + if (Settings.blockValues.containsKey(type)) { + // Specific + value = Settings.blockValues.get(type); + } else if (Settings.blockValues.containsKey(new MaterialData(type.getItemType()))) { + // Generic + value = Settings.blockValues.get(new MaterialData(type.getItemType())); + } + if (value > 0) { + reportLines.add(type.toString() + ":" + + String.format("%,d",en.getCount()) + " blocks x " + value + " = " + (value * en.getCount())); + total += (value * en.getCount()); + } + } + reportLines.add("Subtotal = " + total); + reportLines.add("=================================="); + } + reportLines.add("Regular block count"); + reportLines.add("Total number of blocks = " + String.format("%,d",result.mdCount.size())); + //Iterable> entriesSortedByCount = + // Multisets.copyHighestCountFirst(mdCount).entrySet(); + Iterable> entriesSortedByCount = + result.mdCount.entrySet(); + Iterator> it = entriesSortedByCount.iterator(); + while (it.hasNext()) { + Entry en = it.next(); + MaterialData type = en.getElement(); + int value = 0; + if (Settings.blockValues.containsKey(type)) { + // Specific + value = Settings.blockValues.get(type); + } else if (Settings.blockValues.containsKey(new MaterialData(type.getItemType()))) { + // Generic + value = Settings.blockValues.get(new MaterialData(type.getItemType())); + } + if (value > 0) { + reportLines.add(type.toString() + ":" + + String.format("%,d",en.getCount()) + " blocks x " + value + " = " + (value * en.getCount())); + total += (value * en.getCount()); + } + } + reportLines.add("Total = " + total); + reportLines.add("=================================="); + reportLines.add("Blocks not counted because they exceeded limits: " + String.format("%,d",result.ofCount.size())); + //entriesSortedByCount = Multisets.copyHighestCountFirst(ofCount).entrySet(); + entriesSortedByCount = result.ofCount.entrySet(); + it = entriesSortedByCount.iterator(); + while (it.hasNext()) { + Entry type = it.next(); + Integer limit = Settings.blockLimits.get(type.getElement()); + String explain = ")"; + if (limit == null) { + MaterialData generic = new MaterialData(type.getElement().getItemType()); + limit = Settings.blockLimits.get(generic); + explain = " - All types)"; + } + reportLines.add(type.getElement().toString() + ": " + String.format("%,d",type.getCount()) + " blocks (max " + limit + explain); + } + reportLines.add("=================================="); + reportLines.add("Blocks on island that are not in config.yml"); + reportLines.add("Total number = " + String.format("%,d",result.ncCount.size())); + //entriesSortedByCount = Multisets.copyHighestCountFirst(ncCount).entrySet(); + entriesSortedByCount = result.ncCount.entrySet(); + it = entriesSortedByCount.iterator(); + while (it.hasNext()) { + Entry type = it.next(); + reportLines.add(type.getElement().toString() + ": " + String.format("%,d",type.getCount()) + " blocks"); + } + reportLines.add("================================="); + + for (String line : reportLines) { + asker.get().sendLegacyMessage(line); + } + } + + }); + + } + + }); + + + } + + private Set getIslandChunks(Island island) { + // Check if player's island world is the nether or overworld and adjust accordingly + final World world = island.getWorld(); + // Get the chunks + if (DEBUG) + plugin.getLogger().info("DEBUG: Getting chunks. Protection range = " + island.getProtectionRange()); + //long nano = System.nanoTime(); + Set chunkSnapshot = new HashSet(); + for (int x = island.getMinProtectedX(); x < (island.getMinProtectedX() + (island.getProtectionRange() *2) + 16); x += 16) { + for (int z = island.getMinProtectedZ(); z < (island.getMinProtectedZ() + (island.getProtectionRange() * 2) + 16); z += 16) { + if (!world.isChunkLoaded((int)((double)x/16), (int)((double)z/16))) { + // If the chunk isn't already generated, load it but don't try and generate it + if (world.loadChunk((int)((double)x/16), (int)((double)z/16), false)) { + Chunk chunk = world.getChunkAt((int)((double)x/16), (int)((double)z/16)); + chunkSnapshot.add(chunk.getChunkSnapshot()); + } + } else { + // chunk is loaded + chunkSnapshot.add(world.getBlockAt(x, 0, z).getChunk().getChunkSnapshot()); + } + if (DEBUG) + plugin.getLogger().info("DEBUG: getting chunk at " + x + ", " + z); + } + } + if (DEBUG) + plugin.getLogger().info("DEBUG: size of chunk snapshot = " + chunkSnapshot.size()); + return chunkSnapshot; + } + + /** + * Results class + * @author ben + * + */ + public class Results { + Multiset mdCount = HashMultiset.create(); + Multiset uwCount = HashMultiset.create(); + Multiset ncCount = HashMultiset.create(); + Multiset ofCount = HashMultiset.create(); + long rawBlockCount; + Island island; + long underWaterBlockCount = 0; + long score; + int deathHandicap; + } +} diff --git a/src/bskyblock/addin/level/Level.java b/src/bskyblock/addin/level/Level.java index 6cf4fcc..50b3f25 100644 --- a/src/bskyblock/addin/level/Level.java +++ b/src/bskyblock/addin/level/Level.java @@ -7,16 +7,19 @@ import java.util.HashMap; import java.util.Map.Entry; import java.util.UUID; -import org.bukkit.command.CommandSender; import org.bukkit.plugin.java.JavaPlugin; import org.bukkit.scheduler.BukkitTask; -import bskyblock.addin.level.commands.Commands; -import bskyblock.addin.level.config.LocaleManager; +import bskyblock.addin.level.commands.AdminLevel; +import bskyblock.addin.level.commands.AdminTop; +import bskyblock.addin.level.commands.IslandLevel; +import bskyblock.addin.level.commands.IslandTop; import bskyblock.addin.level.config.PluginConfig; import bskyblock.addin.level.database.object.Levels; import us.tastybento.bskyblock.BSkyBlock; -import us.tastybento.bskyblock.config.BSBLocale; +import us.tastybento.bskyblock.api.commands.CompositeCommand; +import us.tastybento.bskyblock.api.commands.User; +import us.tastybento.bskyblock.config.Settings; import us.tastybento.bskyblock.database.BSBDatabase; import us.tastybento.bskyblock.database.managers.AbstractDatabaseHandler; @@ -34,9 +37,6 @@ public class Level extends JavaPlugin { // Level calc checker BukkitTask checker = null; - // Locale manager for this plugin - private LocaleManager localeManager; - // Database handler for level data private AbstractDatabaseHandler handler; @@ -50,6 +50,9 @@ public class Level extends JavaPlugin { // The Top Ten object private TopTen topTen; + + // Level calculator + private LevelPresenter levelCalc; @SuppressWarnings("unchecked") @Override @@ -70,13 +73,20 @@ public class Level extends JavaPlugin { handler = (AbstractDatabaseHandler) database.getHandler(bSkyBlock, Levels.class); // Initialize the cache levelsCache = new HashMap<>(); + // Load the calculator + levelCalc = new LevelPresenter(this); // Start the top ten and register it for clicks topTen = new TopTen(this); getServer().getPluginManager().registerEvents(topTen, this); // Local locales - localeManager = new LocaleManager(this); + //localeManager = new LocaleManager(this); // Register commands - new Commands(this); + CompositeCommand bsbIslandCmd = (CompositeCommand) BSkyBlock.getPlugin().getCommandsManager().getCommand(Settings.ISLANDCOMMAND); + new IslandLevel(this, bsbIslandCmd); + new IslandTop(this, bsbIslandCmd); + CompositeCommand bsbAdminCmd = (CompositeCommand) BSkyBlock.getPlugin().getCommandsManager().getCommand(Settings.ADMINCOMMAND); + new AdminLevel(this, bsbAdminCmd); + new AdminTop(this, bsbAdminCmd); // Done } @@ -154,24 +164,6 @@ public class Level extends JavaPlugin { topTen.addEntry(targetPlayer, level); } - /** - * Get the locale for this player - * @param sender - * @return Locale object for sender - */ - public BSBLocale getLocale(CommandSender sender) { - return localeManager.getLocale(sender); - } - - /** - * Get the locale for this UUID - * @param uuid - * @return Locale object for UUID - */ - public BSBLocale getLocale(UUID uuid) { - return localeManager.getLocale(uuid); - } - public AbstractDatabaseHandler getHandler() { return handler; } @@ -180,4 +172,8 @@ public class Level extends JavaPlugin { return topTen; } + public void calculateIslandLevel(User user, UUID playerUUID, boolean b) { + levelCalc.calculateIslandLevel(user, playerUUID, b); + } + } diff --git a/src/bskyblock/addin/level/LevelCalcByChunk.java b/src/bskyblock/addin/level/LevelCalcByChunk.java deleted file mode 100644 index b3d9445..0000000 --- a/src/bskyblock/addin/level/LevelCalcByChunk.java +++ /dev/null @@ -1,484 +0,0 @@ -package bskyblock.addin.level; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; -import java.util.UUID; - -import org.apache.commons.lang.math.NumberUtils; -import org.bukkit.ChatColor; -import org.bukkit.Chunk; -import org.bukkit.ChunkSnapshot; -import org.bukkit.World; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import org.bukkit.material.MaterialData; -import org.bukkit.permissions.PermissionAttachmentInfo; - -import com.google.common.collect.HashMultiset; -import com.google.common.collect.Multiset; -import com.google.common.collect.Multiset.Entry; -import com.google.common.collect.Multisets; - -import bskyblock.addin.level.config.Settings; -import bskyblock.addin.level.event.IslandPostLevelEvent; -import bskyblock.addin.level.event.IslandPreLevelEvent; -import us.tastybento.bskyblock.BSkyBlock; -import us.tastybento.bskyblock.database.objects.Island; -import us.tastybento.bskyblock.util.Util; - -/** - * A class that calculates the level of an island very quickly by copying island - * chunks to a list and then processing asynchronously. - * - * @author tastybento - * - */ -public class LevelCalcByChunk { - private static final boolean DEBUG = false; - protected static final boolean LEVEL_LOGGING = false; - private List reportLines = new ArrayList(); - - public LevelCalcByChunk(Level plugin, BSkyBlock bSkyBlock, UUID targetPlayer, CommandSender asker) { - this(plugin, bSkyBlock, targetPlayer, asker, false); - } - - /** - * Calculates the level of an island - * @param bSkyBlock - * @param targetPlayer - UUID of island owner or team member - * @param sender - requester of the level calculation, if anyone - * @param report - provide a report to the asker - */ - public LevelCalcByChunk(final Level plugin, final BSkyBlock bSkyBlock, final UUID targetPlayer, final CommandSender sender, final boolean report) { - // Get player's island - final Island island = bSkyBlock.getIslands().getIsland(targetPlayer); - if (DEBUG) - plugin.getLogger().info("DEBUG: " + island); - if (island != null) { - // Get the permission multiplier if it is available - Player player = plugin.getServer().getPlayer(targetPlayer); - int multiplier = 1; - if (player != null) { - if (DEBUG) - plugin.getLogger().info("DEBUG: player is online"); - // Get permission multiplier - for (PermissionAttachmentInfo perms : player.getEffectivePermissions()) { - if (perms.getPermission().startsWith(us.tastybento.bskyblock.config.Settings.PERMPREFIX + "island.multiplier.")) { - String spl[] = perms.getPermission().split(us.tastybento.bskyblock.config.Settings.PERMPREFIX + "island.multiplier."); - if (spl.length > 1) { - if (!NumberUtils.isDigits(spl[1])) { - bSkyBlock.getLogger().severe("Player " + player.getName() + " has permission: " + perms.getPermission() + " <-- the last part MUST be a number! Ignoring..."); - } else { - // Get the max value should there be more than one - multiplier = Math.max(multiplier, Integer.valueOf(spl[1])); - } - } - } - // Do some sanity checking - if (multiplier < 1) { - multiplier = 1; - } - } - if (DEBUG) - plugin.getLogger().info("DEBUG: multiplier = " + multiplier); - } - final int levelMultiplier = multiplier; - // Get the handicap - final int levelHandicap = island.getLevelHandicap(); - if (DEBUG) - plugin.getLogger().info("DEBUG: island level handicap = " + levelHandicap); - // Get the death handicap - int deaths = bSkyBlock.getPlayers().getDeaths(targetPlayer); - if (DEBUG) - plugin.getLogger().info("DEBUG: deaths = " + deaths); - if (bSkyBlock.getPlayers().inTeam(targetPlayer)) { - if (DEBUG) - plugin.getLogger().info("DEBUG: player is in a team"); - // Get the team leader's deaths - deaths = bSkyBlock.getPlayers().getDeaths(bSkyBlock.getIslands().getTeamLeader(targetPlayer)); - if (Settings.sumTeamDeaths) { - deaths = 0; - //plugin.getLogger().info("DEBUG: player is in team"); - for (UUID member : bSkyBlock.getIslands().getMembers(targetPlayer)) { - deaths += bSkyBlock.getPlayers().getDeaths(member); - } - } - if (DEBUG) - plugin.getLogger().info("DEBUG: deaths is now = " + deaths); - } - final int deathHandicap = deaths; - // Check if player's island world is the nether or overworld and adjust accordingly - final World world = bSkyBlock.getIslands().getIslandLocation(targetPlayer).getWorld(); - // Get the chunks - if (DEBUG) - plugin.getLogger().info("DEBUG: Getting chunks. Protection range = " + island.getProtectionRange()); - //long nano = System.nanoTime(); - Set chunkSnapshot = new HashSet(); - for (int x = island.getMinProtectedX(); x < (island.getMinProtectedX() + (island.getProtectionRange() *2) + 16); x += 16) { - for (int z = island.getMinProtectedZ(); z < (island.getMinProtectedZ() + (island.getProtectionRange() * 2) + 16); z += 16) { - if (!world.isChunkLoaded((int)((double)x/16), (int)((double)z/16))) { - //plugin.getLogger().info("DEBUG: chunk is not loaded"); - // If the chunk isn't already generated, don't try and generate it - if (world.loadChunk((int)((double)x/16), (int)((double)z/16), false)) { - //plugin.getLogger().info("DEBUG: chunk loaded"); - Chunk chunk = world.getChunkAt((int)((double)x/16), (int)((double)z/16)); - chunkSnapshot.add(chunk.getChunkSnapshot()); - //plugin.getLogger().info("DEBUG: unload = " + chunk.unload(false)); - } - } else { - //plugin.getLogger().info("DEBUG: chunk is loaded"); - chunkSnapshot.add(world.getBlockAt(x, 0, z).getChunk().getChunkSnapshot()); - } - if (DEBUG) - plugin.getLogger().info("DEBUG: getting chunk at " + x + ", " + z); - } - } - //plugin.getLogger().info("DEBUG: time = " + (System.nanoTime() - nano) / 1000000 + " ms"); - if (DEBUG) - plugin.getLogger().info("DEBUG: size of chunk snapshot = " + chunkSnapshot.size()); - final Set finalChunk = chunkSnapshot; - final int worldHeight = world.getMaxHeight(); - //plugin.getLogger().info("DEBUG:world height = " +worldHeight); - plugin.getServer().getScheduler().runTaskAsynchronously(plugin, new Runnable() { - - @Override - public void run() { - // Logging - List mdLog = null; - List uwLog = null; - List noCountLog = null; - List overflowLog = null; - if (LEVEL_LOGGING || report) { - mdLog = new ArrayList(); - uwLog = new ArrayList(); - noCountLog = new ArrayList(); - overflowLog = new ArrayList(); - } - // Copy the limits hashmap - HashMap limitCount = new HashMap(Settings.blockLimits); - // Calculate the island score - long blockCount = 0; - long underWaterBlockCount = 0; - for (ChunkSnapshot chunk: finalChunk) { - for (int x = 0; x< 16; x++) { - // Check if the block coord is inside the protection zone and if not, don't count it - if (chunk.getX() * 16 + x < island.getMinProtectedX() || chunk.getX() * 16 + x >= island.getMinProtectedX() + (island.getProtectionRange() * 2)) { - if (DEBUG) - plugin.getLogger().info("Block is outside protected area - x = " + (chunk.getX() * 16 + x)); - continue; - } - for (int z = 0; z < 16; z++) { - // Check if the block coord is inside the protection zone and if not, don't count it - if (chunk.getZ() * 16 + z < island.getMinProtectedZ() || chunk.getZ() * 16 + z >= island.getMinProtectedZ() + (island.getProtectionRange() * 2)) { - if (DEBUG) - plugin.getLogger().info("Block is outside protected area - z = " + (chunk.getZ() * 16 + z)); - continue; - } - - for (int y = 0; y < worldHeight; y++) { - int type = chunk.getBlockTypeId(x, y, z); - int data = chunk.getBlockData(x, y, z); - MaterialData md = new MaterialData(type,(byte) data); - MaterialData generic = new MaterialData(type); - if (type != 0) { // AIR - if (DEBUG) - plugin.getLogger().info("Block is inside protected area " + (chunk.getX() * 16) + "," + (chunk.getZ() * 16 + z)); - if (DEBUG) - plugin.getLogger().info("Block is " + md + "[" + generic +"]"); - if (limitCount.containsKey(md) && Settings.blockValues.containsKey(md)) { - int count = limitCount.get(md); - if (DEBUG) - plugin.getLogger().info("DEBUG: Count for non-generic " + md + " is " + count); - if (count > 0) { - limitCount.put(md, --count); - if (Settings.seaHeight > 0 && y<=Settings.seaHeight) { - underWaterBlockCount += Settings.blockValues.get(md); - if (LEVEL_LOGGING || report) { - uwLog.add(md); - } - } else { - blockCount += Settings.blockValues.get(md); - if (LEVEL_LOGGING || report) { - mdLog.add(md); - } - } - } else if (LEVEL_LOGGING || report) { - overflowLog.add(md); - } - } else if (limitCount.containsKey(generic) && Settings.blockValues.containsKey(generic)) { - int count = limitCount.get(generic); - if (DEBUG) - plugin.getLogger().info("DEBUG: Count for generic " + generic + " is " + count); - if (count > 0) { - limitCount.put(generic, --count); - if (Settings.seaHeight > 0 && y<=Settings.seaHeight) { - underWaterBlockCount += Settings.blockValues.get(generic); - if (LEVEL_LOGGING || report) { - uwLog.add(md); - } - } else { - blockCount += Settings.blockValues.get(generic); - if (LEVEL_LOGGING || report) { - mdLog.add(md); - } - } - } else if (LEVEL_LOGGING || report) { - overflowLog.add(md); - } - } else if (Settings.blockValues.containsKey(md)) { - if (DEBUG) - plugin.getLogger().info("DEBUG: Adding " + md + " = " + Settings.blockValues.get(md)); - if (Settings.seaHeight > 0 && y<=Settings.seaHeight) { - underWaterBlockCount += Settings.blockValues.get(md); - if (LEVEL_LOGGING || report) { - uwLog.add(md); - } - } else { - blockCount += Settings.blockValues.get(md); - if (LEVEL_LOGGING || report) { - mdLog.add(md); - } - } - } else if (Settings.blockValues.containsKey(generic)) { - if (DEBUG) - plugin.getLogger().info("DEBUG: Adding " + generic + " = " + Settings.blockValues.get(generic)); - if (Settings.seaHeight > 0 && y<=Settings.seaHeight) { - underWaterBlockCount += Settings.blockValues.get(generic); - if (LEVEL_LOGGING || report) { - uwLog.add(md); - } - } else { - blockCount += Settings.blockValues.get(generic); - if (LEVEL_LOGGING || report) { - mdLog.add(md); - } - } - } else if (LEVEL_LOGGING || report) { - noCountLog.add(md); - } - } - } - } - } - } - - blockCount += (long)((double)underWaterBlockCount * Settings.underWaterMultiplier); - if (DEBUG) - plugin.getLogger().info("DEBUG: block count = "+blockCount); - - final long score = (((blockCount * levelMultiplier) - (deathHandicap * Settings.deathpenalty)) / Settings.levelCost) - levelHandicap; - // Logging or report - if (LEVEL_LOGGING || report) { - // provide counts - Multiset uwCount = HashMultiset.create(uwLog); - Multiset mdCount = HashMultiset.create(mdLog); - Multiset ncCount = HashMultiset.create(noCountLog); - Multiset ofCount = HashMultiset.create(overflowLog); - reportLines.add("Level Log for island at " + island.getCenter()); - if (sender instanceof Player) { - reportLines.add("Asker is " + sender.getName() + " (" + ((Player)sender).getUniqueId().toString() + ")"); - } else { - reportLines.add("Asker is console"); - } - reportLines.add("Target player UUID = " + targetPlayer.toString()); - reportLines.add("Total block value count = " + String.format("%,d",blockCount)); - reportLines.add("Level cost = " + Settings.levelCost); - reportLines.add("Level multiplier = " + levelMultiplier + " (Player must be online to get a permission multiplier)"); - reportLines.add("Schematic level handicap = " + levelHandicap + " (level is reduced by this amount)"); - reportLines.add("Deaths handicap = " + (deathHandicap * Settings.deathpenalty) + " (" + deathHandicap + " deaths)"); - reportLines.add("Level calculated = " + score); - reportLines.add("=================================="); - int total = 0; - if (!uwCount.isEmpty()) { - reportLines.add("Underwater block count (Multiplier = x" + Settings.underWaterMultiplier + ") value"); - reportLines.add("Total number of underwater blocks = " + String.format("%,d",uwCount.size())); - Iterable> entriesSortedByCount = - Multisets.copyHighestCountFirst(uwCount).entrySet(); - Iterator> it = entriesSortedByCount.iterator(); - while (it.hasNext()) { - Entry type = it.next(); - int value = 0; - if (Settings.blockValues.containsKey(type)) { - // Specific - value = Settings.blockValues.get(type); - } else if (Settings.blockValues.containsKey(new MaterialData(type.getElement().getItemType()))) { - // Generic - value = Settings.blockValues.get(new MaterialData(type.getElement().getItemType())); - } - if (value > 0) { - reportLines.add(type.getElement().toString() + ":" - + String.format("%,d",type.getCount()) + " blocks x " + value + " = " + (value * type.getCount())); - total += (value * type.getCount()); - } - } - reportLines.add("Subtotal = " + total); - reportLines.add("=================================="); - } - reportLines.add("Regular block count"); - reportLines.add("Total number of blocks = " + String.format("%,d",mdCount.size())); - //Iterable> entriesSortedByCount = - // Multisets.copyHighestCountFirst(mdCount).entrySet(); - Iterable> entriesSortedByCount = - mdCount.entrySet(); - Iterator> it = entriesSortedByCount.iterator(); - while (it.hasNext()) { - Entry type = it.next(); - int value = 0; - if (Settings.blockValues.containsKey(type)) { - // Specific - value = Settings.blockValues.get(type); - } else if (Settings.blockValues.containsKey(new MaterialData(type.getElement().getItemType()))) { - // Generic - value = Settings.blockValues.get(new MaterialData(type.getElement().getItemType())); - } - if (value > 0) { - reportLines.add(type.getElement().toString() + ":" - + String.format("%,d",type.getCount()) + " blocks x " + value + " = " + (value * type.getCount())); - total += (value * type.getCount()); - } - } - reportLines.add("Total = " + total); - reportLines.add("=================================="); - reportLines.add("Blocks not counted because they exceeded limits: " + String.format("%,d",ofCount.size())); - //entriesSortedByCount = Multisets.copyHighestCountFirst(ofCount).entrySet(); - entriesSortedByCount = ofCount.entrySet(); - it = entriesSortedByCount.iterator(); - while (it.hasNext()) { - Entry type = it.next(); - Integer limit = Settings.blockLimits.get(type.getElement()); - String explain = ")"; - if (limit == null) { - MaterialData generic = new MaterialData(type.getElement().getItemType()); - limit = Settings.blockLimits.get(generic); - explain = " - All types)"; - } - reportLines.add(type.getElement().toString() + ": " + String.format("%,d",type.getCount()) + " blocks (max " + limit + explain); - } - reportLines.add("=================================="); - reportLines.add("Blocks on island that are not in config.yml"); - reportLines.add("Total number = " + String.format("%,d",ncCount.size())); - //entriesSortedByCount = Multisets.copyHighestCountFirst(ncCount).entrySet(); - entriesSortedByCount = ncCount.entrySet(); - it = entriesSortedByCount.iterator(); - while (it.hasNext()) { - Entry type = it.next(); - reportLines.add(type.getElement().toString() + ": " + String.format("%,d",type.getCount()) + " blocks"); - } - reportLines.add("================================="); - } - - // Calculate how many points are required to get to the next level - long calculatePointsToNextLevel = (Settings.levelCost * (score + 1 + levelHandicap)) - ((blockCount * levelMultiplier) - (deathHandicap * Settings.deathpenalty)); - // Sometimes it will return 0, so calculate again to make sure it will display a good value - if(calculatePointsToNextLevel == 0) calculatePointsToNextLevel = (Settings.levelCost * (score + 2 + levelHandicap)) - ((blockCount * levelMultiplier) - (deathHandicap * Settings.deathpenalty)); - - final long pointsToNextLevel = calculatePointsToNextLevel; - - // Return to main thread - plugin.getServer().getScheduler().runTask(plugin, new Runnable() { - - @Override - public void run() { - // Fire the pre-level event - Island island = bSkyBlock.getIslands().getIsland(targetPlayer); - final IslandPreLevelEvent event = new IslandPreLevelEvent(targetPlayer, island, score); - event.setPointsToNextLevel(pointsToNextLevel); - plugin.getServer().getPluginManager().callEvent(event); - long oldLevel = plugin.getIslandLevel(targetPlayer); - if (!event.isCancelled()) { - if (DEBUG) - plugin.getLogger().info("DEBUG: updating player"); - - //if (oldLevel != event.getLevel()) { - // Update player and team mates - plugin.setIslandLevel(targetPlayer, event.getLevel()); - //} - if (DEBUG) - plugin.getLogger().info("DEBUG: save player, now looking at team members"); - // Update any team members too - if (bSkyBlock.getPlayers().inTeam(targetPlayer)) { - //plugin.getLogger().info("DEBUG: player is in team"); - for (UUID member : bSkyBlock.getIslands().getMembers(targetPlayer)) { - //plugin.getLogger().info("DEBUG: updating team member level too"); - if (plugin.getIslandLevel(member) != event.getLevel()) { - plugin.setIslandLevel(member, event.getLevel()); - bSkyBlock.getPlayers().save(member); - } - } - } - if (DEBUG) { - plugin.getLogger().info("DEBUG: finished team member saving"); - } - } - - // Fire the island post level calculation event - final IslandPostLevelEvent event3 = new IslandPostLevelEvent(targetPlayer, island, event.getLevel(), event.getPointsToNextLevel()); - plugin.getServer().getPluginManager().callEvent(event3); - - if(!event3.isCancelled()){ - // Check that sender still is online - if (sender != null) { - // Check if console - if (!(sender instanceof Player)) { - // Console - if (!report) { - Util.sendMessage(sender, ChatColor.GREEN + plugin.getLocale(sender).get("island.islandLevelIs") + " " + ChatColor.WHITE + plugin.getIslandLevel(targetPlayer)); - } else { - for (String line: reportLines) { - Util.sendMessage(sender, line); - } - Util.sendMessage(sender, ChatColor.GREEN + plugin.getLocale(sender).get("island.islandLevelIs") + " " + ChatColor.WHITE + plugin.getIslandLevel(targetPlayer)); - if (event.getPointsToNextLevel() >= 0) { - String toNextLevel = ChatColor.GREEN + plugin.getLocale(sender).get("island.requiredPointsToNextLevel").replace("[points]", String.valueOf(event.getPointsToNextLevel())); - toNextLevel = toNextLevel.replace("[next]", String.valueOf(plugin.getIslandLevel(targetPlayer) + 1)); - Util.sendMessage(sender, toNextLevel); - } - } - } else { - // Player - if (!report) { - // Tell offline team members the island level changed - if (plugin.getIslandLevel(targetPlayer) != oldLevel) { - //plugin.getLogger().info("DEBUG: telling offline players"); - //bSkyBlock.getMessages().tellOfflineTeam(targetPlayer, ChatColor.GREEN + bSkyBlock.myLocale(targetPlayer).islandislandLevelis + " " + ChatColor.WHITE - // + plugin.getIslandLevel(targetPlayer)); - } - if (sender instanceof Player && ((Player)sender).isOnline()) { - String message = ChatColor.GREEN + plugin.getLocale(sender).get("island.islandLevelIs") + " " + ChatColor.WHITE + plugin.getIslandLevel(targetPlayer); - if (Settings.deathpenalty != 0) { - message += " " + plugin.getLocale(sender).get("levelDeaths").replace("[number]", String.valueOf(deathHandicap)); - } - Util.sendMessage(sender, message); - //Send player how many points are required to reach next island level - if (event.getPointsToNextLevel() >= 0) { - String toNextLevel = ChatColor.GREEN + plugin.getLocale(sender).get("island.requiredPointsToNextLevel").replace("[points]", String.valueOf(event.getPointsToNextLevel())); - toNextLevel = toNextLevel.replace("[next]", String.valueOf(plugin.getIslandLevel(targetPlayer) + 1)); - Util.sendMessage(sender, toNextLevel); - } - } - } else { - if (((Player)sender).isOnline()) { - for (String line: reportLines) { - Util.sendMessage(sender, line); - } - } - Util.sendMessage(sender, ChatColor.GREEN + plugin.getLocale(sender).get("island.islandLevelIs") + " " + ChatColor.WHITE + plugin.getIslandLevel(targetPlayer)); - if (event.getPointsToNextLevel() >= 0) { - String toNextLevel = ChatColor.GREEN + plugin.getLocale(sender).get("island.requiredPointsToNextLevel").replace("[points]", String.valueOf(event.getPointsToNextLevel())); - toNextLevel = toNextLevel.replace("[next]", String.valueOf(plugin.getIslandLevel(targetPlayer) + 1)); - Util.sendMessage(sender, toNextLevel); - } - } - } - } - } - }}); - }}); - } - } - -} diff --git a/src/bskyblock/addin/level/LevelPlugin.java b/src/bskyblock/addin/level/LevelPlugin.java index 022b90f..9bb3ab3 100644 --- a/src/bskyblock/addin/level/LevelPlugin.java +++ b/src/bskyblock/addin/level/LevelPlugin.java @@ -2,11 +2,7 @@ package bskyblock.addin.level; import java.util.logging.Logger; -import org.bukkit.command.CommandSender; - import us.tastybento.bskyblock.BSkyBlock; -import us.tastybento.bskyblock.config.BSBLocale; -import us.tastybento.bskyblock.util.Util; /** * Makes code look nicer @@ -25,12 +21,5 @@ public abstract class LevelPlugin { public final Logger getLogger() { return plugin.getLogger(); } - - public final void sendMessage(CommandSender sender, String message) { - Util.sendMessage(sender, message); - } - - public final BSBLocale getLocale(CommandSender sender) { - return plugin.getLocale(sender); - } + } diff --git a/src/bskyblock/addin/level/LevelPresenter.java b/src/bskyblock/addin/level/LevelPresenter.java new file mode 100644 index 0000000..0ee0481 --- /dev/null +++ b/src/bskyblock/addin/level/LevelPresenter.java @@ -0,0 +1,98 @@ +package bskyblock.addin.level; + +import java.util.Calendar; +import java.util.HashMap; +import java.util.UUID; + +import org.bukkit.ChatColor; + +import us.tastybento.bskyblock.api.commands.User; +import us.tastybento.bskyblock.config.Settings; + +public class LevelPresenter extends LevelPlugin { + + private int levelWait; + // Level calc cool down + private HashMap levelWaitTime = new HashMap(); + + public LevelPresenter(Level plugin) { + super(plugin); + } + + /** + * Calculates the island level + * + * @param sender + * - Player object of player who is asking + * @param targetPlayer + * - UUID of the player's island that is being requested + * @return - true if successful. + */ + public boolean calculateIslandLevel(final User sender, final UUID targetPlayer) { + return calculateIslandLevel(sender, targetPlayer, false); + } + + /** + * Calculates the island level + * @param sender - asker of the level info + * @param targetPlayer + * @param report - if true, a detailed report will be provided + * @return - false if this is cannot be done + */ + public boolean calculateIslandLevel(final User sender, final UUID targetPlayer, boolean report) { + // Check if sender has island + if (!bSkyBlock.getIslands().hasIsland(targetPlayer)) { + sender.sendLegacyMessage("Target does not have an island"); + return false; + } + // Player asking for their own island calc + if (!sender.isPlayer() || sender.getUniqueId().equals(targetPlayer) || sender.isOp() || sender.hasPermission(Settings.PERMPREFIX + "mod.info")) { + // Newer better system - uses chunks + if (!onLevelWaitTime(sender) || levelWait <= 0 || sender.isOp() || sender.hasPermission(Settings.PERMPREFIX + "mod.info")) { + sender.sendLegacyMessage(ChatColor.GREEN + "Calculating level, please wait..."); + setLevelWaitTime(sender); + new ChunkScanner(plugin, bSkyBlock.getIslands().getIsland(targetPlayer), sender); + } else { + sender.sendLegacyMessage( ChatColor.YELLOW + String.valueOf(getLevelWaitTime(sender))); + } + + } else { + // Asking for the level of another player + sender.sendMessage("island.islandLevelIs","[level]", String.valueOf(plugin.getIslandLevel(targetPlayer))); + } + return true; + } + + /** + * Sets cool down for the level command + * + * @param player + */ + private void setLevelWaitTime(final User player) { + levelWaitTime.put(player.getUniqueId(), Long.valueOf(Calendar.getInstance().getTimeInMillis() + levelWait * 1000)); + } + + private boolean onLevelWaitTime(final User sender) { + if (levelWaitTime.containsKey(sender.getUniqueId())) { + if (levelWaitTime.get(sender.getUniqueId()).longValue() > Calendar.getInstance().getTimeInMillis()) { + return true; + } + + return false; + } + + return false; + } + + private long getLevelWaitTime(final User sender) { + if (levelWaitTime.containsKey(sender.getUniqueId())) { + if (levelWaitTime.get(sender.getUniqueId()).longValue() > Calendar.getInstance().getTimeInMillis()) { + return (levelWaitTime.get(sender.getUniqueId()).longValue() - Calendar.getInstance().getTimeInMillis()) / 1000; + } + + return 0L; + } + + return 0L; + } +} diff --git a/src/bskyblock/addin/level/TopTen.java b/src/bskyblock/addin/level/TopTen.java index 6471bcd..f958a30 100644 --- a/src/bskyblock/addin/level/TopTen.java +++ b/src/bskyblock/addin/level/TopTen.java @@ -45,6 +45,7 @@ import bskyblock.addin.level.database.object.Levels; import bskyblock.addin.level.database.object.TopTenList; import bskyblock.addin.level.event.TopTenClick; import us.tastybento.bskyblock.BSkyBlock; +import us.tastybento.bskyblock.api.commands.User; import us.tastybento.bskyblock.config.Settings; import us.tastybento.bskyblock.database.BSBDatabase; import us.tastybento.bskyblock.database.managers.AbstractDatabaseHandler; @@ -141,7 +142,7 @@ public class TopTen implements Listener { if (topTenList == null) create(); // Create the top ten GUI if it does not exist if (gui == null) { - gui = Bukkit.createInventory(null, GUISIZE, plugin.getLocale(player.getUniqueId()).get("topten.guiTitle")); + gui = Bukkit.createInventory(null, GUISIZE, "topten.guiTitle"); if (DEBUG) plugin.getLogger().info("DEBUG: creating GUI for the first time"); } @@ -193,10 +194,10 @@ public class TopTen implements Listener { SkullMeta meta = (SkullMeta) playerSkull.getItemMeta(); //meta.setOwningPlayer(plugin.getServer().getOfflinePlayer(player)); meta.setOwner(playerName); - meta.setDisplayName((plugin.getLocale(player).get("topten.guiHeading").replace("[name]", BSkyBlock.getPlugin().getIslands().getIslandName(player))).replace("[rank]", String.valueOf(rank))); + meta.setDisplayName(("topten.guiHeading".replace("[name]", BSkyBlock.getPlugin().getIslands().getIslandName(player))).replace("[rank]", String.valueOf(rank))); //meta.setDisplayName(ChatColor.YELLOW + "" + ChatColor.BOLD + " " + ChatColor.YELLOW + "Island: " + ChatColor.GOLD + ChatColor.UNDERLINE + plugin.getGrid().getIslandName(player) + ChatColor.GRAY + " (#" + rank + ")"); List lore = new ArrayList(); - lore.add(ChatColor.YELLOW + plugin.getLocale(player).get("topten.islandLevel").replace("[level]", String.valueOf(long1))); + lore.add(ChatColor.YELLOW + "topten.islandLevel".replace("[level]", String.valueOf(long1))); if (BSkyBlock.getPlugin().getPlayers().inTeam(player)) { List memberList = new ArrayList<>(); for (UUID members : BSkyBlock.getPlugin().getIslands().getMembers(player)) { @@ -239,7 +240,7 @@ public class TopTen implements Listener { } // The player that clicked the item Player player = (Player) event.getWhoClicked(); - if (!inventory.getTitle().equals(plugin.getLocale(player).get("topten.guiTitle"))) { + if (!inventory.getTitle().equals("topten.guiTitle")) { return; } event.setCancelled(true); diff --git a/src/bskyblock/addin/level/commands/AdminLevel.java b/src/bskyblock/addin/level/commands/AdminLevel.java new file mode 100644 index 0000000..689480e --- /dev/null +++ b/src/bskyblock/addin/level/commands/AdminLevel.java @@ -0,0 +1,44 @@ +package bskyblock.addin.level.commands; + +import java.util.List; +import java.util.UUID; + +import bskyblock.addin.level.Level; +import us.tastybento.bskyblock.api.commands.CompositeCommand; +import us.tastybento.bskyblock.api.commands.User; +import us.tastybento.bskyblock.config.Settings; + +public class AdminLevel extends CompositeCommand { + + private final Level levelPlugin; + + public AdminLevel(Level levelPlugin, CompositeCommand parent) { + super(parent, "level"); + this.levelPlugin = levelPlugin; + this.setPermission(Settings.PERMPREFIX + "admin.level"); + this.setOnlyPlayer(false); + this.setUsage("admin.level.usage"); + } + + @Override + public boolean execute(User user, List args) { + if (!args.isEmpty()) { + // Asking for another player's level? + // Convert name to a UUID + final UUID playerUUID = getPlugin().getPlayers().getUUID(args.get(0), true); + //getLogger().info("DEBUG: console player info UUID = " + playerUUID); + if (playerUUID == null) { + user.sendMessage("error.UnknownPlayer"); + return true; + } else { + if (user.isPlayer()) { + levelPlugin.calculateIslandLevel(user, playerUUID, false); + } else { + levelPlugin.calculateIslandLevel(user, playerUUID, true); + } + } + } + return true; + } + +} diff --git a/src/bskyblock/addin/level/commands/AdminTop.java b/src/bskyblock/addin/level/commands/AdminTop.java new file mode 100644 index 0000000..d81c647 --- /dev/null +++ b/src/bskyblock/addin/level/commands/AdminTop.java @@ -0,0 +1,39 @@ +package bskyblock.addin.level.commands; + +import java.util.List; +import java.util.Map.Entry; +import java.util.UUID; + +import bskyblock.addin.level.Level; +import us.tastybento.bskyblock.BSkyBlock; +import us.tastybento.bskyblock.api.commands.CompositeCommand; +import us.tastybento.bskyblock.api.commands.User; +import us.tastybento.bskyblock.config.Settings; + +public class AdminTop extends CompositeCommand { + + private final Level levelPlugin; + + public AdminTop(Level levelPlugin, CompositeCommand parent) { + super(parent, "top", "topten"); + this.levelPlugin = levelPlugin; + this.setPermission(Settings.PERMPREFIX + "admin.top"); + this.setOnlyPlayer(false); + this.setUsage("admin.top.usage"); + } + + @Override + public boolean execute(User user, List args) { + int rank = 0; + for (Entry topTen : levelPlugin.getTopTen().getTopTenList().getTopTen().entrySet()) { + UUID player = topTen.getKey(); + rank++; + String item = String.valueOf(rank) + ":" + BSkyBlock.getPlugin().getIslands().getIslandName(player) + " " + + "topten.islandLevel" + String.valueOf(topTen.getValue()); + user.sendLegacyMessage(item); + } + + return true; + } + +} diff --git a/src/bskyblock/addin/level/commands/Commands.java b/src/bskyblock/addin/level/commands/Commands.java deleted file mode 100644 index 43a7b02..0000000 --- a/src/bskyblock/addin/level/commands/Commands.java +++ /dev/null @@ -1,190 +0,0 @@ -package bskyblock.addin.level.commands; - -import java.util.Map.Entry; -import java.util.Set; -import java.util.UUID; - -import org.bukkit.ChatColor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; - -import bskyblock.addin.level.CalculateLevel; -import bskyblock.addin.level.Level; -import us.tastybento.bskyblock.BSkyBlock; -import us.tastybento.bskyblock.api.commands.ArgumentHandler; -import us.tastybento.bskyblock.api.commands.CanUseResp; -import us.tastybento.bskyblock.config.Settings; -import us.tastybento.bskyblock.util.Util; -import us.tastybento.bskyblock.util.VaultHelper; - -public class Commands extends CalculateLevel { - - public Commands(Level plugin) { - super(plugin); - setupCommands(); - } - - private void setupCommands() { - // island level command - bSkyBlock.addSubCommand(new ArgumentHandler("island") { - - @Override - public CanUseResp canUse(CommandSender sender) { - return new CanUseResp(true); - } - - @Override - public void execute(CommandSender sender, String[] args) { - //getLogger().info("DEBUG: " + args); - if (args.length > 0) { - // Asking for another player's level? - // Convert name to a UUID - final UUID playerUUID = bSkyBlock.getPlayers().getUUID(args[0], true); - //getLogger().info("DEBUG: console player info UUID = " + playerUUID); - if (playerUUID == null) { - sendMessage(sender, ChatColor.RED + getLocale(sender).get("error.UnknownPlayer")); - return; - } else { - sendMessage(sender, ChatColor.GREEN + "Level is " + plugin.getIslandLevel(playerUUID)); - return; - } - } - if (sender instanceof Player) { - Player player = (Player)sender; - UUID playerUUID = player.getUniqueId(); - - if (VaultHelper.hasPerm(player, Settings.PERMPREFIX + "island.info")) { - if (!bSkyBlock.getPlayers().inTeam(playerUUID) && !bSkyBlock.getPlayers().hasIsland(playerUUID)) { - Util.sendMessage(player, ChatColor.RED + bSkyBlock.getLocale(sender).get("errors.no-island")); - return; - } else { - calculateIslandLevel(player, playerUUID); - return; - } - } else { - Util.sendMessage(player, ChatColor.RED + bSkyBlock.getLocale(sender).get("errors.no-permission")); - return; - } - } - } - - @Override - public Set tabComplete(CommandSender sender, String[] args) { - return null; - } - - @Override - public String[] usage(CommandSender sender) { - return new String[]{"[player]", "See your island's level or someone else's"}; - } - }.alias("level")); - - // island top command - bSkyBlock.addSubCommand(new ArgumentHandler("island") { - - @Override - public CanUseResp canUse(CommandSender sender) { - if (sender instanceof Player) { - VaultHelper.hasPerm((Player)sender, Settings.PERMPREFIX + "island.topten"); - return new CanUseResp(true); - } - return new CanUseResp(false); - } - - @Override - public void execute(CommandSender sender, String[] args) { - plugin.getTopTen().getGUI((Player)sender); - return; - } - - @Override - public Set tabComplete(CommandSender sender, String[] args) { - return null; - } - - @Override - public String[] usage(CommandSender sender) { - return new String[]{"", "View top ten"}; - } - }.alias("top")); - - // Admin level command - bSkyBlock.addSubCommand(new ArgumentHandler("bsadmin") { - - @Override - public CanUseResp canUse(CommandSender sender) { - return new CanUseResp(true); - } - - @Override - public void execute(CommandSender sender, String[] args) { - if (args.length == 0) { - - } else { - // Convert name to a UUID - final UUID playerUUID = bSkyBlock.getPlayers().getUUID(args[0], true); - //plugin.getLogger().info("DEBUG: console player info UUID = " + playerUUID); - if (playerUUID == null) { - Util.sendMessage(sender, ChatColor.RED + plugin.getLocale(sender).get("error.UnknownPlayer")); - return; - } else { - if (sender instanceof Player) { - calculateIslandLevel(sender, playerUUID, false); - } else { - calculateIslandLevel(sender, playerUUID, true); - } - return; - } - } - } - - @Override - public Set tabComplete(CommandSender sender, String[] args) { - return null; - } - - @Override - public String[] usage(CommandSender sender) { - return new String[]{"[player]", "Calculate a player's island's level"}; - } - }.alias("level")); - - // admin top command - bSkyBlock.addSubCommand(new ArgumentHandler("bsadmin") { - - @Override - public CanUseResp canUse(CommandSender sender) { - if (sender instanceof Player) { - VaultHelper.hasPerm((Player)sender, Settings.PERMPREFIX + "admin.topten"); - return new CanUseResp(true); - } - return new CanUseResp(true); - } - - @Override - public void execute(CommandSender sender, String[] args) { - int rank = 0; - for (Entry topTen : plugin.getTopTen().getTopTenList().getTopTen().entrySet()) { - UUID player = topTen.getKey(); - rank++; - String item = String.valueOf(rank) + ":" + BSkyBlock.getPlugin().getIslands().getIslandName(player) + " " - + plugin.getLocale(sender).get("topten.islandLevel").replace("[level]", String.valueOf(topTen.getValue())); - Util.sendMessage(sender, item); - } - return; - } - - @Override - public Set tabComplete(CommandSender sender, String[] args) { - return null; - } - - @Override - public String[] usage(CommandSender sender) { - return new String[]{"", "List top ten"}; - } - }.alias("top")); - } - - -} diff --git a/src/bskyblock/addin/level/commands/IslandLevel.java b/src/bskyblock/addin/level/commands/IslandLevel.java new file mode 100644 index 0000000..dbcaa04 --- /dev/null +++ b/src/bskyblock/addin/level/commands/IslandLevel.java @@ -0,0 +1,48 @@ +package bskyblock.addin.level.commands; + +import java.util.List; +import java.util.UUID; + +import bskyblock.addin.level.Level; +import us.tastybento.bskyblock.api.commands.CompositeCommand; +import us.tastybento.bskyblock.api.commands.User; +import us.tastybento.bskyblock.config.Settings; + +public class IslandLevel extends CompositeCommand { + + private final Level levelPlugin; + + public IslandLevel(Level levelPlugin, CompositeCommand parent) { + super(parent, "level"); + this.levelPlugin = levelPlugin; + this.setPermission(Settings.PERMPREFIX + "island.level"); + this.setUsage("island.level.usage"); + this.setOnlyPlayer(true); + } + + @Override + public boolean execute(User user, List args) { + if (!args.isEmpty()) { + // Asking for another player's level? + // Convert name to a UUID + final UUID playerUUID = getPlugin().getPlayers().getUUID(args.get(0), true); + //getLogger().info("DEBUG: console player info UUID = " + playerUUID); + if (playerUUID == null) { + user.sendMessage("error.UnknownPlayer"); + return true; + } else if (user.getUniqueId().equals(playerUUID) ) { + // Self level request + levelPlugin.calculateIslandLevel(user, user.getUniqueId(), false); + } else { + user.sendMessage("addon.level.level-is", "[level]", String.valueOf(levelPlugin.getIslandLevel(playerUUID))); + user.sendLegacyMessage("Level = " + String.valueOf(levelPlugin.getIslandLevel(playerUUID))); + return true; + } + } else { + // Self level request + levelPlugin.calculateIslandLevel(user, user.getUniqueId(), false); + } + return false; + } + +} diff --git a/src/bskyblock/addin/level/commands/IslandTop.java b/src/bskyblock/addin/level/commands/IslandTop.java new file mode 100644 index 0000000..4ca37b9 --- /dev/null +++ b/src/bskyblock/addin/level/commands/IslandTop.java @@ -0,0 +1,27 @@ +package bskyblock.addin.level.commands; + +import java.util.List; + +import bskyblock.addin.level.Level; +import us.tastybento.bskyblock.api.commands.CompositeCommand; +import us.tastybento.bskyblock.api.commands.User; +import us.tastybento.bskyblock.config.Settings; + +public class IslandTop extends CompositeCommand { + + private final Level plugin; + + public IslandTop(Level plugin, CompositeCommand parent) { + super(parent, "top", "topten"); + this.plugin = plugin; + this.setPermission(Settings.PERMPREFIX + "island.top"); + this.setUsage("island.top.usage"); + } + + @Override + public boolean execute(User user, List list) { + plugin.getTopTen().getGUI(user.getPlayer()); + return false; + } + +} diff --git a/src/bskyblock/addin/level/config/LocaleManager.java b/src/bskyblock/addin/level/config/LocaleManager.java deleted file mode 100644 index c148e7b..0000000 --- a/src/bskyblock/addin/level/config/LocaleManager.java +++ /dev/null @@ -1,28 +0,0 @@ -package bskyblock.addin.level.config; - -import java.util.UUID; - -import bskyblock.addin.level.Level; -import us.tastybento.bskyblock.BSkyBlock; -import us.tastybento.bskyblock.config.AbstractLocaleManager; -import us.tastybento.bskyblock.config.BSBLocale; -import us.tastybento.bskyblock.config.Settings; - -public class LocaleManager extends AbstractLocaleManager { - - public LocaleManager(Level plugin) { - super(plugin); - } - - @Override - public BSBLocale getLocale(UUID player) { - //getLogger().info("DEBUG: " + player); - //getLogger().info("DEBUG: " + getPlayers() == null ? "Players is null":"Players in not null"); - //getLogger().info("DEBUG: " + getPlayers().getPlayer(player)); - //getLogger().info("DEBUG: " + getPlayers().getPlayer(player).getLocale()); - String locale = BSkyBlock.getPlugin().getPlayers().getPlayer(player).getLocale(); - if(locale.isEmpty() || !getLocales().containsKey(locale)) return getLocales().get(Settings.defaultLanguage); - - return getLocales().get(locale); - } -} diff --git a/src/bskyblock/addin/level/event/IslandPostLevelEvent.java b/src/bskyblock/addin/level/event/IslandPostLevelEvent.java index 6182cdb..478bd5b 100644 --- a/src/bskyblock/addin/level/event/IslandPostLevelEvent.java +++ b/src/bskyblock/addin/level/event/IslandPostLevelEvent.java @@ -2,7 +2,7 @@ package bskyblock.addin.level.event; import java.util.UUID; -import us.tastybento.bskyblock.api.events.IslandEvent; +import us.tastybento.bskyblock.api.events.IslandBaseEvent; import us.tastybento.bskyblock.database.objects.Island; /** @@ -12,7 +12,7 @@ import us.tastybento.bskyblock.database.objects.Island; * * @author Poslovitch, tastybento */ -public class IslandPostLevelEvent extends IslandEvent { +public class IslandPostLevelEvent extends IslandBaseEvent { private long level; private long pointsToNextLevel; diff --git a/src/bskyblock/addin/level/event/IslandPreLevelEvent.java b/src/bskyblock/addin/level/event/IslandPreLevelEvent.java index c818cf9..f3d8bd0 100644 --- a/src/bskyblock/addin/level/event/IslandPreLevelEvent.java +++ b/src/bskyblock/addin/level/event/IslandPreLevelEvent.java @@ -2,10 +2,10 @@ package bskyblock.addin.level.event; import java.util.UUID; -import us.tastybento.bskyblock.api.events.IslandEvent; +import us.tastybento.bskyblock.api.events.IslandBaseEvent; import us.tastybento.bskyblock.database.objects.Island; -public class IslandPreLevelEvent extends IslandEvent { +public class IslandPreLevelEvent extends IslandBaseEvent { private UUID targetPlayer; private long level;