diff --git a/src/main/java/woolbattle/woolbattle/Cache.java b/src/main/java/woolbattle/woolbattle/Cache.java index 9a39006..1b99317 100644 --- a/src/main/java/woolbattle/woolbattle/Cache.java +++ b/src/main/java/woolbattle/woolbattle/Cache.java @@ -14,6 +14,7 @@ public class Cache { /** * A Class that contains a few HashMaps with setters and getters to cache different things easily. + * * @author SimsumMC */ @@ -33,28 +34,28 @@ public class Cache { private static HashMap> activePerkSlots = new HashMap<>(); - private static HashMap> killStreaks = new HashMap>(){{ + private static HashMap> killStreaks = new HashMap>() {{ put("Blue", new HashMap<>()); put("Red", new HashMap<>()); put("Green", new HashMap<>()); put("Yellow", new HashMap<>()); }}; - private static HashMap> teamMembers = new HashMap>(){{ + private static HashMap> teamMembers = new HashMap>() {{ put("Blue", new ArrayList<>()); put("Red", new ArrayList<>()); put("Green", new ArrayList<>()); put("Yellow", new ArrayList<>()); }}; - private static HashMap teamLives = new HashMap(){{ + private static HashMap teamLives = new HashMap() {{ put("Blue", 0); put("Red", 0); put("Green", 0); put("Yellow", 0); }}; - private static HashMap> lifeVoting = new HashMap>(){{ + private static HashMap> lifeVoting = new HashMap>() {{ put(5, new ArrayList<>()); put(10, new ArrayList<>()); put(15, new ArrayList<>()); @@ -62,46 +63,111 @@ public class Cache { private static HashMap> playerStats = new HashMap<>(); - public static HashMap getActivePerks() {return activePerks;} - public static void setActivePerks(HashMap activePerks) {Cache.activePerks = activePerks;} + public static HashMap getActivePerks() { + return activePerks; + } + + public static void setActivePerks(HashMap activePerks) { + Cache.activePerks = activePerks; + } + + public static HashMap> getPassivePerks() { + return passivePerks; + } - public static HashMap> getPassivePerks() {return passivePerks;} - public static void setPassivePerks(HashMap> passivePerks) {Cache.passivePerks = passivePerks;} + public static void setPassivePerks(HashMap> passivePerks) { + Cache.passivePerks = passivePerks; + } + + public static HashMap getPlayerDuels() { + return playerDuels; + } + + public static void setPlayerDuels(HashMap playerDuels) { + Cache.playerDuels = playerDuels; + } - public static HashMap getPlayerDuels() {return playerDuels;} - public static void setPlayerDuels(HashMap playerDuels) {Cache.playerDuels = playerDuels;} + public static HashMap getLastDamage() { + return lastDamage; + } - public static HashMap getLastDamage() {return lastDamage;} - public static void setLastDamage(HashMap lastDamage) {Cache.lastDamage = lastDamage;} + public static void setLastDamage(HashMap lastDamage) { + Cache.lastDamage = lastDamage; + } - public static HashMap getSpawnProtection() {return spawnProtection;} - public static void setSpawnProtection(HashMap spawnProtection) {Cache.spawnProtection = spawnProtection;} + public static HashMap getSpawnProtection() { + return spawnProtection; + } - public static HashMap> getEnderPearls() {return enderPearls;} - public static void setEnderPearls(HashMap> enderPearls) {Cache.enderPearls = enderPearls;} + public static void setSpawnProtection(HashMap spawnProtection) { + Cache.spawnProtection = spawnProtection; + } - public static HashMap>> getJumpPlatformBlocks() {return jumpPlatformBlocks;} - public static void setJumpPlatformBlocks(HashMap>> jumpPlatformBlocks) {Cache.jumpPlatformBlocks = jumpPlatformBlocks;} + public static HashMap> getEnderPearls() { + return enderPearls; + } - public static HashMap> getKillStreaks() {return killStreaks;} - public static void setKillStreaks(HashMap> killStreaks) {Cache.killStreaks = killStreaks;} + public static void setEnderPearls(HashMap> enderPearls) { + Cache.enderPearls = enderPearls; + } - public static HashMap> getTeamMembers() {return teamMembers;} - public static void setTeamMembers(HashMap> teamMembers) {Cache.teamMembers = teamMembers;} + public static HashMap>> getJumpPlatformBlocks() { + return jumpPlatformBlocks; + } - public static HashMap getTeamLives() {return teamLives;} - public static void setTeamLives(HashMap teamLives) {Cache.teamLives = teamLives;} + public static void setJumpPlatformBlocks(HashMap>> jumpPlatformBlocks) { + Cache.jumpPlatformBlocks = jumpPlatformBlocks; + } - public static HashMap> getLifeVoting() {return lifeVoting;} - public static void setLifeVoting(HashMap> lifeVoting) {Cache.lifeVoting = lifeVoting;} + public static HashMap> getKillStreaks() { + return killStreaks; + } - public static HashMap> getPlayerStats() {return playerStats;} - public static void setPlayerStats(HashMap> playerStats) {Cache.playerStats = playerStats;} + public static void setKillStreaks(HashMap> killStreaks) { + Cache.killStreaks = killStreaks; + } - public static HashMap> getActivePerkSlots() {return activePerkSlots;} - public static void setActivePerkSlots(HashMap> activePerkSlots) {Cache.activePerkSlots = activePerkSlots;} + public static HashMap> getTeamMembers() { + return teamMembers; + } + + public static void setTeamMembers(HashMap> teamMembers) { + Cache.teamMembers = teamMembers; + } + + public static HashMap getTeamLives() { + return teamLives; + } + + public static void setTeamLives(HashMap teamLives) { + Cache.teamLives = teamLives; + } + + public static HashMap> getLifeVoting() { + return lifeVoting; + } + + public static void setLifeVoting(HashMap> lifeVoting) { + Cache.lifeVoting = lifeVoting; + } + + public static HashMap> getPlayerStats() { + return playerStats; + } + + public static void setPlayerStats(HashMap> playerStats) { + Cache.playerStats = playerStats; + } + + public static HashMap> getActivePerkSlots() { + return activePerkSlots; + } + + public static void setActivePerkSlots(HashMap> activePerkSlots) { + Cache.activePerkSlots = activePerkSlots; + } - public static void clear(){ + public static void clear() { playerDuels = new HashMap<>(); lastDamage = new HashMap<>(); @@ -116,28 +182,28 @@ public static void clear(){ activePerkSlots = new HashMap<>(); - killStreaks = new HashMap>(){{ + killStreaks = new HashMap>() {{ put("Blue", new HashMap<>()); put("Red", new HashMap<>()); put("Green", new HashMap<>()); put("Yellow", new HashMap<>()); }}; - teamMembers = new HashMap>(){{ + teamMembers = new HashMap>() {{ put("Blue", new ArrayList<>()); put("Red", new ArrayList<>()); put("Green", new ArrayList<>()); put("Yellow", new ArrayList<>()); }}; - teamLives = new HashMap(){{ + teamLives = new HashMap() {{ put("Blue", 0); put("Red", 0); put("Green", 0); put("Yellow", 0); }}; - lifeVoting = new HashMap>(){{ + lifeVoting = new HashMap>() {{ put(5, new ArrayList<>()); put(10, new ArrayList<>()); put(15, new ArrayList<>()); diff --git a/src/main/java/woolbattle/woolbattle/Config.java b/src/main/java/woolbattle/woolbattle/Config.java index 5e71226..d7c4a61 100644 --- a/src/main/java/woolbattle/woolbattle/Config.java +++ b/src/main/java/woolbattle/woolbattle/Config.java @@ -19,6 +19,7 @@ public class Config { /** * A Config class that contains all default values from the config.json as variables. + * * @author SimsumMC & Servaturus */ @@ -95,10 +96,11 @@ public class Config { /** * Returns the value of the given key from the config.json. + * * @param key the JSON key as a String
* @author SimsumMC & Servaturus */ - public static Object getValue(String key) { + public static Object getValue(String key) { if (!fileExisting) { // make sure that the directory exists @@ -146,5 +148,5 @@ public static Object getValue(String key) { e.printStackTrace(); } return jsonObject.get(key); - } + } } \ No newline at end of file diff --git a/src/main/java/woolbattle/woolbattle/Main.java b/src/main/java/woolbattle/woolbattle/Main.java index 875d80c..050ee80 100644 --- a/src/main/java/woolbattle/woolbattle/Main.java +++ b/src/main/java/woolbattle/woolbattle/Main.java @@ -16,14 +16,15 @@ import woolbattle.woolbattle.lobby.LobbySystem; import woolbattle.woolbattle.lobby.StartGameCommand; import woolbattle.woolbattle.lobby.StopGameCommand; -import woolbattle.woolbattle.maprestaurationsystem.MapCommand; +import woolbattle.woolbattle.map.MapCommand; import woolbattle.woolbattle.perks.AllActivePerks; import woolbattle.woolbattle.perks.AllPassivePerks; import woolbattle.woolbattle.stats.StatsCommand; import woolbattle.woolbattle.team.TeamSystem; -import woolbattle.woolbattle.woolsystem.BlockBreakingSystem; -import woolbattle.woolbattle.woolsystem.BlockRegistrationCommand; -import woolbattle.woolbattle.woolsystem.MapBlocksCommand; +import woolbattle.woolbattle.map.BlockBreakingSystem; +import woolbattle.woolbattle.map.BlockRegistrationCommand; +import woolbattle.woolbattle.map.Listener; +import woolbattle.woolbattle.map.MapBlocksCommand; import java.util.ArrayList; import java.util.HashMap; @@ -80,13 +81,12 @@ public void onEnable() { BlockBreakingSystem.setCollectBrokenBlocks(false); BlockBreakingSystem.fetchMapBlocks(); - for (Player player : Bukkit.getOnlinePlayers()) - { + for (Player player : Bukkit.getOnlinePlayers()) { player.setAllowFlight(true); MongoCollection collection = db.getCollection("playerAchievements"); Document foundDocument = collection.find(eq("_id", player.getUniqueId().toString())).first(); - if(foundDocument == null) { + if (foundDocument == null) { HashMap playerData = new HashMap() {{ put("_id", player.getUniqueId().toString()); put("achievements", new ArrayList()); @@ -102,7 +102,7 @@ public void onDisable() { // Plugin shutdown logic } - public static Main getInstance(){ + public static Main getInstance() { return instance; } diff --git a/src/main/java/woolbattle/woolbattle/achievements/AchievementSystem.java b/src/main/java/woolbattle/woolbattle/achievements/AchievementSystem.java index 84af43b..7fb79ab 100644 --- a/src/main/java/woolbattle/woolbattle/achievements/AchievementSystem.java +++ b/src/main/java/woolbattle/woolbattle/achievements/AchievementSystem.java @@ -13,6 +13,7 @@ import woolbattle.woolbattle.Config; import woolbattle.woolbattle.Main; import woolbattle.woolbattle.lobby.LobbySystem; + import java.util.ArrayList; import java.util.HashMap; @@ -23,18 +24,18 @@ public class AchievementSystem implements Listener { /** * A method which, upon being called, checks if the player is qualified to be given * the Strategist achievement. + * * @param player - The player which the achievement is to be assigned to * @author Beelzebub */ public static void giveFullwool(Player player) { MongoDatabase db = Main.getMongoDatabase(); MongoCollection collection = db.getCollection("playerAchievements"); - Document query = new Document().append("_id", player.getUniqueId().toString()); + Document query = new Document().append("_id", player.getUniqueId().toString()); ArrayList arrayList = (ArrayList) collection.find(eq("_id", player.getUniqueId().toString())).first().get("achievements"); if (arrayList.contains("fullwool")) { return; - } - else if (player.getInventory().contains(Material.WOOL, Config.maxStacks * 64)) { + } else if (player.getInventory().contains(Material.WOOL, Config.maxStacks * 64)) { player.sendMessage(ChatColor.GREEN + "You just received the 'Strategist' Achievement!"); Bson updates = Updates.push("achievements", "fullwool"); @@ -45,22 +46,21 @@ else if (player.getInventory().contains(Material.WOOL, Config.maxStacks * 64)) { /** * A method which, upon being called, gives the Player the Dominator achievement * (No separate check needed as method is only called when the player is qualified) + * * @param player - The player which the achievement is to be assigned to * @author Beelzebub */ public static void giveKillstreak5(Player player) { MongoDatabase db = Main.getMongoDatabase(); MongoCollection collection = db.getCollection("playerAchievements"); - Document query = new Document().append("_id", player.getUniqueId().toString()); + Document query = new Document().append("_id", player.getUniqueId().toString()); ArrayList arrayList = (ArrayList) collection.find(eq("_id", player.getUniqueId().toString())).first().get("achievements"); if (!LobbySystem.gameStarted) { return; - } - else if (arrayList.contains("killstreak5")){ + } else if (arrayList.contains("killstreak5")) { return; - } - else { + } else { player.sendMessage(ChatColor.GREEN + "You just received the 'Dominator' Achievement!"); arrayList.add("fullwool"); Bson updates = (Bson) arrayList; @@ -92,8 +92,8 @@ else if (Cache.getKillStreaks().get(winner).get(player) == 0) { } */ // } - /** (UNFINISHED) - * A method which, upon being called, gives the Player the British Way achievement + /** (UNFINISHED) + * A method which, upon being called, gives the Player the British Way achievement * (No separate check needed as method is only called when the player is qualified) * @param winner - The team which has won the game * @author Beelzebub @@ -124,26 +124,27 @@ public static void closeCall (String winner){ } } */ - /** - * A method which puts players into the temporary achievement Hashmap upon them joining, - * provided they are not yet in said Hashmap - * @param event - The PlayerJoinEvent - * @author Beelzebub - */ - @EventHandler - public void onPlayerJoin (PlayerJoinEvent event){ - Player player = event.getPlayer(); - MongoDatabase db = Main.getMongoDatabase(); - MongoCollection collection = db.getCollection("playerAchievements"); + /** + * A method which puts players into the temporary achievement Hashmap upon them joining, + * provided they are not yet in said Hashmap + * + * @param event - The PlayerJoinEvent + * @author Beelzebub + */ + @EventHandler + public void onPlayerJoin(PlayerJoinEvent event) { + Player player = event.getPlayer(); + MongoDatabase db = Main.getMongoDatabase(); + MongoCollection collection = db.getCollection("playerAchievements"); - Document foundDocument = collection.find(eq("_id", player.getUniqueId().toString())).first(); - if (foundDocument == null) { - HashMap playerData = new HashMap() {{ - put("_id", player.getUniqueId().toString()); - put("achievements", new ArrayList()); - }}; - Document document = new Document(playerData); - collection.insertOne(document); - } - } + Document foundDocument = collection.find(eq("_id", player.getUniqueId().toString())).first(); + if (foundDocument == null) { + HashMap playerData = new HashMap() {{ + put("_id", player.getUniqueId().toString()); + put("achievements", new ArrayList()); + }}; + Document document = new Document(playerData); + collection.insertOne(document); + } + } } \ No newline at end of file diff --git a/src/main/java/woolbattle/woolbattle/achievements/AchievementUI.java b/src/main/java/woolbattle/woolbattle/achievements/AchievementUI.java index 206eb01..d2d8cff 100644 --- a/src/main/java/woolbattle/woolbattle/achievements/AchievementUI.java +++ b/src/main/java/woolbattle/woolbattle/achievements/AchievementUI.java @@ -18,7 +18,9 @@ public class AchievementUI { - /** A function which creates the GUI which contains the Achievements. + /** + * A function which creates the GUI which contains the Achievements. + * * @param player - A handle to the player object which is passed by a function in LobbySystem. The parameter is the player which has clicked the item in order to open the GUI. * @author Beelzebub */ @@ -39,7 +41,9 @@ public static void showAchievementGUI(Player player) { //adding fullwool achievement Material fullwoolMat = Material.COAL; - if (arrayList.contains("fullwool")) {fullwoolMat = Material.DIAMOND;} + if (arrayList.contains("fullwool")) { + fullwoolMat = Material.DIAMOND; + } ItemStack fullwool = new ItemStack(fullwoolMat); ItemMeta fullwoolmeta = fullwool.getItemMeta(); ArrayList fullwoolLore = new ArrayList<>(); @@ -48,8 +52,7 @@ public static void showAchievementGUI(Player player) { fullwoolLore.add(" "); if (fullwoolMat == Material.COAL) { fullwoolLore.add(ChatColor.RED + "Not Completed"); - } - else { + } else { fullwoolLore.add(ChatColor.GREEN + "Completed"); } fullwoolmeta.setDisplayName("§6Strategist"); @@ -59,8 +62,10 @@ public static void showAchievementGUI(Player player) { //adding Killstreak 5 achievement Material killstreak5Mat = Material.COAL; - if (arrayList.contains("killstreak5")) {killstreak5Mat = Material.DIAMOND;} - ItemStack Killstreak5 = new ItemStack(killstreak5Mat, 1, (byte)1); + if (arrayList.contains("killstreak5")) { + killstreak5Mat = Material.DIAMOND; + } + ItemStack Killstreak5 = new ItemStack(killstreak5Mat, 1, (byte) 1); ItemMeta Killstreak5meta = Killstreak5.getItemMeta(); ArrayList Killstreak5Lore = new ArrayList<>(); @@ -68,8 +73,7 @@ public static void showAchievementGUI(Player player) { Killstreak5Lore.add(" "); if (killstreak5Mat == Material.COAL) { Killstreak5Lore.add(ChatColor.RED + "Not Completed"); - } - else { + } else { Killstreak5Lore.add(ChatColor.GREEN + "Completed"); } Killstreak5meta.setDisplayName("§6Dominator"); @@ -79,8 +83,10 @@ public static void showAchievementGUI(Player player) { //adding closeCall achievement Material closeCallMat = Material.COAL; - if (arrayList.contains("closeCall")) {closeCallMat = Material.DIAMOND;} - ItemStack closeCall = new ItemStack(closeCallMat, 1, (byte)1); + if (arrayList.contains("closeCall")) { + closeCallMat = Material.DIAMOND; + } + ItemStack closeCall = new ItemStack(closeCallMat, 1, (byte) 1); ItemMeta closeCallMeta = closeCall.getItemMeta(); ArrayList closeCallLore = new ArrayList<>(); @@ -88,8 +94,7 @@ public static void showAchievementGUI(Player player) { closeCallLore.add(" "); if (closeCallMat == Material.COAL) { closeCallLore.add(ChatColor.RED + "Not Completed"); - } - else { + } else { closeCallLore.add(ChatColor.GREEN + "Completed"); } closeCallMeta.setDisplayName("§6Close Call"); @@ -99,8 +104,10 @@ public static void showAchievementGUI(Player player) { //adding losing achievement Material losingMat = Material.COAL; - if (arrayList.contains("losing")) {losingMat = Material.DIAMOND;} - ItemStack losing = new ItemStack(losingMat, 1, (byte)1); + if (arrayList.contains("losing")) { + losingMat = Material.DIAMOND; + } + ItemStack losing = new ItemStack(losingMat, 1, (byte) 1); ItemMeta losingMeta = losing.getItemMeta(); ArrayList losingLore = new ArrayList<>(); @@ -108,8 +115,7 @@ public static void showAchievementGUI(Player player) { losingLore.add(" "); if (losingMat == Material.COAL) { losingLore.add(ChatColor.RED + "Not Completed"); - } - else { + } else { losingLore.add(ChatColor.GREEN + "Completed"); } losingMeta.setDisplayName("§6Losing is the new winning"); @@ -119,8 +125,10 @@ public static void showAchievementGUI(Player player) { //adding carried achievement Material carriedMat = Material.COAL; - if (arrayList.contains("carried")) {carriedMat = Material.DIAMOND;} - ItemStack carried = new ItemStack(carriedMat, 1, (byte)1); + if (arrayList.contains("carried")) { + carriedMat = Material.DIAMOND; + } + ItemStack carried = new ItemStack(carriedMat, 1, (byte) 1); ItemMeta carriedMeta = carried.getItemMeta(); ArrayList carriedLore = new ArrayList<>(); @@ -129,8 +137,7 @@ public static void showAchievementGUI(Player player) { carriedLore.add(" "); if (carriedMat == Material.COAL) { carriedLore.add(ChatColor.RED + "Not Completed"); - } - else { + } else { carriedLore.add(ChatColor.GREEN + "Completed"); } carriedMeta.setDisplayName("§6The British way"); diff --git a/src/main/java/woolbattle/woolbattle/base/Base.java b/src/main/java/woolbattle/woolbattle/base/Base.java index e46d6b8..7ef939e 100644 --- a/src/main/java/woolbattle/woolbattle/base/Base.java +++ b/src/main/java/woolbattle/woolbattle/base/Base.java @@ -38,14 +38,14 @@ public class Base implements Listener { public void onEntityDamage(EntityDamageEvent event) { if (event.getCause() != EntityDamageEvent.DamageCause.ENTITY_ATTACK && event.getCause() != EntityDamageEvent.DamageCause.PROJECTILE) { event.setCancelled(true); - } - else{ + } else { event.setDamage(0); } } /** * An event which changes the chat format to one that looks better + * * @param event the AsyncPlayerChatEvent * @author Beelzebub */ @@ -105,38 +105,40 @@ public void onBlockPlace(BlockPlaceEvent event) { /** * An Event that gets executed whenever a player drags an item from one spot to another to prevent stealing items * from the lobby items. + * * @param event the InventoryDragEvent event * @author SimsumMC */ @EventHandler - public void onInventoryDrag(InventoryDragEvent event){ + public void onInventoryDrag(InventoryDragEvent event) { event.setCancelled(true); } /** * An Event that gets executed whenever the weather changes to prevent the changing of weather. + * * @param event the InventoryDragEvent event * @author SimsumMC */ @EventHandler - public void onWeatherChange(WeatherChangeEvent event){ + public void onWeatherChange(WeatherChangeEvent event) { event.setCancelled(true); } /** * A Method that adds the given Ender Pearl Entity to the Cache. + * * @param enderPearl the Ender Pearl Entity * @author SimsumMC */ - public static void addEnderPearl(EnderPearl enderPearl){ + public static void addEnderPearl(EnderPearl enderPearl) { ProjectileSource source = enderPearl.getShooter(); - if(source instanceof Player){ + if (source instanceof Player) { HashMap> enderPearls = Cache.getEnderPearls(); ArrayList playerPearls; - if(!enderPearls.containsKey((Player) source)){ + if (!enderPearls.containsKey((Player) source)) { playerPearls = new ArrayList<>(); - } - else{ + } else { playerPearls = enderPearls.get((Player) source); } @@ -149,17 +151,18 @@ public static void addEnderPearl(EnderPearl enderPearl){ /** * A Method that removes all ender pearls from a given player from the hashmap & from the world. + * * @param player the player that ender pearls get removed * @author SimsumMC */ - public static void resetEnderPearls(Player player){ + public static void resetEnderPearls(Player player) { HashMap> enderPearls = Cache.getEnderPearls(); - if(!enderPearls.containsKey(player)){ + if (!enderPearls.containsKey(player)) { return; } - for(EnderPearl enderPearl : enderPearls.get(player)){ + for (EnderPearl enderPearl : enderPearls.get(player)) { enderPearl.remove(); } diff --git a/src/main/java/woolbattle/woolbattle/itemsystem/ItemSystem.java b/src/main/java/woolbattle/woolbattle/items/ItemSystem.java similarity index 81% rename from src/main/java/woolbattle/woolbattle/itemsystem/ItemSystem.java rename to src/main/java/woolbattle/woolbattle/items/ItemSystem.java index a14c000..bf7a67b 100644 --- a/src/main/java/woolbattle/woolbattle/itemsystem/ItemSystem.java +++ b/src/main/java/woolbattle/woolbattle/items/ItemSystem.java @@ -1,4 +1,4 @@ -package woolbattle.woolbattle.itemsystem; +package woolbattle.woolbattle.items; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; @@ -32,7 +32,7 @@ public class ItemSystem { //Creates the item-meta-specific values that are known, before a potential player is passed into the giveItems // method - private static final HashMap armorStacks = new HashMap(){ + private static final HashMap armorStacks = new HashMap() { { put(0, new ItemStack(Material.LEATHER_BOOTS).getItemMeta()); put(1, new ItemStack(Material.LEATHER_LEGGINGS).getItemMeta()); @@ -40,7 +40,7 @@ public class ItemSystem { put(3, new ItemStack(Material.LEATHER_HELMET).getItemMeta()); } }; - public static final HashMap defaultSlots = new HashMap(){ + public static final HashMap defaultSlots = new HashMap() { { put("shears", 0); put("bow", 1); @@ -53,10 +53,11 @@ public class ItemSystem { /** * Method to add the game's base items, additionally to this the individual player's perk-items into their * inventory, colours colour-able fragments of this equipment according to the player's team-colour. + * * @param player The player to be given the items specified above * @author Servaturus */ - public static void giveItems(Player player){ + public static void giveItems(Player player) { Color color = findTeamColor(player); PlayerInventory inventory = player.getInventory(); @@ -73,14 +74,13 @@ public static void giveItems(Player player){ MongoCollection collection = db.getCollection("playerInventories"); Document foundDocument = collection.find(eq("_id", player.getUniqueId().toString())).first(); - if(foundDocument == null){ + if (foundDocument == null) { shearsSlot = defaultSlots.get("shears"); bowSlot = defaultSlots.get("bow"); enderPearlSlot = defaultSlots.get("enderpearl"); perk1Slot = defaultSlots.get("perk1"); perk2Slot = defaultSlots.get("perk2"); - } - else{ + } else { shearsSlot = (int) foundDocument.get("shears"); bowSlot = (int) foundDocument.get("bow"); enderPearlSlot = (int) foundDocument.get("ender_pearl"); @@ -104,25 +104,25 @@ public static void giveItems(Player player){ Document perksDocument = perksCollection.find(eq("_id", player.getUniqueId().toString())).first(); - if(perksDocument != null) { + if (perksDocument != null) { String activePerk1String = null; String activePerk2String = null; String passivePerkString = null; - if (perksDocument.get("first_active") != null){ + if (perksDocument.get("first_active") != null) { activePerk1String = (String) perksDocument.get("first_active"); } - if (perksDocument.get("second_active") != null){ + if (perksDocument.get("second_active") != null) { activePerk2String = (String) perksDocument.get("second_active"); } - if (perksDocument.get("passive") != null){ + if (perksDocument.get("passive") != null) { passivePerkString = (String) perksDocument.get("passive"); } - if(activePerk1String != null) { + if (activePerk1String != null) { ActivePerk activePerk1 = Cache.getActivePerks().get(activePerk1String); if (activePerk1 != null) { @@ -130,15 +130,15 @@ public static void giveItems(Player player){ } } - if(activePerk2String != null) { + if (activePerk2String != null) { ActivePerk activePerk2 = Cache.getActivePerks().get(activePerk2String); if (activePerk2 != null) { inventory.setItem(perk2Slot, activePerk2.getItemStack()); } } - if(passivePerkString != null) { - PassivePerk passivePerk = Cache.getPassivePerks().get(passivePerkString); + if (passivePerkString != null) { + PassivePerk passivePerk = Cache.getPassivePerks().get(passivePerkString); if (passivePerk != null) { inventory.setItem(passivePerkSlot, passivePerk.getItem()); } @@ -146,13 +146,13 @@ public static void giveItems(Player player){ } - for(Integer index : armorStacks.keySet()){ + for (Integer index : armorStacks.keySet()) { LeatherArmorMeta meta = (LeatherArmorMeta) armorStacks.get(index); meta.setColor(color); - ItemStack armorPiece = new ItemStack(){ + ItemStack armorPiece = new ItemStack() { { - switch(index){ + switch (index) { case 0: this.setType(Material.LEATHER_BOOTS); meta.setDisplayName(ChatColor.AQUA + "Leather Boots"); @@ -179,7 +179,7 @@ public static void giveItems(Player player){ } }; armorPiece.setAmount(1); - switch(index){ + switch (index) { case 0: inventory.setBoots(armorPiece); break; @@ -203,24 +203,25 @@ public static void giveItems(Player player){ /** * Method that subtracts wool from a players inventory. - * @author Servaturus - * @param player The player, to remove the wool from + * + * @param player The player, to remove the wool from * @param subtractWool The wool subtractWool to subtract + * @author Servaturus * @author Servaturus & SimsumMC */ - public static boolean subtractWool(Player player, int subtractWool){ + public static boolean subtractWool(Player player, int subtractWool) { PlayerInventory inv = player.getInventory(); int existingWoolAmount = 0; - for(ItemStack iterStack : inv.getContents()){ - if(iterStack != null && iterStack.getType().equals(Material.WOOL)){ + for (ItemStack iterStack : inv.getContents()) { + if (iterStack != null && iterStack.getType().equals(Material.WOOL)) { existingWoolAmount += iterStack.getAmount(); } } - if(existingWoolAmount - subtractWool < 0){ + if (existingWoolAmount - subtractWool < 0) { return false; } @@ -229,38 +230,38 @@ public static boolean subtractWool(Player player, int subtractWool){ ArrayList woolStacks = new ArrayList<>(); DyeColor color = findTeamDyeColor(player); - for(ItemStack is : inv.getContents()){ - if(is != null && is.getType().equals(Material.WOOL)){ + for (ItemStack is : inv.getContents()) { + if (is != null && is.getType().equals(Material.WOOL)) { woolAmount += is.getAmount(); } } - if(woolAmount - subtractWool ==0){ + if (woolAmount - subtractWool == 0) { player.getInventory().remove(Material.WOOL); return true; } woolAmount = woolAmount - subtractWool; - int modulo = woolAmount%64; + int modulo = woolAmount % 64; inv.remove(Material.WOOL); - ItemStack woolInstance = new Wool(color).toItemStack(); + ItemStack woolInstance = new Wool(color).toItemStack(); - if(woolAmount%64 !=0){ + if (woolAmount % 64 != 0) { ItemStack wool = new ItemStack(woolInstance); wool.setAmount(modulo); woolStacks.add(new ItemStack(wool)); - woolAmount-=(woolAmount%64); + woolAmount -= (woolAmount % 64); } - for(int i = 0; i spawnProtection = Cache.getSpawnProtection(); @@ -77,7 +79,7 @@ public static void setPlayerSpawnProtection(Player player, int length){ */ @EventHandler public void onPlayerMove(PlayerMoveEvent event) { - if(!LobbySystem.gameStarted){ + if (!LobbySystem.gameStarted) { return; } @@ -100,7 +102,7 @@ public void onPlayerMove(PlayerMoveEvent event) { HashMap playerDuels = Cache.getPlayerDuels(); Player otherPlayer = playerDuels.get(player); - if(otherPlayer != null){ + if (otherPlayer != null) { playerDuels.remove(player); playerDuels.remove(otherPlayer); Cache.setPlayerDuels(playerDuels); @@ -122,26 +124,25 @@ public void onPlayerMove(PlayerMoveEvent event) { Entity damager; - if(lastDamageEvent instanceof EntityDamageByEntityEvent){ + if (lastDamageEvent instanceof EntityDamageByEntityEvent) { damager = ((EntityDamageByEntityEvent) lastDamageEvent).getDamager(); - } - else{ + } else { damager = null; } - if(damager == null){ + if (damager == null) { teleportPlayerTeamSpawn(player); setPlayerSpawnProtection(player, Config.spawnProtectionLengthAfterDeath); } - if(damager instanceof Arrow){ + if (damager instanceof Arrow) { Arrow arrow = (Arrow) damager; damager = (Entity) arrow.getShooter(); } if (damager instanceof Player) { - if(lives != 0){ + if (lives != 0) { lives -= 1; } teamLives.put(team, lives); @@ -151,7 +152,7 @@ public void onPlayerMove(PlayerMoveEvent event) { Cache.setLastDamage(lastDamage); String damagerTeam = TeamSystem.getPlayerTeam((Player) damager, true); - ChatColor damagerTeamColour = TeamSystem.getTeamColour(damagerTeam) ; + ChatColor damagerTeamColour = TeamSystem.getTeamColour(damagerTeam); String killMessage = ChatColor.GRAY + "The player " + TeamSystem.getTeamColour(team) + player.getDisplayName() + ChatColor.GRAY + " was killed by " + damagerTeamColour + ((Player) damager).getDisplayName() + ChatColor.GRAY + "."; @@ -161,13 +162,14 @@ public void onPlayerMove(PlayerMoveEvent event) { HashMap kills = killStreaks.get(damagerTeam); - killStreaks.put(team, new HashMap(){{put(player, 0);}}); + killStreaks.put(team, new HashMap() {{ + put(player, 0); + }}); int amKills; - if(kills.containsKey(damager)){ + if (kills.containsKey(damager)) { amKills = kills.get(damager) + 1; - } - else{ + } else { amKills = 1; } @@ -175,7 +177,7 @@ public void onPlayerMove(PlayerMoveEvent event) { HashMap> playerStats = Cache.getPlayerStats(); - if(amKills == 5){ + if (amKills == 5) { AchievementSystem.giveKillstreak5((Player) damager); @@ -201,8 +203,7 @@ public void onPlayerMove(PlayerMoveEvent event) { if (lives == 0) { TeamSystem.removePlayerTeam(player); LobbySystem.setPlayerSpectator(player); - } - else{ + } else { teleportPlayerTeamSpawn(player); setPlayerSpawnProtection(player, Config.spawnProtectionLengthAfterDeath); } diff --git a/src/main/java/woolbattle/woolbattle/lobby/LobbySystem.java b/src/main/java/woolbattle/woolbattle/lobby/LobbySystem.java index 3d713b4..29d0b0d 100644 --- a/src/main/java/woolbattle/woolbattle/lobby/LobbySystem.java +++ b/src/main/java/woolbattle/woolbattle/lobby/LobbySystem.java @@ -29,13 +29,13 @@ import woolbattle.woolbattle.Enums.PerkType; import woolbattle.woolbattle.Main; import woolbattle.woolbattle.achievements.AchievementUI; -import woolbattle.woolbattle.itemsystem.ItemSystem; +import woolbattle.woolbattle.items.ItemSystem; import woolbattle.woolbattle.perks.ActivePerk; import woolbattle.woolbattle.perks.AllPassivePerks; import woolbattle.woolbattle.perks.PassivePerk; import woolbattle.woolbattle.stats.StatsSystem; import woolbattle.woolbattle.team.TeamSystem; -import woolbattle.woolbattle.woolsystem.BlockBreakingSystem; +import woolbattle.woolbattle.map.BlockBreakingSystem; import java.util.*; @@ -63,7 +63,7 @@ public void onPlayerDeath(PlayerDeathEvent event) { Player player = event.getEntity(); event.setDeathMessage(ChatColor.GRAY + "The player " + ChatColor.GREEN + player.getDisplayName() + ChatColor.GRAY + " died."); - if(!gameStarted){ + if (!gameStarted) { giveLobbyItems(player); } @@ -144,11 +144,11 @@ public void onPlayerQuit(PlayerQuitEvent event) { public void onInventoryClick(InventoryClickEvent event) { Player player = (Player) event.getWhoClicked(); - if(event.getCurrentItem() == null){ + if (event.getCurrentItem() == null) { return; } - if(event.getCurrentItem().getType() == Material.SULPHUR){ + if (event.getCurrentItem().getType() == Material.SULPHUR) { player.sendMessage(ChatColor.RED + "You can't move items that are on cooldown!"); event.setCancelled(true); } @@ -171,17 +171,17 @@ public void onInventoryClick(InventoryClickEvent event) { } } - if(event.getClickedInventory().getName() == null ||!event.getCurrentItem().hasItemMeta() || event.getCurrentItem().getItemMeta().getDisplayName().equals(" ")) { + if (event.getClickedInventory().getName() == null || !event.getCurrentItem().hasItemMeta() || event.getCurrentItem().getItemMeta().getDisplayName().equals(" ")) { return; } String rawInventoryName = event.getClickedInventory().getName().substring(2); String rawItemName = event.getCurrentItem().getItemMeta().getDisplayName().substring(2); - if(rawItemName == null){ + if (rawItemName == null) { return; } - switch(rawInventoryName) { + switch (rawInventoryName) { case "Amount of Lives Voting": HashMap> votingData = Cache.getLifeVoting(); ItemMeta clickedItemMeta = event.getCurrentItem().getItemMeta(); @@ -230,7 +230,7 @@ public void onInventoryClick(InventoryClickEvent event) { break; case "Choose Perks": - switch(rawItemName){ + switch (rawItemName) { case "Active Perk #1": showActivePerkMenu(player, PerkType.FIRST_ACTIVE); break; @@ -244,28 +244,25 @@ public void onInventoryClick(InventoryClickEvent event) { break; case "Active Perk #1": - if(rawItemName.equals("Go Back")){ + if (rawItemName.equals("Go Back")) { showPerkMenu(player); - } - else{ + } else { savePerkSelection(player, rawItemName, PerkType.FIRST_ACTIVE); showActivePerkMenu(player, PerkType.FIRST_ACTIVE); } break; case "Active Perk #2": - if(rawItemName.equals("Go Back")){ + if (rawItemName.equals("Go Back")) { showPerkMenu(player); - } - else { + } else { savePerkSelection(player, rawItemName, PerkType.SECOND_ACTIVE); showActivePerkMenu(player, PerkType.SECOND_ACTIVE); } break; case "Passive Perk": - if(rawItemName.equals("Go Back")){ + if (rawItemName.equals("Go Back")) { showPerkMenu(player); - } - else { + } else { savePerkSelection(player, rawItemName, PerkType.PASSIVE); showPassivePerkMenu(player); } @@ -276,12 +273,14 @@ public void onInventoryClick(InventoryClickEvent event) { /** * An Event that gets executed whenever a player interacts with an item to make the lobby items functional. + * * @param event the PlayerInteractEvent event * @author SimsumMC */ @EventHandler public void onPlayerInteract(PlayerInteractEvent event) { - if (event.getItem() == null || event.getItem().getItemMeta() == null || event.getItem().getItemMeta().getDisplayName() == null) return; + if (event.getItem() == null || event.getItem().getItemMeta() == null || event.getItem().getItemMeta().getDisplayName() == null) + return; Player player = event.getPlayer(); String displayName = event.getItem().getItemMeta().getDisplayName(); @@ -308,7 +307,7 @@ public void onPlayerInteract(PlayerInteractEvent event) { } ActivePerk activePerk = Cache.getActivePerks().get(displayName.substring(2)); - if(activePerk != null){ + if (activePerk != null) { activePerk.execute(event, player); } @@ -317,12 +316,13 @@ public void onPlayerInteract(PlayerInteractEvent event) { /** * An Event that gets executed whenever a player closes the current inventory which is required to save the new * inventory of the "Edit Inventory" Item + * * @param event the InventoryCloseEvent event * @author SimsumMC */ @EventHandler public void onInventoryClose(InventoryCloseEvent event) { - if(event.getInventory().getName() == null || !event.getInventory().getName().equals("§bEdit Inventory")){ + if (event.getInventory().getName() == null || !event.getInventory().getName().equals("§bEdit Inventory")) { return; } @@ -337,8 +337,8 @@ public void onInventoryClose(InventoryCloseEvent event) { int position = 0; for (ItemStack itemStack : eventInventory.getContents()) { - if(itemStack != null && itemStack.hasItemMeta() && !itemStack.getType().equals(Material.GLASS)){ - switch(itemStack.getItemMeta().getDisplayName()){ + if (itemStack != null && itemStack.hasItemMeta() && !itemStack.getType().equals(Material.GLASS)) { + switch (itemStack.getItemMeta().getDisplayName()) { case "§bShears": shearsPosition = position - 9; break; @@ -366,7 +366,7 @@ public void onInventoryClose(InventoryCloseEvent event) { int finalActivePerk2Position = activePerk2Position; //check for mistakes - ArrayList values= new ArrayList(){{ + ArrayList values = new ArrayList() {{ add(finalShearsPosition); add(finalBowPosition); add(finalEnderPearlPosition); @@ -374,14 +374,14 @@ public void onInventoryClose(InventoryCloseEvent event) { int notDefined = 0; - for(Integer value: values){ - if(value==0){ - notDefined +=1; + for (Integer value : values) { + if (value == 0) { + notDefined += 1; } } - if(notDefined >= 2){ - new BukkitRunnable(){ + if (notDefined >= 2) { + new BukkitRunnable() { @Override public void run() { @@ -398,8 +398,8 @@ public void run() { MongoCollection collection = db.getCollection("playerInventories"); Document foundDocument = collection.find(eq("_id", player.getUniqueId().toString())).first(); - if(foundDocument == null){ - HashMap playerData = new HashMap(){{ + if (foundDocument == null) { + HashMap playerData = new HashMap() {{ put("_id", player.getUniqueId().toString()); put("shears", finalShearsPosition); put("bow", finalBowPosition); @@ -410,9 +410,8 @@ public void run() { Document document = new Document(playerData); collection.insertOne(document); - } - else{ - Document query = new Document().append("_id", player.getUniqueId().toString()); + } else { + Document query = new Document().append("_id", player.getUniqueId().toString()); Bson updates = Updates.combine( Updates.set("shears", finalShearsPosition), @@ -427,7 +426,7 @@ public void run() { player.sendMessage(ChatColor.GREEN + "Your new inventory was successfully saved."); - new BukkitRunnable(){ + new BukkitRunnable() { @Override public void run() { @@ -440,11 +439,12 @@ public void run() { /** * A Method that starts the game, gives every player the right items, changes the scoreboard, resets the cooldown and * teleports the players to the right position. + * * @return A boolean whether the game could successfully be started * @author SimsumMC */ public static boolean startGame() { - if(gameStarted){ + if (gameStarted) { return false; } @@ -459,11 +459,11 @@ public static boolean startGame() { Collection players = Bukkit.getOnlinePlayers(); - for(Player player: players){ + for (Player player : players) { String team = TeamSystem.getPlayerTeam(player, true); teamLives.put(team, topVotedLifeAmount); Location location; - switch (team){ + switch (team) { case "Red": location = Config.redLocation; break; @@ -487,7 +487,7 @@ public static boolean startGame() { setPlayerSpawnProtection(player, Config.spawnProtectionLengthAtGameStart); - if(player.getGameMode() == GameMode.SPECTATOR || player.getGameMode() == GameMode.CREATIVE){ + if (player.getGameMode() == GameMode.SPECTATOR || player.getGameMode() == GameMode.CREATIVE) { player.setGameMode(GameMode.SURVIVAL); } @@ -503,6 +503,7 @@ public static boolean startGame() { /** * A Method that ends the game, gives every player the lobby items, changes the scoreboard, resets the Cache, * teleports the players to the lobby and announces the winner team. + * * @param winnerTeam the winner team as a **COLORED** String * @return A boolean whether the game could be successfully ended * @author SimsumMC @@ -510,7 +511,7 @@ public static boolean startGame() { public static boolean endGame(String winnerTeam) { runScoreBoardTask = false; - if(!gameStarted){ + if (!gameStarted) { return false; } @@ -528,11 +529,11 @@ public static boolean endGame(String winnerTeam) { Collection players = Bukkit.getOnlinePlayers(); - for(Player player: players){ + for (Player player : players) { setLobbyScoreBoard(player); giveLobbyItems(player); player.teleport(Config.lobbyLocation); - if(player.getGameMode() == GameMode.SPECTATOR || player.getGameMode() == GameMode.CREATIVE){ + if (player.getGameMode() == GameMode.SPECTATOR || player.getGameMode() == GameMode.CREATIVE) { player.setGameMode(GameMode.SURVIVAL); } player.sendTitle(winnerTeam + ChatColor.GRAY + " won!", " "); @@ -545,6 +546,7 @@ public static boolean endGame(String winnerTeam) { /** * A Method that trys to find a winner team and ends the game if a team is found. + * * @author SimsumMC */ public static void determinateWinnerTeam() { @@ -554,21 +556,19 @@ public static void determinateWinnerTeam() { int emptyTeams = 0; String existingTeam = null; - for(String key : teamMembers.keySet()){ + for (String key : teamMembers.keySet()) { ArrayList players = teamMembers.get(key); - if(players.size() == 0){ + if (players.size() == 0) { emptyTeams += 1; - } - else{ + } else { existingTeam = key; } } - if(emptyTeams >= 3){ - if(existingTeam != null){ + if (emptyTeams >= 3) { + if (existingTeam != null) { endGame(TeamSystem.getTeamColour(existingTeam) + existingTeam); - } - else{ + } else { endGame("§cUnknown"); } return; @@ -580,21 +580,19 @@ public static void determinateWinnerTeam() { int deathTeams = 0; existingTeam = null; - for(String key : teamLives.keySet()){ + for (String key : teamLives.keySet()) { int lives = teamLives.get(key); - if(lives == 0){ + if (lives == 0) { deathTeams += 1; - } - else{ + } else { existingTeam = key; } } - if(deathTeams >= 3){ - if(existingTeam != null){ + if (deathTeams >= 3) { + if (existingTeam != null) { endGame(TeamSystem.getTeamColour(existingTeam) + existingTeam); - } - else{ + } else { endGame("§cUnknown"); } } @@ -603,21 +601,22 @@ public static void determinateWinnerTeam() { /** * A Method that saves the Perk that was selected by a player. - * @param player the Player that selected the perk + * + * @param player the Player that selected the perk * @param perkName the Name of the Perk without colour code * @param perkType the Type of the perk as an enum * @author SimsumMC */ - public void savePerkSelection(Player player, String perkName, PerkType perkType){ + public void savePerkSelection(Player player, String perkName, PerkType perkType) { String perkTypeString = perkType.toString().toLowerCase(); MongoDatabase db = Main.getMongoDatabase(); MongoCollection collection = db.getCollection("playerPerks"); Document foundDocument = collection.find(eq("_id", player.getUniqueId().toString())).first(); - if(foundDocument == null){ + if (foundDocument == null) { - HashMap playerData = new HashMap(){{ + HashMap playerData = new HashMap() {{ put("_id", player.getUniqueId().toString()); put("first_active", null); put("second_active", null); @@ -628,24 +627,22 @@ public void savePerkSelection(Player player, String perkName, PerkType perkType) Document document = new Document(playerData); collection.insertOne(document); - } - else{ - if(perkType == PerkType.FIRST_ACTIVE){ + } else { + if (perkType == PerkType.FIRST_ACTIVE) { Object get = foundDocument.get(PerkType.SECOND_ACTIVE.toString().toLowerCase()); - if(get != null && get.equals(perkName)){ + if (get != null && get.equals(perkName)) { player.sendMessage(ChatColor.RED + "You can't have the same active perks!"); return; } - } - else if (perkType == PerkType.SECOND_ACTIVE){ + } else if (perkType == PerkType.SECOND_ACTIVE) { Object get = foundDocument.get(PerkType.FIRST_ACTIVE.toString().toLowerCase()); - if(get != null && get.equals(perkName)){ + if (get != null && get.equals(perkName)) { player.sendMessage(ChatColor.RED + "You can't have the same active perks!"); return; } } - Document query = new Document().append("_id", player.getUniqueId().toString()); + Document query = new Document().append("_id", player.getUniqueId().toString()); Bson updates = Updates.set(perkTypeString, perkName); @@ -656,6 +653,7 @@ else if (perkType == PerkType.SECOND_ACTIVE){ /** * A Method that gives the lobby items to the given player. + * * @param player the player that becomes the items in the inventory * @author SimsumMC */ @@ -719,11 +717,12 @@ public static void giveLobbyItems(Player player) { /** * A Method that shows / updates the inventar to vote for the life count. + * * @param player the player that gets the life amount voting inventory opened * @author SimsumMC */ private static void showLifeAmountVoting(Player player) { - Inventory inv = Bukkit.createInventory(null, 3*9, "§aAmount of Lives Voting"); + Inventory inv = Bukkit.createInventory(null, 3 * 9, "§aAmount of Lives Voting"); // Glass Background ItemStack glassStack = new ItemStack(Material.STAINED_GLASS_PANE, 1, (short) 15); @@ -731,7 +730,7 @@ private static void showLifeAmountVoting(Player player) { glassMeta.setDisplayName(" "); glassStack.setItemMeta(glassMeta); - for (int i = 0; i<= 26; i++) { + for (int i = 0; i <= 26; i++) { inv.setItem(i, glassStack); } @@ -740,7 +739,9 @@ private static void showLifeAmountVoting(Player player) { ItemStack fiveLivesStack = new ItemStack(Material.INK_SACK, 5, (short) 0, (byte) 10); ItemMeta fiveLivesMeta = fiveLivesStack.getItemMeta(); fiveLivesMeta.setDisplayName("§a5 Lives"); - fiveLivesMeta.setLore(new ArrayList(){{add(ChatColor.GRAY + "»Votes: §a" + fiveVoteCount);}}); + fiveLivesMeta.setLore(new ArrayList() {{ + add(ChatColor.GRAY + "»Votes: §a" + fiveVoteCount); + }}); fiveLivesStack.setItemMeta(fiveLivesMeta); inv.setItem(11, fiveLivesStack); @@ -749,7 +750,9 @@ private static void showLifeAmountVoting(Player player) { ItemStack tenLivesStack = new ItemStack(Material.INK_SACK, 10, (short) 0, (byte) 10); ItemMeta tenLivesMeta = tenLivesStack.getItemMeta(); tenLivesMeta.setDisplayName("§a10 Lives"); - tenLivesMeta.setLore(new ArrayList(){{add(ChatColor.GRAY + "»Votes: §a" + tenVoteCount);}}); + tenLivesMeta.setLore(new ArrayList() {{ + add(ChatColor.GRAY + "»Votes: §a" + tenVoteCount); + }}); tenLivesStack.setItemMeta(tenLivesMeta); inv.setItem(13, tenLivesStack); @@ -758,7 +761,9 @@ private static void showLifeAmountVoting(Player player) { ItemStack fifteenLivesStack = new ItemStack(Material.INK_SACK, 15, (short) 0, (byte) 10); ItemMeta fifteenLivesMeta = fifteenLivesStack.getItemMeta(); fifteenLivesMeta.setDisplayName("§a15 Lives"); - fifteenLivesMeta.setLore(new ArrayList(){{add(ChatColor.GRAY + "»Votes: §a" + fifteenVoteCount);}}); + fifteenLivesMeta.setLore(new ArrayList() {{ + add(ChatColor.GRAY + "»Votes: §a" + fifteenVoteCount); + }}); fifteenLivesStack.setItemMeta(fifteenLivesMeta); inv.setItem(15, fifteenLivesStack); @@ -767,11 +772,12 @@ private static void showLifeAmountVoting(Player player) { /** * A Method that shows / updates the inventar to change the inventory sort. + * * @param player - the Player that gets the inventory opened * @author SimsumMC */ private static void showEditInventoryMenu(Player player) { - Inventory inv = Bukkit.createInventory(null, 3*9, "§bEdit Inventory"); + Inventory inv = Bukkit.createInventory(null, 3 * 9, "§bEdit Inventory"); // Glass Background ItemStack glassStack = new ItemStack(Material.STAINED_GLASS_PANE, 1, (short) 15); @@ -779,8 +785,8 @@ private static void showEditInventoryMenu(Player player) { glassMeta.setDisplayName(" "); glassStack.setItemMeta(glassMeta); - for (int i = 0; i<= 26; i++) { - if(i >= 9 && i <=17){ + for (int i = 0; i <= 26; i++) { + if (i >= 9 && i <= 17) { continue; } inv.setItem(i, glassStack); @@ -796,14 +802,13 @@ private static void showEditInventoryMenu(Player player) { MongoCollection collection = db.getCollection("playerInventories"); Document foundDocument = collection.find(eq("_id", player.getUniqueId().toString())).first(); - if(foundDocument == null){ + if (foundDocument == null) { shearsSlot = 9; bowSlot = 10; enderPearlSlot = 17; activePerk1Slot = 16; activePerk2Slot = 11; - } - else{ + } else { shearsSlot = (int) foundDocument.get("shears") + 9; bowSlot = (int) foundDocument.get("bow") + 9; enderPearlSlot = (int) foundDocument.get("ender_pearl") + 9; @@ -854,11 +859,12 @@ private static void showEditInventoryMenu(Player player) { /** * A Method that shows the inventar to choose between the different perk types to change them. + * * @param player - The player gets an inventory opened to choose the perks. * @author SimsumMC */ private static void showPerkMenu(Player player) { - Inventory inv = Bukkit.createInventory(null, 3*9, "§dChoose Perks"); + Inventory inv = Bukkit.createInventory(null, 3 * 9, "§dChoose Perks"); // Glass Background ItemStack glassStack = new ItemStack(Material.STAINED_GLASS_PANE, 1, (short) 15); @@ -866,7 +872,7 @@ private static void showPerkMenu(Player player) { glassMeta.setDisplayName(" "); glassStack.setItemMeta(glassMeta); - for (int i = 0; i<= 26; i++) { + for (int i = 0; i <= 26; i++) { inv.setItem(i, glassStack); } @@ -896,6 +902,7 @@ private static void showPerkMenu(Player player) { /** * A Method that shows the inventar to choose between the different perk types to change them. + * * @author SimsumMC */ private static void showActivePerkMenu(Player player, PerkType perkType) { @@ -907,32 +914,31 @@ private static void showActivePerkMenu(Player player, PerkType perkType) { MongoCollection collection = db.getCollection("playerPerks"); Document foundDocument = collection.find(eq("_id", player.getUniqueId().toString())).first(); - if(foundDocument != null){ - if(foundDocument.get(perkTypeString) != null){ + if (foundDocument != null) { + if (foundDocument.get(perkTypeString) != null) { selectedPerk = (String) foundDocument.get(perkTypeString); } } - Inventory inv = Bukkit.createInventory(null, 3*9, "§dActive Perk #" + perkType.value); + Inventory inv = Bukkit.createInventory(null, 3 * 9, "§dActive Perk #" + perkType.value); ArrayList newLore; HashMap activePerks = Cache.getActivePerks(); - for(ActivePerk perk : activePerks.values()){ - if(!perk.getSelectableStatus()){ + for (ActivePerk perk : activePerks.values()) { + if (!perk.getSelectableStatus()) { continue; } ItemStack itemStack = perk.getItemStack().clone(); ItemMeta itemMeta = itemStack.getItemMeta(); - if(selectedPerk != null && itemMeta.getDisplayName().substring(2).equals(selectedPerk)){ + if (selectedPerk != null && itemMeta.getDisplayName().substring(2).equals(selectedPerk)) { itemMeta.addEnchant(Enchantment.KNOCKBACK, 1, true); itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); - } - else{ - if (itemMeta.hasEnchants()){ - for(Enchantment enchantment : itemMeta.getEnchants().keySet()){ + } else { + if (itemMeta.hasEnchants()) { + for (Enchantment enchantment : itemMeta.getEnchants().keySet()) { itemMeta.removeEnchant(enchantment); } } @@ -971,27 +977,26 @@ private static void showPassivePerkMenu(Player player) { MongoCollection collection = db.getCollection("playerPerks"); Document foundDocument = collection.find(eq("_id", player.getUniqueId().toString())).first(); - if(foundDocument != null){ + if (foundDocument != null) { selectedPerk = (String) foundDocument.get("passive"); } - Inventory inv = Bukkit.createInventory(null, 3*9, "§dPassive Perk"); + Inventory inv = Bukkit.createInventory(null, 3 * 9, "§dPassive Perk"); ArrayList newLore; HashMap> passivePerks = Cache.getPassivePerks(); - for(PassivePerk perk : passivePerks.values()){ + for (PassivePerk perk : passivePerks.values()) { ItemStack itemStack = perk.getItem().clone(); ItemMeta itemMeta = itemStack.getItemMeta(); - if(selectedPerk != null && itemMeta.getDisplayName().substring(2).equals(selectedPerk)){ + if (selectedPerk != null && itemMeta.getDisplayName().substring(2).equals(selectedPerk)) { itemMeta.addEnchant(Enchantment.KNOCKBACK, 1, true); itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); - } - else{ - if (itemMeta.hasEnchants()){ - for(Enchantment enchantment : itemMeta.getEnchants().keySet()){ + } else { + if (itemMeta.hasEnchants()) { + for (Enchantment enchantment : itemMeta.getEnchants().keySet()) { itemMeta.removeEnchant(enchantment); } } @@ -1020,10 +1025,10 @@ private static void showPassivePerkMenu(Player player) { } - /** * A Method that updates the player cooldown (the number in the XP bar) every 20 ticks depended on the player * amount. + * * @author SimsumMC */ public static void updatePlayerCooldown() { @@ -1031,8 +1036,8 @@ public static void updatePlayerCooldown() { new BukkitRunnable() { @Override public void run() { - if(runScoreBoardTask){ - if(!gameStarted) { + if (runScoreBoardTask) { + if (!gameStarted) { Collection players = Bukkit.getOnlinePlayers(); int playerAmount = players.size(); if (playerAmount >= (Config.teamSize * 2)) { @@ -1061,11 +1066,12 @@ public void run() { /** * A Method that sets the cooldown for the given player. + * * @param player the player that gets the cooldown modified * @author SimsumMC */ public static void setPlayerCooldown(Player player, int level) { - float exp = (float) level/60; + float exp = (float) level / 60; player.setExp(exp); player.setLevel(level); @@ -1073,16 +1079,17 @@ public static void setPlayerCooldown(Player player, int level) { /** * A Method that returns the current top-voted amount of lives. + * * @return The top voted life amount as an Integer * @author SimsumMC */ - public static int getTopVotedLifeAmount(){ + public static int getTopVotedLifeAmount() { int topKey = Config.defaultLives; int topVoters = 0; HashMap> data = Cache.getLifeVoting(); - for(Integer key: data.keySet()){ + for (Integer key : data.keySet()) { ArrayList players = data.get(key); - if(players.size() > topVoters){ + if (players.size() > topVoters) { topVoters = players.size(); topKey = key; } @@ -1092,6 +1099,7 @@ public static int getTopVotedLifeAmount(){ /** * A Method that sets a player to a spectator -> game mode & position changes + * * @param player the player that gets into spectator mode * @author SimsumMC */ @@ -1102,6 +1110,7 @@ public static void setPlayerSpectator(Player player) { /** * A Method that updates the scoreboard for every player, depending on the game status. + * * @author SimsumMC */ public static void updateScoreBoard() { @@ -1112,19 +1121,21 @@ public static void updateScoreBoard() { public void run() { Collection players = Bukkit.getServer().getOnlinePlayers(); - for(Player player : players) { + for (Player player : players) { if (!gameStarted) { updateLobbyScoreBoard(player); } else { updateGameScoreBoard(player); } - } } + } + } }.runTaskTimer(Main.getInstance(), 0, 20); } /** * A Method that changes the scoreboard for the given player to the lobby scoreboard. + * * @param player the player that gets the scoreboard modified * @author SimsumMC */ @@ -1184,11 +1195,14 @@ public static void setLobbyScoreBoard(Player player) { /** * A Method that updates the scoreboard for the given player with the current values. + * * @param player the player that gets the scoreboard modified * @author SimsumMC */ public static void updateLobbyScoreBoard(Player player) { - if (!runScoreBoardTask){return;} + if (!runScoreBoardTask) { + return; + } int maxPlayers = Bukkit.getServer().getMaxPlayers(); int actualPlayers = Bukkit.getServer().getOnlinePlayers().size(); @@ -1209,6 +1223,7 @@ public static void updateLobbyScoreBoard(Player player) { /** * A Method that changes the scoreboard for the given player to the game scoreboard. + * * @param player the player that gets the scoreboard modified * @author SimsumMC */ @@ -1250,7 +1265,7 @@ public static void setGameScoreBoard(Player player) { obj.getScore("§e").setScore(0); team.addEntry("§c"); - team.setPrefix(TeamSystem.getPlayerTeam(player,false)); + team.setPrefix(TeamSystem.getPlayerTeam(player, false)); map.addEntry("§d"); map.setPrefix("§d" + Config.defaultMap); @@ -1279,11 +1294,14 @@ public static void setGameScoreBoard(Player player) { /** * A Method that updates the scoreboard for the given player with the current values. + * * @param player the player that gets the scoreboard modified * @author SimsumMC */ public static void updateGameScoreBoard(Player player) { - if (!runScoreBoardTask){return;} + if (!runScoreBoardTask) { + return; + } Scoreboard board = player.getScoreboard(); @@ -1295,7 +1313,7 @@ public static void updateGameScoreBoard(Player player) { Team greenTeam = board.getTeam("greenTeam"); Team yellowTeam = board.getTeam("yellowTeam"); - team.setPrefix(TeamSystem.getPlayerTeam(player,false)); + team.setPrefix(TeamSystem.getPlayerTeam(player, false)); map.setPrefix("§d" + Config.defaultMap); HashMap teamLives = Cache.getTeamLives(); diff --git a/src/main/java/woolbattle/woolbattle/lobby/StartGameCommand.java b/src/main/java/woolbattle/woolbattle/lobby/StartGameCommand.java index f2c4cd4..bcf7cea 100644 --- a/src/main/java/woolbattle/woolbattle/lobby/StartGameCommand.java +++ b/src/main/java/woolbattle/woolbattle/lobby/StartGameCommand.java @@ -12,19 +12,20 @@ public class StartGameCommand implements CommandExecutor { /** * A Command that calls the startGame() method to start the game. + * * @author SimsumMC */ @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (sender instanceof Player) { Player player = (Player) sender; - if(!player.isOp()){ + if (!player.isOp()) { player.sendMessage(ChatColor.RED + "You need OP to use this command!"); return true; } - if (startGame()){ + if (startGame()) { player.sendMessage(ChatColor.GREEN + "Started the game."); - } else{ + } else { player.sendMessage(ChatColor.RED + "The game has already been started!"); } return true; diff --git a/src/main/java/woolbattle/woolbattle/lobby/StopGameCommand.java b/src/main/java/woolbattle/woolbattle/lobby/StopGameCommand.java index 823c1bb..b9e0be5 100644 --- a/src/main/java/woolbattle/woolbattle/lobby/StopGameCommand.java +++ b/src/main/java/woolbattle/woolbattle/lobby/StopGameCommand.java @@ -12,19 +12,20 @@ public class StopGameCommand implements CommandExecutor { /** * A Command that calls the endGame() method to stop the game. + * * @author SimsumMC */ @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (sender instanceof Player) { Player player = (Player) sender; - if(!player.isOp()){ + if (!player.isOp()) { player.sendMessage(ChatColor.RED + "You need OP to use this command!"); return true; } - if(endGame(ChatColor.YELLOW + "Yellow")){ + if (endGame(ChatColor.YELLOW + "Yellow")) { player.sendMessage("§aStopped the game successfully."); - } else{ + } else { player.sendMessage(ChatColor.RED + "There is no running game!"); } return true; diff --git a/src/main/java/woolbattle/woolbattle/woolsystem/BlockBreakingSystem.java b/src/main/java/woolbattle/woolbattle/map/BlockBreakingSystem.java similarity index 62% rename from src/main/java/woolbattle/woolbattle/woolsystem/BlockBreakingSystem.java rename to src/main/java/woolbattle/woolbattle/map/BlockBreakingSystem.java index a6ee873..43a5978 100644 --- a/src/main/java/woolbattle/woolbattle/woolsystem/BlockBreakingSystem.java +++ b/src/main/java/woolbattle/woolbattle/map/BlockBreakingSystem.java @@ -1,4 +1,4 @@ -package woolbattle.woolbattle.woolsystem; +package woolbattle.woolbattle.map; import com.mongodb.client.MongoDatabase; import org.bson.Document; @@ -6,7 +6,9 @@ import org.bukkit.block.Block; import woolbattle.woolbattle.Config; import woolbattle.woolbattle.Main; + import java.util.ArrayList; + import static com.mongodb.client.model.Filters.eq; import static java.lang.String.format; @@ -22,35 +24,50 @@ public class BlockBreakingSystem { //Setter and getter, concerning the previously defined private variables - public static boolean isCollectBrokenBlocks() {return collectBrokenBlocks;} - public static void setCollectBrokenBlocks(boolean collectBrokenBlocksArg) {collectBrokenBlocks = collectBrokenBlocksArg;} + public static boolean isCollectBrokenBlocks() { + return collectBrokenBlocks; + } + + public static void setCollectBrokenBlocks(boolean collectBrokenBlocksArg) { + collectBrokenBlocks = collectBrokenBlocksArg; + } + + public static ArrayList getMapBlocks() { + return mapBlocks; + } - public static ArrayList getMapBlocks() {return mapBlocks;} - public static void setMapBlocks(ArrayList mapBlocksArg) {mapBlocks = mapBlocksArg;} + public static void setMapBlocks(ArrayList mapBlocksArg) { + mapBlocks = mapBlocksArg; + } - public static ArrayList getRemovedBlocks() {return removedBlocks;} - public static void setRemovedBlocks(ArrayList removedBlocks) {BlockBreakingSystem.removedBlocks = removedBlocks;} + public static ArrayList getRemovedBlocks() { + return removedBlocks; + } + public static void setRemovedBlocks(ArrayList removedBlocks) { + BlockBreakingSystem.removedBlocks = removedBlocks; + } /** * Method, dedicated to clearing the mapBlocks array, stored in the specified database. + * * @author Servaturus - * */ - public static void clearDbMapBlocks(){ + */ + public static void clearDbMapBlocks() { MongoDatabase db = Main.getMongoClient().getDatabase("woolbattle"); db.getCollection("map"). replaceOne( - eq("_id", "mapBlocks"), - new Document("_id", "mapBlocks").append("mapBlocks", new ArrayList>()) - ); + eq("_id", "mapBlocks"), + new Document("_id", "mapBlocks").append("mapBlocks", new ArrayList>()) + ); } /** * Method that fetches stored mapBlocks from the db into the cached blocks array. - * @author Servaturus * + * @author Servaturus */ public static void fetchMapBlocks() { MongoDatabase db = Main.getMongoClient().getDatabase("woolbattle"); @@ -58,28 +75,28 @@ public static void fetchMapBlocks() { //Checks, whether the "map" collection and the "mapBlocks" documents exist in the db, creates them, if this is not the case. - if(!db.listCollectionNames().into(new ArrayList<>()).contains("map")){ + if (!db.listCollectionNames().into(new ArrayList<>()).contains("map")) { db.createCollection("map"); } Document found = db.getCollection("map").find(eq("_id", "mapBlocks")).first(); - if(found == null){ - db.getCollection("map").insertOne( new Document("_id", "mapBlocks").append("mapBlocks", new ArrayList>())); + if (found == null) { + db.getCollection("map").insertOne(new Document("_id", "mapBlocks").append("mapBlocks", new ArrayList>())); } //Iterates over the mapBlocks, present in the db, converts the into valid locations and ultimately add them to a previously created array. - for(ArrayList argArray: (ArrayList>) Main.getMongoDatabase().getCollection("map").find(eq("_id", "mapBlocks")).first().get("mapBlocks")/*db.getCollection("map").find(eq("_id", "mapBlocks")).first().get("mapBlocks")*/){ - if(argArray.size() == 0){ + for (ArrayList argArray : (ArrayList>) Main.getMongoDatabase().getCollection("map").find(eq("_id", "mapBlocks")).first().get("mapBlocks")/*db.getCollection("map").find(eq("_id", "mapBlocks")).first().get("mapBlocks")*/) { + if (argArray.size() == 0) { break; - }else { + } else { Location location = new Location( Bukkit.getWorlds().get(0), argArray.get(0), argArray.get(1), argArray.get(2) ); - if(updatedMapBlocks.contains(location)){ + if (updatedMapBlocks.contains(location)) { continue; } updatedMapBlocks.add(location); @@ -93,72 +110,73 @@ public static void fetchMapBlocks() { /** * Method pushing cached mapBlocks towards the specified database. + * * @author Servaturus */ - public static void pushMapBlocks(){ + public static void pushMapBlocks() { //Pushes the currently present cached blocks into the database. - if(mapBlocks.size() == 0){ + if (mapBlocks.size() == 0) { return; } - if(!Main.getMongoDatabase().listCollectionNames().into(new ArrayList<>()).contains("map")){ + if (!Main.getMongoDatabase().listCollectionNames().into(new ArrayList<>()).contains("map")) { Main.getMongoDatabase().createCollection("map"); } Document found = Main.getMongoDatabase().getCollection("map").find(eq("_id", "mapBlocks")).first(); - if(found == null){ + if (found == null) { Main.getMongoDatabase().getCollection("map").insertOne(new Document("_id", "mapBlocks").append("mapBlocks", new ArrayList>())); } //Fetches the stored mapBlocks from the db into a new array (update). - ArrayList> update = (ArrayList>) Main.getMongoDatabase().getCollection("map").find(eq("_id", "mapBlocks")).first().get("mapBlocks"); + ArrayList> update = (ArrayList>) Main.getMongoDatabase().getCollection("map").find(eq("_id", "mapBlocks")).first().get("mapBlocks"); - //Adds the cached blocks to the updated array, in case they are not already present in said collection. - - for(Location loc : mapBlocks){ - ArrayList locArray = new ArrayList(){ - { - add(loc.getX()); - add(loc.getY()); - add(loc.getZ()); - } - }; + //Adds the cached blocks to the updated array, in case they are not already present in said collection. - if(!update.contains(locArray)){ - update.add(locArray); + for (Location loc : mapBlocks) { + ArrayList locArray = new ArrayList() { + { + add(loc.getX()); + add(loc.getY()); + add(loc.getZ()); } + }; + if (!update.contains(locArray)) { + update.add(locArray); } - //Searches for blocks in the array, about to replace the mapBlocks-array in the db, that are present in the removed-blocks-array and deletes them. + } - for(ArrayList locArray : update){ - Location loc = new Location(Bukkit.getWorlds().get(0), locArray.get(0), locArray.get(1), locArray.get(2)); - if(removedBlocks.contains(loc)){ - update.remove(locArray); - } + //Searches for blocks in the array, about to replace the mapBlocks-array in the db, that are present in the removed-blocks-array and deletes them. + + for (ArrayList locArray : update) { + Location loc = new Location(Bukkit.getWorlds().get(0), locArray.get(0), locArray.get(1), locArray.get(2)); + if (removedBlocks.contains(loc)) { + update.remove(locArray); } + } - //Replaces the mapBlocksArray in the db with the previously-prepared one (update). - Main.getMongoDatabase().getCollection("map").replaceOne(eq("_id", "mapBlocks"), new Document("_id", "mapBlocks").append("mapBlocks", update)); + //Replaces the mapBlocksArray in the db with the previously-prepared one (update). + Main.getMongoDatabase().getCollection("map").replaceOne(eq("_id", "mapBlocks"), new Document("_id", "mapBlocks").append("mapBlocks", update)); } /** - * Method, meant to convert an array of locations towards an appropriately coloured string, representing it. + * Method, meant to convert an array of locations towards an appropriately coloured string, representing it. + * * @param locs The ArrayList of locations, meant to be converted into a string. * @return The string, generated according to the input ArrayList of locations. */ - public static String locArrayToString(ArrayList locs){ + public static String locArrayToString(ArrayList locs) { StringBuilder result = new StringBuilder(ChatColor.DARK_PURPLE + "["); - if(locs.size() == 0){ + if (locs.size() == 0) { result.append(format("%s]", ChatColor.DARK_PURPLE)); return result.toString(); - } - else{ + } else { - for(int i = 0; i locs){ green )); - if(i == (locs.size() -1)){ + if (i == (locs.size() - 1)) { result.append(format("%s]", ChatColor.DARK_PURPLE)); - }else{ + } else { result.append(format("%s,", ChatColor.AQUA)); } @@ -182,19 +200,20 @@ public static String locArrayToString(ArrayList locs){ } /** - * Method, meant to convert an array of ArrayList of doubles towards an appropriately coloured string, representing it. + * Method, meant to convert an array of ArrayList of doubles towards an appropriately coloured string, representing it. + * * @param locs The ArrayList of locations, meant to be converted into a string. * @return The String, corresponding with the specified input ArrayList of ArrayLists of doubles. */ - public static String doubleArrArrToString(ArrayList> locs){ + public static String doubleArrArrToString(ArrayList> locs) { StringBuilder result = new StringBuilder(ChatColor.DARK_PURPLE + "["); - if(locs.size() == 0){ + if (locs.size() == 0) { result.append(format("%s]", ChatColor.DARK_PURPLE)); return result.toString(); } - for(int i = 0; i> locs){ green )); - if(i == (locs.size() -1)){ + if (i == (locs.size() - 1)) { result.append(format("%s]", ChatColor.DARK_PURPLE)); - }else{ + } else { result.append(format("%s,", ChatColor.AQUA)); } @@ -218,6 +237,7 @@ public static String doubleArrArrToString(ArrayList> locs){ /** * Method, capable of adding locations to the local array of map-Blocks, using two input location-vectors. * The differences of these vectors in the respective dimensions serve as the height, width and depth of a volume of blocks, whose elements are added to the array of map-blocks. + * * @param a The location, specifying the origin vector of the range, used to add the blocks to the array of map-blocks. * @param b The location, specifying the end vector of the range, used to add the blocks to the array of map-blocks. * @author Servaturus @@ -236,43 +256,43 @@ public static void addBlocksByRange(Location a, Location b) { zs = new ArrayList<>(); //Adds every x value in the range of xdiff to the xs array. - if(Integer.signum(xdiff) == 0){ + if (Integer.signum(xdiff) == 0) { xs.add((int) b.getX()); - }else{ - for(int i = (int) b.getX(); ((Integer.signum(xdiff)) == -1)? (i>a.getX()) : (i a.getX()) : (i < a.getX()); i += Integer.signum(xdiff)) { xs.add(i); } } //Similar approach regarding ydiff and ys. - if(Integer.signum(ydiff) == 0){ + if (Integer.signum(ydiff) == 0) { xs.add((int) b.getX()); - }else{ - for(int i = (int) b.getY();((Integer.signum(ydiff)) == -1)? (i>a.getY()) : (i a.getY()) : (i < a.getY()); i += Integer.signum(ydiff)) { ys.add(i); } } //Another repetition in regard of zdiff and zs. - if(Integer.signum(zdiff) == 0){ + if (Integer.signum(zdiff) == 0) { zs.add((int) b.getZ()); - }else{ - for(int i = (int) b.getZ();((Integer.signum(zdiff)) == -1)? (i>a.getZ()) : (i a.getZ()) : (i < a.getZ()); i += Integer.signum(zdiff)) { zs.add(i); } } //Combines every element of xs with every element of y and the resulting combinations with every element of z. - for(int x : xs){ - for(int y : ys){ - for(int z : zs){ + for (int x : xs) { + for (int y : ys) { + for (int z : zs) { - if(new Location(standard, x, y, z).getBlock().getType().equals(Material.WOOL)){ + if (new Location(standard, x, y, z).getBlock().getType().equals(Material.WOOL)) { locs.add(new Location(standard, x, y, z)); } } } } //Adds locations, constituted by the former created value pairs (of xs, ys, and zs), to the global mapBlocks array. - for(Location l : locs){ - if(!mapBlocks.contains(l)){ + for (Location l : locs) { + if (!mapBlocks.contains(l)) { mapBlocks.add(l); } } @@ -281,32 +301,32 @@ public static void addBlocksByRange(Location a, Location b) { /** * Removes any wool blocks in a previously defined range of chunks, not belonging to the blocks of the same map, * defined in addition to that. - * @author Servaturus * + * @author Servaturus */ - public static void resetMap(){ + public static void resetMap() { Document doc = Main.getMongoDatabase().getCollection("map").find(eq("_id", "mapChunks")).first(); - if(doc == null){ + if (doc == null) { System.out.println("There are no chunks, belonging to the map, specified in the database"); return; } ArrayList> mapChunks = (ArrayList>) doc.get("chunks"); - if(mapChunks == null){ + if (mapChunks == null) { System.out.println("Couldn't reset map as there were no chunks, belonging to the map defined in the db.\nConsult /map def, in order to specify said ones."); return; } World world = Bukkit.getWorlds().get(0); - for(ArrayList chunkCoords : mapChunks){ - Chunk chunk = world.getChunkAt( (int) (long) chunkCoords.get(0), (int) (long) chunkCoords.get(1)); - for(int x = 0;x<16;x++){ - for(int y = 0; y< Config.maxHeight; y++){ - for(int z = 0; z<16;z++){ - Block block = chunk.getBlock(x,y,z); - if(!block.getType().equals(Material.WOOL)){ + for (ArrayList chunkCoords : mapChunks) { + Chunk chunk = world.getChunkAt((int) (long) chunkCoords.get(0), (int) (long) chunkCoords.get(1)); + for (int x = 0; x < 16; x++) { + for (int y = 0; y < Config.maxHeight; y++) { + for (int z = 0; z < 16; z++) { + Block block = chunk.getBlock(x, y, z); + if (!block.getType().equals(Material.WOOL)) { continue; } - if(mapBlocks.contains(block.getLocation())){ + if (mapBlocks.contains(block.getLocation())) { continue; } diff --git a/src/main/java/woolbattle/woolbattle/woolsystem/BlockRegistrationCommand.java b/src/main/java/woolbattle/woolbattle/map/BlockRegistrationCommand.java similarity index 97% rename from src/main/java/woolbattle/woolbattle/woolsystem/BlockRegistrationCommand.java rename to src/main/java/woolbattle/woolbattle/map/BlockRegistrationCommand.java index 3beb4e8..271e775 100644 --- a/src/main/java/woolbattle/woolbattle/woolsystem/BlockRegistrationCommand.java +++ b/src/main/java/woolbattle/woolbattle/map/BlockRegistrationCommand.java @@ -1,6 +1,5 @@ -package woolbattle.woolbattle.woolsystem; +package woolbattle.woolbattle.map; -import java.util.Locale; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Location; @@ -50,7 +49,7 @@ public boolean onCommand(CommandSender sender, Command command, String label, St "command to work properly." + syntax ); return false; - }else { + } else { try { Location start = new Location(Bukkit.getWorlds().get(0), Double.parseDouble(args[1].toLowerCase()), Double.parseDouble(args[2].toLowerCase()), Double.parseDouble(args[3].toLowerCase())); diff --git a/src/main/java/woolbattle/woolbattle/Listener.java b/src/main/java/woolbattle/woolbattle/map/Listener.java similarity index 82% rename from src/main/java/woolbattle/woolbattle/Listener.java rename to src/main/java/woolbattle/woolbattle/map/Listener.java index 4efa9be..9d607eb 100644 --- a/src/main/java/woolbattle/woolbattle/Listener.java +++ b/src/main/java/woolbattle/woolbattle/map/Listener.java @@ -1,4 +1,4 @@ -package woolbattle.woolbattle; +package woolbattle.woolbattle.map; import org.bukkit.*; import org.bukkit.block.Block; @@ -14,8 +14,10 @@ import org.bukkit.inventory.ItemStack; import org.bukkit.material.Colorable; import org.bukkit.scheduler.BukkitRunnable; +import woolbattle.woolbattle.Cache; +import woolbattle.woolbattle.Config; +import woolbattle.woolbattle.Main; import woolbattle.woolbattle.achievements.AchievementSystem; -import woolbattle.woolbattle.woolsystem.BlockBreakingSystem; import java.util.ArrayList; @@ -25,7 +27,7 @@ public class Listener implements org.bukkit.event.Listener { /** * @param event The spigot-api's event class, specifying, to which occasion the method is called and delivering - * information, concerning these circumstances. + * information, concerning these circumstances. */ @EventHandler public void onBlockBreak(BlockBreakEvent event) { @@ -33,7 +35,7 @@ public void onBlockBreak(BlockBreakEvent event) { Player p = event.getPlayer(); //Checks, whether the player, having broken the event's block is in the creative, or spectator mode, returns if //this is the case - if(p.getGameMode().equals(GameMode.CREATIVE) || p.getGameMode().equals(GameMode.SPECTATOR)){ + if (p.getGameMode().equals(GameMode.CREATIVE) || p.getGameMode().equals(GameMode.SPECTATOR)) { return; } @@ -44,7 +46,8 @@ public void onBlockBreak(BlockBreakEvent event) { DyeColor teamColor = findTeamDyeColor(p);//Is to be implemented in the team-system, being created Inventory inventory = p.getInventory(); Block block = event.getBlock(); - ItemStack itemStack = new ItemStack(Material.WOOL, 0, teamColor.getWoolData()){}; + ItemStack itemStack = new ItemStack(Material.WOOL, 0, teamColor.getWoolData()) { + }; Material type = block.getType(); boolean blockIsMap = false; int itemAmount = 0; @@ -54,8 +57,8 @@ public void onBlockBreak(BlockBreakEvent event) { int delayInTicks = Config.woolReplaceDelay; //Checks, whether the event's block is specified in the internal array of map-blocks, writes the value of the operation in the boolean blockIsMap. - for(Location iterBlock : BlockBreakingSystem.getMapBlocks()){ - if(iterBlock.equals(block.getLocation())){ + for (Location iterBlock : BlockBreakingSystem.getMapBlocks()) { + if (iterBlock.equals(block.getLocation())) { blockIsMap = true; break; } @@ -64,11 +67,11 @@ public void onBlockBreak(BlockBreakEvent event) { //Checks, whether a modification of the map's blocks, following the action of breaking a block is to be made. // If this is not the case, and if the broken block possesses the wool material as it's type, it is replaced // after cooldown and an amount of - if(BlockBreakingSystem.isCollectBrokenBlocks()){ + if (BlockBreakingSystem.isCollectBrokenBlocks()) { ArrayList mapBlocks = BlockBreakingSystem.getMapBlocks(); ArrayList removedBlocks = BlockBreakingSystem.getRemovedBlocks(); - if(mapBlocks.contains(block.getLocation())){ + if (mapBlocks.contains(block.getLocation())) { mapBlocks.remove(block.getLocation()); BlockBreakingSystem.setMapBlocks(mapBlocks); @@ -77,24 +80,24 @@ public void onBlockBreak(BlockBreakEvent event) { Bukkit.broadcastMessage("Removed Blocks: " + BlockBreakingSystem.locArrayToString(BlockBreakingSystem.getRemovedBlocks())); } - }else{ + } else { event.setCancelled(true); - if(type.equals(Material.WOOL)){ + if (type.equals(Material.WOOL)) { - for(ItemStack is : inventory){ - if(is != null){ - itemAmount += is.getType().equals(Material.WOOL)? is.getAmount() : 0; + for (ItemStack is : inventory) { + if (is != null) { + itemAmount += is.getType().equals(Material.WOOL) ? is.getAmount() : 0; } } itemStack.setType(type); - if(itemAmount < maxStacks*64){ + if (itemAmount < maxStacks * 64) { itemStack.setAmount(givenWoolAmount); inventory.addItem(itemStack); Cache.getPassivePerks().values().forEach(perk -> { - if(perk.hasPlayer(p)){ + if (perk.hasPlayer(p)) { perk.functionality(event); } }); @@ -103,9 +106,9 @@ public void onBlockBreak(BlockBreakEvent event) { Colorable data = (Colorable) block.getState().getData(); block.setType(Material.AIR); - if(blockIsMap){ + if (blockIsMap) { - new BukkitRunnable(){ + new BukkitRunnable() { @Override public void run() { block.setType(Material.WOOL); @@ -123,15 +126,16 @@ public void onPlayerItemDamage(PlayerItemDamageEvent event) { } /** - * The block, placed, in case a block-scanning-process is occurring, is, if it is contained by either the array of - * map blocks or the array of removed blocks, purged from the latter and added to the first one. - *@param event The spigot-api's event class, specifying, to which occasion the method is called and delivering + * The block, placed, in case a block-scanning-process is occurring, is, if it is contained by either the array of + * map blocks or the array of removed blocks, purged from the latter and added to the first one. + * + * @param event The spigot-api's event class, specifying, to which occasion the method is called and delivering * information, concerning these circumstances. */ @EventHandler public void onBlockPlace(BlockPlaceEvent event) { - if(BlockBreakingSystem.isCollectBrokenBlocks()){ + if (BlockBreakingSystem.isCollectBrokenBlocks()) { ArrayList mapBlocks = BlockBreakingSystem.getMapBlocks(); mapBlocks.add(event.getBlockPlaced().getLocation()); @@ -160,7 +164,7 @@ public void onBlockPlace(BlockPlaceEvent event) { public void onPlayerToggleFlight(PlayerToggleFlightEvent event) { Player p = event.getPlayer(); - if(p.getGameMode() == GameMode.CREATIVE || p.getGameMode() == GameMode.SPECTATOR || p.isFlying()){ + if (p.getGameMode() == GameMode.CREATIVE || p.getGameMode() == GameMode.SPECTATOR || p.isFlying()) { return; } @@ -172,13 +176,13 @@ public void onPlayerToggleFlight(PlayerToggleFlightEvent event) { long jumpCooldown; - try{ + try { jumpCooldown = Config.jumpCooldown; - }catch(ExceptionInInitializerError e){ + } catch (ExceptionInInitializerError e) { jumpCooldown = 40; } - new BukkitRunnable(){ + new BukkitRunnable() { @Override public void run() { p.setAllowFlight(true); @@ -209,9 +213,9 @@ public void onPlayerGameModeChange(PlayerGameModeChangeEvent event) { p.setAllowFlight(true); - new BukkitRunnable(){ + new BukkitRunnable() { @Override - public void run(){ + public void run() { p.setAllowFlight(true); } diff --git a/src/main/java/woolbattle/woolbattle/woolsystem/MapBlocksCommand.java b/src/main/java/woolbattle/woolbattle/map/MapBlocksCommand.java similarity index 82% rename from src/main/java/woolbattle/woolbattle/woolsystem/MapBlocksCommand.java rename to src/main/java/woolbattle/woolbattle/map/MapBlocksCommand.java index 93f0252..3711718 100644 --- a/src/main/java/woolbattle/woolbattle/woolsystem/MapBlocksCommand.java +++ b/src/main/java/woolbattle/woolbattle/map/MapBlocksCommand.java @@ -1,4 +1,5 @@ -package woolbattle.woolbattle.woolsystem; +package woolbattle.woolbattle.map; + import org.bson.BsonValue; import org.bson.Document; import org.bukkit.ChatColor; @@ -7,8 +8,10 @@ import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import woolbattle.woolbattle.Main; + import java.util.ArrayList; import java.util.Locale; + import static com.mongodb.client.model.Filters.eq; public class MapBlocksCommand implements CommandExecutor { @@ -17,25 +20,21 @@ public class MapBlocksCommand implements CommandExecutor { @Override public boolean onCommand(CommandSender sender, Command command, String s, String[] args) { - if(args.length <1){ + if (args.length < 1) { sender.sendMessage(ChatColor.RED + "The arguments, added to the command are not portraying\nthe amount of information, needed in order for the command\nto work.\n" + syntax ); return false; - } - - else if(args.length>2){ - sender.sendMessage(ChatColor.RED+ - "The amount of arguments, sent to use this command\nhas been to high.\n"+ + } else if (args.length > 2) { + sender.sendMessage(ChatColor.RED + + "The amount of arguments, sent to use this command\nhas been to high.\n" + syntax ); return false; - } - - else{ - switch(args[0].toLowerCase(Locale.ROOT)){ + } else { + switch (args[0].toLowerCase(Locale.ROOT)) { case "fetch": sender.sendMessage(ChatColor.GREEN + "Initiating fetching process..."); int previousSize = BlockBreakingSystem.getMapBlocks().size(); @@ -43,12 +42,12 @@ else if(args.length>2){ sender.sendMessage(ChatColor.GREEN + "In advance of the fetching process, there were " + - ChatColor.BLUE+ - previousSize+ - ChatColor.GREEN+ - " mapBlocks.\nThe current amount of them is equal to "+ ChatColor.BLUE + - BlockBreakingSystem.getMapBlocks().size()+ + previousSize + + ChatColor.GREEN + + " mapBlocks.\nThe current amount of them is equal to " + + ChatColor.BLUE + + BlockBreakingSystem.getMapBlocks().size() + ChatColor.GREEN + "." ); @@ -59,7 +58,7 @@ else if(args.length>2){ int previousSizeDb; Document found = Main.getMongoDatabase().getCollection("map").find(eq("_id", "mapBlocks")).first(); - if(found == null){ + if (found == null) { previousSizeDb = 0; Main.getMongoDatabase().getCollection("map").insertOne(new Document("_id", "mapBlocks").append("mapBlocks", new ArrayList<>())); } @@ -70,7 +69,7 @@ else if(args.length>2){ previousSizeDb = 0; }*/ - else{ + else { previousSizeDb = ((ArrayList) Main.getMongoDatabase(). getCollection("map"). find(eq("_id", "mapBlocks")). @@ -81,34 +80,34 @@ else if(args.length>2){ BlockBreakingSystem.pushMapBlocks(); - int currentSize= ((ArrayList) Main.getMongoDatabase(). + int currentSize = ((ArrayList) Main.getMongoDatabase(). getCollection("map"). find(eq("_id", "mapBlocks")). first(). get("mapBlocks")).size(); sender.sendMessage(ChatColor.GREEN + - "The blocks having been pushed are equal to "+ - ChatColor.BLUE+ - previousSizeCached+ - ChatColor.GREEN+ - " .\nThe blocks, stored in the plugin's database in advance of the pushing process were equal to "+ - ChatColor.BLUE+ - previousSizeDb+ - ChatColor.GREEN+ - " .\nThe blocks, present in the database, in this moment are equal to "+ - ChatColor.BLUE+ - currentSize+ - ChatColor.GREEN+ + "The blocks having been pushed are equal to " + + ChatColor.BLUE + + previousSizeCached + + ChatColor.GREEN + + " .\nThe blocks, stored in the plugin's database in advance of the pushing process were equal to " + + ChatColor.BLUE + + previousSizeDb + + ChatColor.GREEN + + " .\nThe blocks, present in the database, in this moment are equal to " + + ChatColor.BLUE + + currentSize + + ChatColor.GREEN + "." ); break; case "ls": - if(args.length !=2){ + if (args.length != 2) { sender.sendMessage(ChatColor.RED + "The amount of arguments specified is not congruent with the one needed. " + syntax); } - switch(args[1].toLowerCase(Locale.ROOT)){ + switch (args[1].toLowerCase(Locale.ROOT)) { case "db": sender.sendMessage(ChatColor.GREEN + "The following array-like string is standing on behalf of the blocks, currently present in the mapBlocks collection of the db:\n" + BlockBreakingSystem.doubleArrArrToString((ArrayList>) Main. @@ -131,14 +130,13 @@ else if(args.length>2){ break; case "clear": - if(args.length < 2) { + if (args.length < 2) { sender.sendMessage(ChatColor.RED + "The arguments, added to the command are not portraying\n" + "the amount of information, needed in order for the command\n" + - "to work.\n"+ + "to work.\n" + syntax); - } - else{ - switch(args[1].toLowerCase(Locale.ROOT)){ + } else { + switch (args[1].toLowerCase(Locale.ROOT)) { case "db": sender.sendMessage(ChatColor.GREEN + "Clearing the mapBlocks, stored in the db..."); BlockBreakingSystem.clearDbMapBlocks(); diff --git a/src/main/java/woolbattle/woolbattle/maprestaurationsystem/MapCommand.java b/src/main/java/woolbattle/woolbattle/map/MapCommand.java similarity index 65% rename from src/main/java/woolbattle/woolbattle/maprestaurationsystem/MapCommand.java rename to src/main/java/woolbattle/woolbattle/map/MapCommand.java index 76f01c9..39ea595 100644 --- a/src/main/java/woolbattle/woolbattle/maprestaurationsystem/MapCommand.java +++ b/src/main/java/woolbattle/woolbattle/map/MapCommand.java @@ -1,69 +1,68 @@ -package woolbattle.woolbattle.maprestaurationsystem; - -import org.bukkit.Bukkit; -import org.bukkit.ChatColor; -import org.bukkit.World; -import org.bukkit.command.Command; -import org.bukkit.command.CommandExecutor; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; -import woolbattle.woolbattle.woolsystem.BlockBreakingSystem; - -import java.util.ArrayList; -import java.util.UUID; - -public class MapCommand implements CommandExecutor { - - @Override - public boolean onCommand(CommandSender commandSender, Command command, String s, String[] args) { - final String usage = "/map "; - if(!(args.length > 0)){ - - return false; - } - switch(args[0]){ - case "def": - World world = null; - if(args.length == 6){ - try{ - world = Bukkit.getWorld(UUID.fromString(args[5])); - }catch(NullPointerException e){ - System.out.println(world); - } - - }else if(args.length==5){ - if(commandSender instanceof Player){ - world = ((Player) commandSender).getWorld(); - }else{ - world = Bukkit.getWorlds().get(0); - } - - }else{ - commandSender.sendMessage("The specified number of arguments is either to low, or to high, in order to be" - + " parsed. Usage: " + usage); - return false; - } - ArrayList> chunks; - try{ - chunks = MapSystem.getChunksInRange(world, - - Long.parseLong(args[1]), - Long.parseLong(args[2]), - Long.parseLong(args[3]), - Long.parseLong(args[4]) - ); - }catch(NumberFormatException e){ - commandSender.sendMessage(ChatColor.RED + "One of the latter 4 arguments does not seem to possess the right format (integer), to be parsed properly."); - return false; - } - System.out.println("is called\n\n"); - MapSystem.defineMapChunks(chunks); - break; - case "reset": - BlockBreakingSystem.resetMap(); - break; - } - - return false; - } +package woolbattle.woolbattle.map; + +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.World; +import org.bukkit.command.Command; +import org.bukkit.command.CommandExecutor; +import org.bukkit.command.CommandSender; +import org.bukkit.entity.Player; + +import java.util.ArrayList; +import java.util.UUID; + +public class MapCommand implements CommandExecutor { + + @Override + public boolean onCommand(CommandSender commandSender, Command command, String s, String[] args) { + final String usage = "/map "; + if (!(args.length > 0)) { + + return false; + } + switch (args[0]) { + case "def": + World world = null; + if (args.length == 6) { + try { + world = Bukkit.getWorld(UUID.fromString(args[5])); + } catch (NullPointerException e) { + System.out.println(world); + } + + } else if (args.length == 5) { + if (commandSender instanceof Player) { + world = ((Player) commandSender).getWorld(); + } else { + world = Bukkit.getWorlds().get(0); + } + + } else { + commandSender.sendMessage("The specified number of arguments is either to low, or to high, in order to be" + + " parsed. Usage: " + usage); + return false; + } + ArrayList> chunks; + try { + chunks = MapSystem.getChunksInRange(world, + + Long.parseLong(args[1]), + Long.parseLong(args[2]), + Long.parseLong(args[3]), + Long.parseLong(args[4]) + ); + } catch (NumberFormatException e) { + commandSender.sendMessage(ChatColor.RED + "One of the latter 4 arguments does not seem to possess the right format (integer), to be parsed properly."); + return false; + } + System.out.println("is called\n\n"); + MapSystem.defineMapChunks(chunks); + break; + case "reset": + BlockBreakingSystem.resetMap(); + break; + } + + return false; + } } \ No newline at end of file diff --git a/src/main/java/woolbattle/woolbattle/maprestaurationsystem/MapSystem.java b/src/main/java/woolbattle/woolbattle/map/MapSystem.java similarity index 69% rename from src/main/java/woolbattle/woolbattle/maprestaurationsystem/MapSystem.java rename to src/main/java/woolbattle/woolbattle/map/MapSystem.java index 659795c..fb35d4a 100644 --- a/src/main/java/woolbattle/woolbattle/maprestaurationsystem/MapSystem.java +++ b/src/main/java/woolbattle/woolbattle/map/MapSystem.java @@ -1,61 +1,63 @@ -package woolbattle.woolbattle.maprestaurationsystem; - -import org.bson.Document; -import org.bukkit.Bukkit; -import org.bukkit.World; -import woolbattle.woolbattle.Main; -import java.util.ArrayList; -import static com.mongodb.client.model.Filters.eq; - - -public class MapSystem { - - public static void defineMapChunks(ArrayList> chunks){ - - if(Main.getMongoDatabase().getCollection("map").find(eq("_id", "mapChunks")).first() == null){ - Main.getMongoDatabase().getCollection("map").insertOne(new Document("_id", "mapChunks").append("chunks", new ArrayList>())); - } - - ArrayList> dbChunks; - try{ - dbChunks = (ArrayList>) Main.getMongoDatabase().getCollection("map").find(eq("_id", "mapChunks")).first().get("chunks"); - - }catch(ClassCastException e){ - System.out.println("The value of the chunks, belonging to the map, stored in the database consists of a value, not capable of being cast to an ArrayList."); - dbChunks = new ArrayList<>(); - } - - - if(dbChunks != null && dbChunks.size() >0 ){ - for(ArrayList chunk : dbChunks){ - if (!chunks.contains(chunk)) { - chunks.add(chunk); - } - } - } - - Document chunkDoc = new Document("_id", "mapChunks").append("chunks", chunks); - Main.getMongoDatabase().getCollection("map").replaceOne(eq("_id", "mapChunks"), chunkDoc); - } - - public static ArrayList> getChunksInRange(World world /*temporary undefined parameter, to be modified in the future*/, long bx, long by, long ex, long ey){ - - boolean bxGreaterEqualsEx= bx>=ex; - boolean byGreaterEqualsEy = by>=ey; - ArrayList> result = new ArrayList<>(); - for(long i = (bxGreaterEqualsEx)? ex : bx; (bxGreaterEqualsEx)? i iterChunk = new ArrayList<>(); - iterChunk.add(i); - iterChunk.add(j); - result.add(iterChunk); - Bukkit.broadcastMessage("[" + i + ", " + j + "]"); - } - } - return result; - } - - public static void clearMapChunks(){ - - } +package woolbattle.woolbattle.map; + +import org.bson.Document; +import org.bukkit.Bukkit; +import org.bukkit.World; +import woolbattle.woolbattle.Main; + +import java.util.ArrayList; + +import static com.mongodb.client.model.Filters.eq; + + +public class MapSystem { + + public static void defineMapChunks(ArrayList> chunks) { + + if (Main.getMongoDatabase().getCollection("map").find(eq("_id", "mapChunks")).first() == null) { + Main.getMongoDatabase().getCollection("map").insertOne(new Document("_id", "mapChunks").append("chunks", new ArrayList>())); + } + + ArrayList> dbChunks; + try { + dbChunks = (ArrayList>) Main.getMongoDatabase().getCollection("map").find(eq("_id", "mapChunks")).first().get("chunks"); + + } catch (ClassCastException e) { + System.out.println("The value of the chunks, belonging to the map, stored in the database consists of a value, not capable of being cast to an ArrayList."); + dbChunks = new ArrayList<>(); + } + + + if (dbChunks != null && dbChunks.size() > 0) { + for (ArrayList chunk : dbChunks) { + if (!chunks.contains(chunk)) { + chunks.add(chunk); + } + } + } + + Document chunkDoc = new Document("_id", "mapChunks").append("chunks", chunks); + Main.getMongoDatabase().getCollection("map").replaceOne(eq("_id", "mapChunks"), chunkDoc); + } + + public static ArrayList> getChunksInRange(World world /*temporary undefined parameter, to be modified in the future*/, long bx, long by, long ex, long ey) { + + boolean bxGreaterEqualsEx = bx >= ex; + boolean byGreaterEqualsEy = by >= ey; + ArrayList> result = new ArrayList<>(); + for (long i = (bxGreaterEqualsEx) ? ex : bx; (bxGreaterEqualsEx) ? i < bx : i < ex; i++) { + for (long j = (byGreaterEqualsEy) ? ey : by; (byGreaterEqualsEy) ? j < by : j < ey; j++) { + ArrayList iterChunk = new ArrayList<>(); + iterChunk.add(i); + iterChunk.add(j); + result.add(iterChunk); + Bukkit.broadcastMessage("[" + i + ", " + j + "]"); + } + } + return result; + } + + public static void clearMapChunks() { + + } } \ No newline at end of file diff --git a/src/main/java/woolbattle/woolbattle/perks/ActivePerk.java b/src/main/java/woolbattle/woolbattle/perks/ActivePerk.java index c9f4f29..c2fe4d9 100644 --- a/src/main/java/woolbattle/woolbattle/perks/ActivePerk.java +++ b/src/main/java/woolbattle/woolbattle/perks/ActivePerk.java @@ -20,7 +20,7 @@ import java.util.HashMap; import static com.mongodb.client.model.Filters.eq; -import static woolbattle.woolbattle.itemsystem.ItemSystem.*; +import static woolbattle.woolbattle.items.ItemSystem.*; public class ActivePerk { private ItemStack itemStack; @@ -65,7 +65,7 @@ public int getCooldown() { return cooldown; } - public boolean getSelectableStatus(){ + public boolean getSelectableStatus() { return selectable; } @@ -78,7 +78,7 @@ public ActivePerk setDescription(String description) { return this; } - public ActivePerk setItemName(String name){ + public ActivePerk setItemName(String name) { ItemMeta itemMeta = itemStack.getItemMeta(); itemMeta.setDisplayName(name); itemStack.setItemMeta(itemMeta); @@ -86,11 +86,11 @@ public ActivePerk setItemName(String name){ return this; } - public ActivePerk addEnchantment(Enchantment enchantment, int level, boolean invisible){ + public ActivePerk addEnchantment(Enchantment enchantment, int level, boolean invisible) { ItemMeta itemMeta = itemStack.getItemMeta(); itemMeta.addEnchant(enchantment, level, true); - if(invisible){ + if (invisible) { itemMeta.addItemFlags(ItemFlag.HIDE_ENCHANTS); } @@ -99,31 +99,31 @@ public ActivePerk addEnchantment(Enchantment enchantment, int level, boolean inv return this; } - public ActivePerk addEnchantment(Enchantment enchantment, boolean invisible){ - return addEnchantment(enchantment,1, invisible); + public ActivePerk addEnchantment(Enchantment enchantment, boolean invisible) { + return addEnchantment(enchantment, 1, invisible); } - public void register(){ + public void register() { HashMap activePerks = Cache.getActivePerks(); activePerks.put(itemName.substring(2), this); Cache.setActivePerks(activePerks); } - public void execute(PlayerInteractEvent event, Player player){ - if(!useOnExecute){ + public void execute(PlayerInteractEvent event, Player player) { + if (!useOnExecute) { return; } int slot = getSlotCache(player); - if(!subtractWool(player, woolCost)){ + if (!subtractWool(player, woolCost)) { event.setCancelled(true); player.playNote(player.getLocation(), Instrument.PIANO, Note.flat(1, Note.Tone.C)); player.playNote(player.getLocation(), Instrument.PIANO, Note.flat(1, Note.Tone.B)); return; } - if(cooldown != 0){ + if (cooldown != 0) { setItemCooldown(player, slot, itemStack, cooldown); } @@ -132,10 +132,12 @@ public void execute(PlayerInteractEvent event, Player player){ StatsSystem.addActivePerkUsage(player); } - public void onExecute(PlayerInteractEvent event, Player player) {} + public void onExecute(PlayerInteractEvent event, Player player) { + } /** * A Method that returns the Slot of the Active Perk. -> normally from the cache + * * @param player - the player of the perk * @author SimsumMC */ @@ -144,7 +146,7 @@ public int getSlotCache(Player player) { HashMap> activePerkSlots = Cache.getActivePerkSlots(); - if(!activePerkSlots.containsKey(player) || !activePerkSlots.get(player).containsKey(activePerkName)){ + if (!activePerkSlots.containsKey(player) || !activePerkSlots.get(player).containsKey(activePerkName)) { return getSlotDB(player); } @@ -153,10 +155,11 @@ public int getSlotCache(Player player) { /** * A Method that returns the Slot of the Active Perk. -> directly from the database + * * @param player - the player of the perk * @author SimsumMC */ - private int getSlotDB(Player player){ + private int getSlotDB(Player player) { String activePerkName = this.itemName.substring(2); MongoDatabase database = Main.getMongoDatabase(); @@ -171,25 +174,22 @@ private int getSlotDB(Player player){ int perk1Slot; int perk2Slot; - if(foundDocument == null){ + if (foundDocument == null) { shearsSlot = defaultSlots.get("shears"); bowSlot = defaultSlots.get("bow"); enderPearlSlot = defaultSlots.get("enderpearl"); perk1Slot = defaultSlots.get("perk1"); perk2Slot = defaultSlots.get("perk2"); - } - else{ - if(foundDocument.get("active_perk1") instanceof Integer){ + } else { + if (foundDocument.get("active_perk1") instanceof Integer) { perk1Slot = (int) foundDocument.get("active_perk1"); - } - else { + } else { perk1Slot = defaultSlots.get("perk1"); } - if(foundDocument.get("active_perk2") instanceof Integer){ + if (foundDocument.get("active_perk2") instanceof Integer) { perk2Slot = (int) foundDocument.get("active_perk2"); - } - else { + } else { perk2Slot = defaultSlots.get("perk2"); } @@ -198,14 +198,14 @@ private int getSlotDB(Player player){ enderPearlSlot = (int) foundDocument.get("ender_pearl"); } - if(!this.selectable){ - if(activePerkName.equals("Shears")){ + if (!this.selectable) { + if (activePerkName.equals("Shears")) { return shearsSlot; } - if(activePerkName.equals("Bow")){ + if (activePerkName.equals("Bow")) { return bowSlot; } - if(activePerkName.equals("Ender Pearl")){ + if (activePerkName.equals("Ender Pearl")) { return enderPearlSlot; } } @@ -214,21 +214,21 @@ private int getSlotDB(Player player){ Document perksDocument = perksCollection.find(eq("_id", player.getUniqueId().toString())).first(); - if(perksDocument != null) { + if (perksDocument != null) { String activePerk1String; String activePerk2String; - if (perksDocument.get("first_active") != null){ + if (perksDocument.get("first_active") != null) { activePerk1String = (String) perksDocument.get("first_active"); - if(activePerk1String.equals(activePerkName)) { + if (activePerk1String.equals(activePerkName)) { return perk1Slot; } } - if (perksDocument.get("second_active") != null){ + if (perksDocument.get("second_active") != null) { activePerk2String = (String) perksDocument.get("second_active"); - if(activePerk2String.equals(activePerkName)) { + if (activePerk2String.equals(activePerkName)) { return perk2Slot; } } @@ -239,9 +239,10 @@ private int getSlotDB(Player player){ /** * A Method that puts all the slots from all active perks for every player in a HashMap, in the so-called "Cache" * to reduce database calls. + * * @author SimsumMC */ - public static void loadActivePerkSlots(){ + public static void loadActivePerkSlots() { MongoDatabase database = Main.getMongoDatabase(); MongoCollection collection = database.getCollection("playerInventories"); @@ -249,7 +250,7 @@ public static void loadActivePerkSlots(){ Collection onlinePlayers = Bukkit.getOnlinePlayers(); - for(Player player : onlinePlayers){ + for (Player player : onlinePlayers) { Document foundDocument = collection.find(eq("_id", player.getUniqueId().toString())).first(); int shearsSlot; @@ -258,25 +259,22 @@ public static void loadActivePerkSlots(){ int perk1Slot; int perk2Slot; - if(foundDocument == null){ + if (foundDocument == null) { shearsSlot = defaultSlots.get("shears"); bowSlot = defaultSlots.get("bow"); enderPearlSlot = defaultSlots.get("enderpearl"); perk1Slot = defaultSlots.get("perk1"); perk2Slot = defaultSlots.get("perk2"); - } - else{ - if(foundDocument.get("active_perk1") instanceof Integer){ + } else { + if (foundDocument.get("active_perk1") instanceof Integer) { perk1Slot = (int) foundDocument.get("active_perk1"); - } - else { + } else { perk1Slot = defaultSlots.get("perk1"); } - if(foundDocument.get("active_perk2") instanceof Integer){ + if (foundDocument.get("active_perk2") instanceof Integer) { perk2Slot = (int) foundDocument.get("active_perk2"); - } - else { + } else { perk2Slot = defaultSlots.get("perk2"); } @@ -293,18 +291,18 @@ public static void loadActivePerkSlots(){ Document perksDocument = perksCollection.find(eq("_id", player.getUniqueId().toString())).first(); - if(perksDocument != null) { + if (perksDocument != null) { String activePerk1String; String activePerk2String; - if (perksDocument.get("first_active") != null){ + if (perksDocument.get("first_active") != null) { activePerk1String = (String) perksDocument.get("first_active"); playerSlots.put(activePerk1String, perk1Slot); } - if (perksDocument.get("second_active") != null){ + if (perksDocument.get("second_active") != null) { activePerk2String = (String) perksDocument.get("second_active"); playerSlots.put(activePerk2String, perk2Slot); } diff --git a/src/main/java/woolbattle/woolbattle/perks/AllActivePerks.java b/src/main/java/woolbattle/woolbattle/perks/AllActivePerks.java index e8b30ad..30f8c6b 100644 --- a/src/main/java/woolbattle/woolbattle/perks/AllActivePerks.java +++ b/src/main/java/woolbattle/woolbattle/perks/AllActivePerks.java @@ -20,8 +20,8 @@ import java.util.HashMap; import static woolbattle.woolbattle.base.Base.addEnderPearl; -import static woolbattle.woolbattle.itemsystem.ItemSystem.setItemCooldown; -import static woolbattle.woolbattle.itemsystem.ItemSystem.subtractWool; +import static woolbattle.woolbattle.items.ItemSystem.setItemCooldown; +import static woolbattle.woolbattle.items.ItemSystem.subtractWool; import static woolbattle.woolbattle.lives.LivesSystem.teleportPlayerTeamSpawn; import static woolbattle.woolbattle.team.TeamSystem.*; @@ -30,25 +30,22 @@ public class AllActivePerks implements Listener { @EventHandler(ignoreCancelled = true) public void onProjectileLaunch(ProjectileLaunchEvent event) { Projectile projectile = event.getEntity(); - if(!(event.getEntity().getShooter() instanceof Player)){ + if (!(event.getEntity().getShooter() instanceof Player)) { return; } Player player = (Player) projectile.getShooter(); - if(projectile.getType() == EntityType.SNOWBALL || projectile.getType() == EntityType.ENDER_PEARL || - projectile.getType() == EntityType.ARROW || projectile.getType() == EntityType.EGG){ + if (projectile.getType() == EntityType.SNOWBALL || projectile.getType() == EntityType.ENDER_PEARL || + projectile.getType() == EntityType.ARROW || projectile.getType() == EntityType.EGG) { String perkName; - if(projectile.getType() == EntityType.SNOWBALL){ + if (projectile.getType() == EntityType.SNOWBALL) { perkName = "Exchanger"; - } - else if(projectile.getType() == EntityType.ARROW){ + } else if (projectile.getType() == EntityType.ARROW) { perkName = "Bow"; - } - else if(projectile.getType() == EntityType.EGG){ + } else if (projectile.getType() == EntityType.EGG) { perkName = "Egg"; - } - else{ + } else { perkName = "Ender Pearl"; } @@ -60,23 +57,22 @@ else if(projectile.getType() == EntityType.EGG){ int cooldown = perk.getCooldown(); int perkSlot = perk.getSlotCache(player); - if(!(projectile.getType() == EntityType.ARROW)) { + if (!(projectile.getType() == EntityType.ARROW)) { player.getInventory().setItem(perkSlot, itemStack); } - if(!subtractWool(player, woolCost)){ + if (!subtractWool(player, woolCost)) { event.setCancelled(true); projectile.remove(); player.playNote(player.getLocation(), Instrument.PIANO, Note.flat(1, Note.Tone.C)); player.playNote(player.getLocation(), Instrument.PIANO, Note.flat(1, Note.Tone.B)); - } - else{ - if(cooldown != 0) { + } else { + if (cooldown != 0) { setItemCooldown(player, perkSlot, itemStack, cooldown); StatsSystem.addActivePerkUsage(player); } - if(perkName.equals("Ender Pearl")){ + if (perkName.equals("Ender Pearl")) { addEnderPearl((EnderPearl) projectile); } } @@ -85,13 +81,13 @@ else if(projectile.getType() == EntityType.EGG){ @EventHandler(ignoreCancelled = true) public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { - if(!(event.getEntity() instanceof Player)){ + if (!(event.getEntity() instanceof Player)) { return; } - if(event.getDamager() instanceof Player){ + if (event.getDamager() instanceof Player) { Player player = (Player) event.getDamager(); Player damagedPlayer = (Player) event.getEntity(); - if(player.getItemInHand().hasItemMeta() && player.getItemInHand().getItemMeta().getDisplayName().substring(2).equals("Duel")){ + if (player.getItemInHand().hasItemMeta() && player.getItemInHand().getItemMeta().getDisplayName().substring(2).equals("Duel")) { event.setCancelled(true); ActivePerk perk = Cache.getActivePerks().get("Duel"); @@ -102,30 +98,29 @@ public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { HashMap playerDuels = Cache.getPlayerDuels(); - if(playerDuels.containsKey(damagedPlayer)){ + if (playerDuels.containsKey(damagedPlayer)) { String damagedPlayerDuelName = getTeamColour(getPlayerTeam(playerDuels.get(damagedPlayer), true)) + damagedPlayer.getDisplayName(); player.sendMessage( - ChatColor.RED + "This player is already in a duel with " + damagedPlayerDuelName + ChatColor.RED + "!"); + ChatColor.RED + "This player is already in a duel with " + damagedPlayerDuelName + ChatColor.RED + "!"); return; } - if(playerDuels.containsKey(player)){ + if (playerDuels.containsKey(player)) { String playerDuelName = getTeamColour(getPlayerTeam(playerDuels.get(player), true)) + player.getDisplayName(); player.sendMessage( - ChatColor.RED + "You are already in a duel with " + playerDuelName + ChatColor.RED + "!"); + ChatColor.RED + "You are already in a duel with " + playerDuelName + ChatColor.RED + "!"); return; } int woolCost = perk.getWoolCost(); int cooldown = perk.getCooldown(); - if(!subtractWool(player, woolCost)){ + if (!subtractWool(player, woolCost)) { event.setCancelled(true); player.playNote(player.getLocation(), Instrument.PIANO, Note.flat(1, Note.Tone.C)); player.playNote(player.getLocation(), Instrument.PIANO, Note.flat(1, Note.Tone.B)); return; - } - else{ + } else { setItemCooldown(player, perkSlot, itemStack, cooldown); playerDuels.put(damagedPlayer, player); @@ -144,11 +139,11 @@ public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { } } - if(!(event.getDamager() instanceof Projectile)){ + if (!(event.getDamager() instanceof Projectile)) { return; } Projectile projectile = (Projectile) event.getDamager(); - if(projectile.getType() == EntityType.SNOWBALL) { + if (projectile.getType() == EntityType.SNOWBALL) { event.setCancelled(true); Player shooterPlayer; if (!(projectile.getShooter() instanceof Player)) { @@ -168,7 +163,7 @@ public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { projectile.remove(); } - if(projectile.getType() == EntityType.EGG) { + if (projectile.getType() == EntityType.EGG) { Player player = (Player) event.getEntity(); Vector velocity = player.getVelocity().multiply(2); player.setVelocity(velocity); @@ -190,15 +185,14 @@ public void onPlayerFish(PlayerFishEvent event) { perkSlot = perk.getSlotCache(player); - if(!subtractWool(player, woolCost)){ + if (!subtractWool(player, woolCost)) { event.setCancelled(true); hook.remove(); player.playNote(player.getLocation(), Instrument.PIANO, Note.flat(1, Note.Tone.C)); player.playNote(player.getLocation(), Instrument.PIANO, Note.flat(1, Note.Tone.B)); return; - } - else{ - if(cooldown != 0) { + } else { + if (cooldown != 0) { setItemCooldown(player, perkSlot, itemStack, cooldown); } } @@ -214,6 +208,7 @@ public void onPlayerFish(PlayerFishEvent event) { /** * The PlayerMoveEvent Event is duplicated here for the jump Platform perk. + * * @param event the PlayerMoveEvent event * @author SimsumMC */ @@ -230,39 +225,39 @@ public void onPlayerMoveEvent(PlayerMoveEvent event) { nearbyWoolBlocks.add(block); - if(block.getType() != Material.WOOL){ + if (block.getType() != Material.WOOL) { World world = playerLocation.getWorld(); double x = location.getX(); double y = location.getY(); double z = location.getZ(); - nearbyWoolBlocks.add(new Location(world,x-1, y, z).getBlock()); - nearbyWoolBlocks.add(new Location(world,x-1, y, z).getBlock()); - nearbyWoolBlocks.add(new Location(world,x-1, y, z-1).getBlock()); - nearbyWoolBlocks.add(new Location(world, x, y, z+1).getBlock()); + nearbyWoolBlocks.add(new Location(world, x - 1, y, z).getBlock()); + nearbyWoolBlocks.add(new Location(world, x - 1, y, z).getBlock()); + nearbyWoolBlocks.add(new Location(world, x - 1, y, z - 1).getBlock()); + nearbyWoolBlocks.add(new Location(world, x, y, z + 1).getBlock()); nearbyWoolBlocks.add(new Location(world, x, y, z).getBlock()); - nearbyWoolBlocks.add(new Location(world, x,y, z-1).getBlock()); - nearbyWoolBlocks.add(new Location(world,x+1, y, z+1).getBlock()); - nearbyWoolBlocks.add(new Location(world,x+1, y, z).getBlock()); - nearbyWoolBlocks.add(new Location(world,x+1, y, z-1).getBlock()); + nearbyWoolBlocks.add(new Location(world, x, y, z - 1).getBlock()); + nearbyWoolBlocks.add(new Location(world, x + 1, y, z + 1).getBlock()); + nearbyWoolBlocks.add(new Location(world, x + 1, y, z).getBlock()); + nearbyWoolBlocks.add(new Location(world, x + 1, y, z - 1).getBlock()); nearbyWoolBlocks.removeIf(nearbyBlock -> nearbyBlock.getType() != Material.WOOL); } HashMap>> jumpPlatformBlocks = Cache.getJumpPlatformBlocks(); - if(!jumpPlatformBlocks.containsKey(player)){ + if (!jumpPlatformBlocks.containsKey(player)) { return; } ArrayList> playerBlocks = jumpPlatformBlocks.get(player); - if(playerBlocks.isEmpty()){ + if (playerBlocks.isEmpty()) { return; } - for(ArrayList array : playerBlocks){ - for(Block nearbyBlock : nearbyWoolBlocks) { + for (ArrayList array : playerBlocks) { + for (Block nearbyBlock : nearbyWoolBlocks) { if (array.contains(nearbyBlock)) { for (Block existingJumpBlock : array) { existingJumpBlock.setType(Material.AIR); @@ -279,12 +274,12 @@ public void onPlayerMoveEvent(PlayerMoveEvent event) { @EventHandler(ignoreCancelled = true) public void onCreatureSpawn(CreatureSpawnEvent event) { - if(event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.EGG){ + if (event.getSpawnReason() == CreatureSpawnEvent.SpawnReason.EGG) { event.setCancelled(true); } } - public static void load(){ + public static void load() { ActivePerk shears = new ActivePerk(new ItemStack(Material.SHEARS), 0, 0, false, false) .setItemName(ChatColor.AQUA + "Shears") @@ -320,9 +315,9 @@ public static void load(){ enderPearl.register(); - ActivePerk rescuePlatform = new ActivePerk(new ItemStack(Material.BLAZE_ROD), 15, 25, true){ + ActivePerk rescuePlatform = new ActivePerk(new ItemStack(Material.BLAZE_ROD), 15, 25, true) { @Override - public void onExecute(PlayerInteractEvent event, Player player){ + public void onExecute(PlayerInteractEvent event, Player player) { Location playerLocation = player.getLocation(); DyeColor teamColor = findTeamDyeColor(player); @@ -331,34 +326,34 @@ public void onExecute(PlayerInteractEvent event, Player player){ double y = playerLocation.getY(); double z = playerLocation.getZ(); - ArrayList locations = new ArrayList(){{ - add(new Location(world, x, y -5, z)); - add(new Location(world, x, y -5, z+1)); - add(new Location(world, x, y -5, z+2)); - add(new Location(world, x, y -5, z-1)); - add(new Location(world, x, y -5, z-2)); - add(new Location(world, x+1, y -5, z)); - add(new Location(world, x+1, y -5, z+1)); - add(new Location(world, x+1, y -5, z+2)); - add(new Location(world, x+1, y -5, z-1)); - add(new Location(world, x+1, y -5, z-2)); - add(new Location(world, x+2, y -5, z)); - add(new Location(world, x+2, y -5, z+1)); - add(new Location(world, x+2, y -5, z-1)); - add(new Location(world, x-1, y -5, z)); - add(new Location(world, x-1, y -5, z+1)); - add(new Location(world, x-1, y -5, z+2)); - add(new Location(world, x-1, y -5, z-1)); - add(new Location(world, x-1, y -5, z-2)); - add(new Location(world, x-2, y -5, z)); - add(new Location(world, x-2, y -5, z+1)); - add(new Location(world, x-2, y -5, z-1)); + ArrayList locations = new ArrayList() {{ + add(new Location(world, x, y - 5, z)); + add(new Location(world, x, y - 5, z + 1)); + add(new Location(world, x, y - 5, z + 2)); + add(new Location(world, x, y - 5, z - 1)); + add(new Location(world, x, y - 5, z - 2)); + add(new Location(world, x + 1, y - 5, z)); + add(new Location(world, x + 1, y - 5, z + 1)); + add(new Location(world, x + 1, y - 5, z + 2)); + add(new Location(world, x + 1, y - 5, z - 1)); + add(new Location(world, x + 1, y - 5, z - 2)); + add(new Location(world, x + 2, y - 5, z)); + add(new Location(world, x + 2, y - 5, z + 1)); + add(new Location(world, x + 2, y - 5, z - 1)); + add(new Location(world, x - 1, y - 5, z)); + add(new Location(world, x - 1, y - 5, z + 1)); + add(new Location(world, x - 1, y - 5, z + 2)); + add(new Location(world, x - 1, y - 5, z - 1)); + add(new Location(world, x - 1, y - 5, z - 2)); + add(new Location(world, x - 2, y - 5, z)); + add(new Location(world, x - 2, y - 5, z + 1)); + add(new Location(world, x - 2, y - 5, z - 1)); }}; - for(Location location : locations){ + for (Location location : locations) { Block block = location.getBlock(); Material material = block.getType(); - if(material != Material.AIR){ + if (material != Material.AIR) { continue; } block.setType(Material.WOOL); @@ -366,7 +361,7 @@ public void onExecute(PlayerInteractEvent event, Player player){ } } }.setItemName(ChatColor.AQUA + "Rescue Platform").addEnchantment(Enchantment.DURABILITY, true) - .setDescription("Places blocks under you."); + .setDescription("Places blocks under you."); rescuePlatform.register(); @@ -379,14 +374,14 @@ public void onExecute(PlayerInteractEvent event, Player player){ ActivePerk knockbackStick = new ActivePerk(new ItemStack(Material.STICK), 0, 0, false) .setItemName(ChatColor.AQUA + "Knockback Stick") - .addEnchantment(Enchantment.KNOCKBACK,100, false) + .addEnchantment(Enchantment.KNOCKBACK, 100, false) .setDescription("Best weapon in the game."); knockbackStick.register(); - ActivePerk jumpPlatform = new ActivePerk(new ItemStack(Material.SLIME_BALL), 15, 25, true){ + ActivePerk jumpPlatform = new ActivePerk(new ItemStack(Material.SLIME_BALL), 15, 25, true) { @Override - public void onExecute(PlayerInteractEvent event, Player player){ + public void onExecute(PlayerInteractEvent event, Player player) { Location playerLocation = player.getLocation(); DyeColor teamColor = findTeamDyeColor(player); @@ -395,12 +390,12 @@ public void onExecute(PlayerInteractEvent event, Player player){ double y = playerLocation.getY(); double z = playerLocation.getZ(); - ArrayList locations = new ArrayList(){{ - add(new Location(world, x, y -5, z)); - add(new Location(world, x, y -5, z+1)); - add(new Location(world, x, y -5, z-1)); - add(new Location(world, x+1, y -5, z)); - add(new Location(world, x-1, y -5, z)); + ArrayList locations = new ArrayList() {{ + add(new Location(world, x, y - 5, z)); + add(new Location(world, x, y - 5, z + 1)); + add(new Location(world, x, y - 5, z - 1)); + add(new Location(world, x + 1, y - 5, z)); + add(new Location(world, x - 1, y - 5, z)); }}; HashMap>> jumpPlatformBlocks = Cache.getJumpPlatformBlocks(); @@ -411,11 +406,11 @@ public void onExecute(PlayerInteractEvent event, Player player){ ArrayList newPlayerBlocks = new ArrayList<>(); - for(Location location : locations){ + for (Location location : locations) { Block block = location.getBlock(); Material material = block.getType(); - if(material != Material.AIR){ + if (material != Material.AIR) { continue; } @@ -433,7 +428,7 @@ public void onExecute(PlayerInteractEvent event, Player player){ } }.setItemName(ChatColor.AQUA + "Jump Platform").addEnchantment(Enchantment.DURABILITY, true) - .setDescription("Boosts yourself up."); + .setDescription("Boosts yourself up."); jumpPlatform.register(); @@ -443,19 +438,19 @@ public void onExecute(PlayerInteractEvent event, Player player){ grapplingHook.register(); - ActivePerk homeTeleport = new ActivePerk(new ItemStack(Material.WATCH), 30, 25, true){ + ActivePerk homeTeleport = new ActivePerk(new ItemStack(Material.WATCH), 30, 25, true) { @Override public void onExecute(PlayerInteractEvent event, Player player) { teleportPlayerTeamSpawn(player); } }.setItemName(ChatColor.AQUA + "Home Teleport").addEnchantment(Enchantment.DURABILITY, true) - .setDescription("Teleports you home."); + .setDescription("Teleports you home."); homeTeleport.register(); - ActivePerk rescuePod = new ActivePerk(new ItemStack(Material.FEATHER), 15, 30, true){ + ActivePerk rescuePod = new ActivePerk(new ItemStack(Material.FEATHER), 15, 30, true) { @Override - public void onExecute(PlayerInteractEvent event, Player player){ + public void onExecute(PlayerInteractEvent event, Player player) { Location playerLocation = player.getLocation(); DyeColor teamColor = findTeamDyeColor(player); @@ -464,25 +459,25 @@ public void onExecute(PlayerInteractEvent event, Player player){ double y = playerLocation.getY(); double z = playerLocation.getZ(); - ArrayList locations = new ArrayList(){{ - add(new Location(world, x, y -1, z)); - add(new Location(world, x, y+2 , z)); - add(new Location(world, x, y , z+1)); - add(new Location(world, x, y , z-1)); - add(new Location(world, x+1, y , z)); - add(new Location(world, x-1, y , z)); - add(new Location(world, x, y+1, z+1)); - add(new Location(world, x, y+1, z-1)); - add(new Location(world, x+1, y+1, z)); - add(new Location(world, x-1, y+1, z)); + ArrayList locations = new ArrayList() {{ + add(new Location(world, x, y - 1, z)); + add(new Location(world, x, y + 2, z)); + add(new Location(world, x, y, z + 1)); + add(new Location(world, x, y, z - 1)); + add(new Location(world, x + 1, y, z)); + add(new Location(world, x - 1, y, z)); + add(new Location(world, x, y + 1, z + 1)); + add(new Location(world, x, y + 1, z - 1)); + add(new Location(world, x + 1, y + 1, z)); + add(new Location(world, x - 1, y + 1, z)); }}; player.teleport(new Location(world, x, y, z)); - for(Location location : locations){ + for (Location location : locations) { Block block = location.getBlock(); Material material = block.getType(); - if(material != Material.AIR){ + if (material != Material.AIR) { continue; } block.setType(Material.WOOL); @@ -490,7 +485,7 @@ public void onExecute(PlayerInteractEvent event, Player player){ } } }.setItemName(ChatColor.AQUA + "Rescue Pod").addEnchantment(Enchantment.DURABILITY, true) - .setDescription("Places blocks around you."); + .setDescription("Places blocks around you."); rescuePod.register(); diff --git a/src/main/java/woolbattle/woolbattle/perks/AllPassivePerks.java b/src/main/java/woolbattle/woolbattle/perks/AllPassivePerks.java index 3df375c..cc1bef1 100644 --- a/src/main/java/woolbattle/woolbattle/perks/AllPassivePerks.java +++ b/src/main/java/woolbattle/woolbattle/perks/AllPassivePerks.java @@ -31,67 +31,69 @@ public class AllPassivePerks { ChatColor.AQUA + "Wool Duplication", false, "Increases the amount of wool you get" - ){ - final int factor = (2)-1; + ) { + final int factor = (2) - 1; @Override public void functionality(H event) { assert event instanceof BlockBreakEvent; Player p = ((BlockBreakEvent) event).getPlayer(); - ItemStack wool = new ItemStack(Material.WOOL, Config.givenWoolAmount*factor, findTeamDyeColor(p).getWoolData()); + ItemStack wool = new ItemStack(Material.WOOL, Config.givenWoolAmount * factor, findTeamDyeColor(p).getWoolData()); AtomicInteger amount = new AtomicInteger(); p.getInventory().spliterator().tryAdvance(itemStack -> amount.addAndGet(itemStack.getAmount())); - if(amount.get() == (Config.maxStacks * 64)){ + if (amount.get() == (Config.maxStacks * 64)) { return; - } - else if (amount.get() + (Config.givenWoolAmount * (factor)) >(Config.maxStacks * 64)) { - wool.setAmount(((Config.maxStacks * 64)-amount.get())); + } else if (amount.get() + (Config.givenWoolAmount * (factor)) > (Config.maxStacks * 64)) { + wool.setAmount(((Config.maxStacks * 64) - amount.get())); } p.getInventory().addItem(wool); } }; - /**Method setting up the system of passive perks. Over the course of the method, instances of the passive perk are added to the HashMap of + /** + * Method setting up the system of passive perks. Over the course of the method, instances of the passive perk are added to the HashMap of * passive perks in Cache.java and assigned to potential owners through a query * toward the db respectively + * * @author Servaturus */ - public static void load(){ + public static void load() { woolMultiplication.register(); assignPlayersToPerks(); } - public static void assignPlayersToPerks(){ + public static void assignPlayersToPerks() { MongoDatabase db = Main.getMongoDatabase(); MongoCollection collection = db.getCollection("playerPerks"); - HashMap> passivePerks = Cache.getPassivePerks();; + HashMap> passivePerks = Cache.getPassivePerks(); + ; HashMap> newPassivePerks = new HashMap<>(); FindIterable iterable = collection.find(); - MongoCursor cursor = iterable.iterator(); + MongoCursor cursor = iterable.iterator(); - for(PassivePerk perk : passivePerks.values()){ + for (PassivePerk perk : passivePerks.values()) { ArrayList players = new ArrayList<>(); //iterates over the elements of the fetched document, creates a Player object through the stored information //, additionally to that stores players in possession of the perk to its respective instance's array of players. - try{ - while(cursor.hasNext()){ + try { + while (cursor.hasNext()) { Document document = cursor.next(); - if(document.get("passive") == null || !document.get("passive").equals(perk.getName().substring(2))){ + if (document.get("passive") == null || !document.get("passive").equals(perk.getName().substring(2))) { continue; } Player player = Bukkit.getPlayer(UUID.fromString((String) document.get("_id"))); - if(document.get("passive").equals(perk.getName().substring(2)) && player != null){ + if (document.get("passive").equals(perk.getName().substring(2)) && player != null) { players.add(player); } } - }finally{ + } finally { cursor.close(); } @@ -99,11 +101,12 @@ public static void assignPlayersToPerks(){ newPassivePerks.put(perk.getName().substring(2), perk); - if(perk.isOverwriteEvent()){ - try{ + if (perk.isOverwriteEvent()) { + try { Bukkit.getPluginManager().registerEvents(perk, Main.getInstance()); - }catch(IllegalPluginAccessException ignored){} + } catch (IllegalPluginAccessException ignored) { + } } } diff --git a/src/main/java/woolbattle/woolbattle/perks/PassivePerk.java b/src/main/java/woolbattle/woolbattle/perks/PassivePerk.java index 0ba31e4..4b74eb3 100644 --- a/src/main/java/woolbattle/woolbattle/perks/PassivePerk.java +++ b/src/main/java/woolbattle/woolbattle/perks/PassivePerk.java @@ -4,7 +4,6 @@ import com.mongodb.client.MongoDatabase; import org.bson.Document; import org.bukkit.Bukkit; -import org.bukkit.OfflinePlayer; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; @@ -33,11 +32,11 @@ public HandlerList getHandlers() { } }; E e = (E) g; - private final Class type = (Class) e.getClass(); + private final Class type = (Class) e.getClass(); private ArrayList players = new ArrayList<>(); - public PassivePerk(ItemStack item, String name, int delayInTicks, String description){ + public PassivePerk(ItemStack item, String name, int delayInTicks, String description) { this.delay = delayInTicks; this.name = name; this.item = item; @@ -51,13 +50,13 @@ public PassivePerk(ItemStack item, String name, int delayInTicks, String descrip collection.listIndexes().forEach((Consumer) document -> { assert document instanceof Document; - if(((Document) document).get("passive").equals(name)){ + if (((Document) document).get("passive").equals(name)) { players.add(Bukkit.getPlayer((UUID) ((Document) document).get("_id"))); } }); } - public PassivePerk (ItemStack item, String name, boolean overwriteEvent, String description){ + public PassivePerk(ItemStack item, String name, boolean overwriteEvent, String description) { this.name = name; this.item = item; ItemMeta meta = item.getItemMeta(); @@ -71,24 +70,25 @@ public PassivePerk (ItemStack item, String name, boolean overwriteEvent, String collection.listIndexes().forEach((Consumer) document -> { assert document instanceof Document; - if(((Document) document).get("passive") != null && ((Document) document).get("passive").equals(name)){ + if (((Document) document).get("passive") != null && ((Document) document).get("passive").equals(name)) { players.add(Bukkit.getPlayer((UUID) ((Document) document).get("_id"))); } }); } - public void functionality(){ + public void functionality() { } - public void functionality(S event){} + public void functionality(S event) { + } - public final void loop(){ - if(delay == 0){ + public final void loop() { + if (delay == 0) { return; } - new BukkitRunnable(){ + new BukkitRunnable() { @Override public void run() { functionality(); @@ -111,17 +111,35 @@ public Class getType() { return type; } - public String getName() {return name;} - public ItemStack getItem() {return item;} - public int getDelay() {return delay;} - public boolean isOverwriteEvent() {return overwriteEvent;} + public String getName() { + return name; + } + + public ItemStack getItem() { + return item; + } + + public int getDelay() { + return delay; + } + + public boolean isOverwriteEvent() { + return overwriteEvent; + } + + public ArrayList getPlayers() { + return players; + } - public ArrayList getPlayers(){return players;} - public void setPlayers(ArrayList players) {this.players = players;} + public void setPlayers(ArrayList players) { + this.players = players; + } - public boolean hasPlayer(Player p){return players.contains(p);} + public boolean hasPlayer(Player p) { + return players.contains(p); + } - public String getDescription(){ + public String getDescription() { return description; } } \ No newline at end of file diff --git a/src/main/java/woolbattle/woolbattle/stats/StatsCommand.java b/src/main/java/woolbattle/woolbattle/stats/StatsCommand.java index 44c4a4b..aa603ed 100644 --- a/src/main/java/woolbattle/woolbattle/stats/StatsCommand.java +++ b/src/main/java/woolbattle/woolbattle/stats/StatsCommand.java @@ -12,11 +12,11 @@ public class StatsCommand implements CommandExecutor { @Override public boolean onCommand(CommandSender commandSender, Command command, String s, String[] strings) { - if(!(commandSender instanceof Player)){ + if (!(commandSender instanceof Player)) { commandSender.sendMessage(ChatColor.RED + "You can only use this command as a normal player!"); return true; } - if(strings.length == 0){ + if (strings.length == 0) { commandSender.sendMessage(StatsSystem.getPlayerStatsFormatted((OfflinePlayer) commandSender)); return true; } diff --git a/src/main/java/woolbattle/woolbattle/stats/StatsSystem.java b/src/main/java/woolbattle/woolbattle/stats/StatsSystem.java index 055be0f..8ea43be 100644 --- a/src/main/java/woolbattle/woolbattle/stats/StatsSystem.java +++ b/src/main/java/woolbattle/woolbattle/stats/StatsSystem.java @@ -20,10 +20,11 @@ public class StatsSystem { /** * A method that adds a perk usage to the cache. + * * @param player - the player that used the perk * @author SimsumMC */ - public static void addActivePerkUsage(Player player){ + public static void addActivePerkUsage(Player player) { HashMap> playerStats = Cache.getPlayerStats(); HashMap stats = playerStats.get(player); @@ -37,15 +38,16 @@ public static void addActivePerkUsage(Player player){ /** * A method that adds the default values in the Cache. + * * @author SimsumMC */ - public static void addDefaultStats(){ + public static void addDefaultStats() { HashMap> playerStats = Cache.getPlayerStats(); - for(Player player : Bukkit.getOnlinePlayers()){ - HashMap stats = new HashMap(){{ + for (Player player : Bukkit.getOnlinePlayers()) { + HashMap stats = new HashMap() {{ put("games", 1); - put("wins", 0); + put("wins", 0); put("kills", 0); put("deaths", 0); put("streaks", 0); @@ -60,29 +62,32 @@ public static void addDefaultStats(){ /** * A method that saves the stats (from Cache) from all players of the round in the database. + * + * @param winnerTeam - * @author SimsumMC */ - public static void saveAllPlayerStats(String winnerTeam){ + public static void saveAllPlayerStats(String winnerTeam) { HashMap> playerStats = Cache.getPlayerStats(); - for(Player player : Cache.getTeamMembers().get(winnerTeam.substring(2))){ + for (Player player : Cache.getTeamMembers().get(winnerTeam.substring(2))) { HashMap stats = playerStats.get(player); stats.put("wins", 1); playerStats.put(player, stats); } - for(Player player : playerStats.keySet()){ + for (Player player : playerStats.keySet()) { savePlayerStats(player, playerStats.get(player)); } } /** * A method that saves the stats (from Cache) of a given player in the database. - * @param player - The player that stats get updated in the database + * + * @param player - The player that stats get updated in the database * @param playerStats - The stats of the player for the last game * @author SimsumMC */ - public static void savePlayerStats(Player player, HashMap playerStats){ + public static void savePlayerStats(Player player, HashMap playerStats) { int games = playerStats.get("games"); int wins = playerStats.get("wins"); @@ -96,9 +101,9 @@ public static void savePlayerStats(Player player, HashMap playe Document foundDocument = collection.find(eq("_id", player.getUniqueId().toString())).first(); - if(foundDocument == null){ + if (foundDocument == null) { - HashMap newPlayerStats = new HashMap(){{ + HashMap newPlayerStats = new HashMap() {{ put("_id", player.getUniqueId().toString()); put("games", games); put("wins", wins); @@ -110,8 +115,7 @@ public static void savePlayerStats(Player player, HashMap playe Document document = new Document(newPlayerStats); collection.insertOne(document); - } - else{ + } else { int totalGames = (int) foundDocument.get("games") + games; int totalWins = (int) foundDocument.get("wins") + wins; int totalKills = (int) foundDocument.get("kills") + kills; @@ -128,7 +132,7 @@ public static void savePlayerStats(Player player, HashMap playe Updates.set("used_perks", totalUsedPerks) ); - Document query = new Document().append("_id", player.getUniqueId().toString()); + Document query = new Document().append("_id", player.getUniqueId().toString()); collection.updateOne(query, updates); } @@ -136,6 +140,7 @@ public static void savePlayerStats(Player player, HashMap playe /** * A method that fetches the stats from a given player from the database and returns it as a beautiful string. + * * @param player- The player that stats get returned as a formatted string * @author SimsumMC */ diff --git a/src/main/java/woolbattle/woolbattle/team/TeamSystem.java b/src/main/java/woolbattle/woolbattle/team/TeamSystem.java index 499ad62..d44fb73 100644 --- a/src/main/java/woolbattle/woolbattle/team/TeamSystem.java +++ b/src/main/java/woolbattle/woolbattle/team/TeamSystem.java @@ -23,6 +23,7 @@ public class TeamSystem implements Listener { /** * A method that handles the team division. + * * @author Beelzebub */ public static void teamsOnStart() { @@ -31,14 +32,14 @@ public static void teamsOnStart() { ArrayList onlinePlayers = new ArrayList<>(Bukkit.getOnlinePlayers()); ArrayList teamLessPlayers = new ArrayList<>(); - for (int i = Bukkit.getOnlinePlayers().size() - 1; i>=0; i--) { + for (int i = Bukkit.getOnlinePlayers().size() - 1; i >= 0; i--) { Player player = onlinePlayers.get(i); if (TeamSystem.getPlayerTeam(player, true).equals("§cNot selected")) { teamLessPlayers.add(player); } } - for (int i = teamLessPlayers.size() - 1; i>=0; i--) { + for (int i = teamLessPlayers.size() - 1; i >= 0; i--) { int[] sizes = { getTeamMembers().get("Red").size(), getTeamMembers().get("Blue").size(), @@ -47,24 +48,27 @@ public static void teamsOnStart() { }; int smallestNumber = 0; int temp = sizes[0]; - for(int a=0;a 0) { switch (i) { - case 0: teamWithMembers = "Red"; break; - case 1: teamWithMembers = "Blue"; break; - case 2: teamWithMembers = "Green"; break; - case 3: teamWithMembers = "Yellow"; break; + case 0: + teamWithMembers = "Red"; + break; + case 1: + teamWithMembers = "Blue"; + break; + case 2: + teamWithMembers = "Green"; + break; + case 3: + teamWithMembers = "Yellow"; + break; } numActiveTeams += 1; } @@ -106,8 +118,7 @@ public static void teamsOnStart() { members.put(teamWithMembers, member); Cache.setTeamMembers(members); - } - else { + } else { HashMap> members = getTeamMembers(); ArrayList newMem = new ArrayList() {{ @@ -127,6 +138,7 @@ public static void teamsOnStart() { /** * A method that opens the Inventory for the team selection for the given player. + * * @param player - the player that gets the inventory "shown" (opened) * @author Beelzebub */ @@ -200,19 +212,20 @@ public static void showTeamSelectionInventory(Player player) { /** * An event that gets executed whenever an entity damages another entity to prevent hitting team members. + * * @param event - the EntityDamageByEntityEvent * @author Beelzebub & SimsumMC */ @EventHandler - public void onEntityDamageByEntity(EntityDamageByEntityEvent event){ - if(!(event.getEntity() instanceof Player)){ + public void onEntityDamageByEntity(EntityDamageByEntityEvent event) { + if (!(event.getEntity() instanceof Player)) { return; } - if(event.getDamager() instanceof Player){ + if (event.getDamager() instanceof Player) { HashMap playerDuels = Cache.getPlayerDuels(); Player player = (Player) event.getEntity(); - if(playerDuels.containsKey(player) && (playerDuels.get(player) != event.getDamager())){ + if (playerDuels.containsKey(player) && (playerDuels.get(player) != event.getDamager())) { event.setCancelled(true); String duelPlayerName = getTeamColour(getPlayerTeam(playerDuels.get(player), true)) + ((Player) event.getEntity()).getDisplayName(); @@ -221,7 +234,7 @@ public void onEntityDamageByEntity(EntityDamageByEntityEvent event){ return; } player = (Player) event.getDamager(); - if(playerDuels.containsKey(player) && (playerDuels.get(player) != event.getEntity())){ + if (playerDuels.containsKey(player) && (playerDuels.get(player) != event.getEntity())) { event.setCancelled(true); String duelPlayerName = getTeamColour(getPlayerTeam(playerDuels.get(player), true)) + ((Player) event.getEntity()).getDisplayName(); @@ -239,13 +252,12 @@ public void onEntityDamageByEntity(EntityDamageByEntityEvent event){ Player damager; Player damaged = (Player) event.getEntity(); - if(event.getDamager() instanceof Arrow){ + if (event.getDamager() instanceof Arrow) { Arrow arrow = (Arrow) event.getDamager(); damager = (Player) arrow.getShooter(); - } - else{ - if(!(event.getDamager() instanceof Player)){ + } else { + if (!(event.getDamager() instanceof Player)) { return; } damager = (Player) event.getDamager(); @@ -260,8 +272,8 @@ public void onEntityDamageByEntity(EntityDamageByEntityEvent event){ return; } HashMap spawnProtection = Cache.getSpawnProtection(); - if(spawnProtection.containsKey(damaged) && (unixTime < spawnProtection.get(damaged))){ - if(damager.getUniqueId() != damaged.getUniqueId()){ + if (spawnProtection.containsKey(damaged) && (unixTime < spawnProtection.get(damaged))) { + if (damager.getUniqueId() != damaged.getUniqueId()) { damager.sendMessage("§cThe player has spawn protection!"); } event.setCancelled(true); @@ -271,8 +283,9 @@ public void onEntityDamageByEntity(EntityDamageByEntityEvent event){ /** * A Method that returns the team of the player with the colour as a string. + * * @param player the player which team gets returned - * @param raw a boolean whether the method should return a raw string or a colored one + * @param raw a boolean whether the method should return a raw string or a colored one * @return the team name as a string if any, else "§cNot selected" * @author SimsumMC */ @@ -281,13 +294,12 @@ public static String getPlayerTeam(Player player, boolean raw) { String teamName = ChatColor.RED + "Not selected"; HashMap> data = getTeamMembers(); - for(String key : data.keySet()){ + for (String key : data.keySet()) { ArrayList players = data.get(key); - if(players.contains(player)){ - if(!raw){ + if (players.contains(player)) { + if (!raw) { teamName = getTeamColour(key).toString(); - } - else{ + } else { teamName = ""; } teamName += key; @@ -300,15 +312,16 @@ public static String getPlayerTeam(Player player, boolean raw) { /** * A Method that removes the player from the current team + * * @param player which gets removed from his team * @author SimsumMC */ public static void removePlayerTeam(Player player) { HashMap> teamMembers = getTeamMembers(); - for(String key : teamMembers.keySet()){ + for (String key : teamMembers.keySet()) { ArrayList players = teamMembers.get(key); - if(players.contains(player)){ + if (players.contains(player)) { players.remove(player); teamMembers.put(key, players); Cache.setTeamMembers(teamMembers); @@ -319,12 +332,13 @@ public static void removePlayerTeam(Player player) { /** * A Method that returns the team of the player with the colour as a ChatColor Enum. + * * @param team a S * @return the colour of the team * @author SimsumMC */ public static ChatColor getTeamColour(String team) { - switch(team){ + switch (team) { case "Blue": return ChatColor.DARK_BLUE; case "Green": @@ -338,12 +352,13 @@ public static ChatColor getTeamColour(String team) { /** * Method that returns the team-color of the specified player as a DyeColor. + * * @param p The player to get the team-color of * @author Servaturus */ - public static DyeColor findTeamDyeColor(Player p){ + public static DyeColor findTeamDyeColor(Player p) { String team = getPlayerTeam(p, true); - switch(team){ + switch (team) { case "Blue": return DyeColor.BLUE; case "Red": @@ -359,12 +374,13 @@ public static DyeColor findTeamDyeColor(Player p){ /** * Method that returns the team-color of the specified player as a Color. + * * @param p The player to get the team-color of * @author Servaturus */ - public static Color findTeamColor(Player p){ + public static Color findTeamColor(Player p) { String team = getPlayerTeam(p, true); - switch(team){ + switch (team) { case "Blue": return Color.BLUE; case "Red":